Leetcode 1005. Maximize Sum Of Array After K Negations
Given an integer array nums
and an integer k
, modify the array in the following way:
choose an index
i
and replacenums[i]
with-nums[i]
.
You should apply this process exactly k
times. You may choose the same index i
multiple times.
Return the largest possible sum of the array after modifying it in this way.
Example 1:
Input: nums = [4,2,3], k = 1Output: 5Explanation: Choose index 1 and nums becomes [4,-2,3].
Example 2:
Input: nums = [3,-1,0,2], k = 3Output: 6Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
Input: nums = [2,-3,-1,5,-4], k = 2Output: 13Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Constraints:
1 <= nums.length <= 104
-100 <= nums[i] <= 100
1 <= k <= 104
Easy 题目,如果是小于0的,就取绝对值,如果等于0,说明前面小于0的就已经遍历完了,就可以直接求和了。
但是如果所有的都遍历完了,k还是大于0的话,那么就只能对数组排序一下,然后对第一个值取反。一直取。即可。
然后求和;
Runtime: 2 ms, faster than 98.19% of Java online submissions for Maximize Sum Of Array After K Negations.
Memory Usage: 41.8 MB, less than 62.99% of Java online submissions for Maximize Sum Of Array After K Negations.