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 replace?nums[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的就已經(jīng)遍歷完了,就可以直接求和了。
但是如果所有的都遍歷完了,k還是大于0的話,那么就只能對數(shù)組排序一下,然后對第一個值取反。一直取。即可。
然后求和;
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.