给你一个整数数组 nums
和一个整数 k
,按以下方法修改该数组:
- 选择某个下标
i
并将nums[i]
替换为-nums[i]
。
重复这个过程恰好 k
次。可以多次选择同一个下标 i
。
以这种方式修改数组后,返回数组 可能的最大和 。
示例 1:
输入:nums = [4,2,3], k = 1 输出:5 解释:选择下标 1 ,nums 变为 [4,-2,3] 。
示例 2:
输入:nums = [3,-1,0,2], k = 3 输出:6 解释:选择下标 (1, 2, 2) ,nums 变为 [3,1,0,2] 。
示例 3:
输入:nums = [2,-3,-1,5,-4], k = 2 输出:13 解释:选择下标 (1, 4) ,nums 变为 [2,3,-1,5,4] 。
提示:
1 <= nums.length <= 104
-100 <= nums[i] <= 100
1 <= k <= 104
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
counter = Counter(nums)
ans = sum(nums)
for i in range(-100, 0):
if counter[i]:
ops = min(counter[i], k)
ans -= i * ops * 2
counter[i] -= ops
counter[-i] += ops
k -= ops
if k == 0:
break
if k > 0 and k % 2 == 1 and not counter[0]:
for i in range(1, 101):
if counter[i]:
ans -= 2 * i
break
return ans
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
int ans = 0;
Map<Integer, Integer> counter = new HashMap<>();
for (int num : nums) {
ans += num;
counter.put(num, counter.getOrDefault(num, 0) + 1);
}
for (int i = -100; i < 0; ++i) {
if (counter.getOrDefault(i, 0) > 0) {
int ops = Math.min(counter.get(i), k);
ans -= (i * ops * 2);
counter.put(i, counter.getOrDefault(i, 0) - ops);
counter.put(-i, counter.getOrDefault(-i, 0) + ops);
k -= ops;
if (k == 0) {
break;
}
}
}
if (k > 0 && (k % 2) == 1 && counter.get(0) == null) {
for (int i = 1; i < 101; ++i) {
if (counter.getOrDefault(i, 0) > 0) {
ans -= 2 * i;
break;
}
}
}
return ans;
}
}
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
unordered_map<int, int> counter;
for (int num : nums) ++counter[num];
int ans = accumulate(nums.begin(), nums.end(), 0);
for (int i = -100; i < 0; ++i) {
if (counter[i]) {
int ops = min(counter[i], k);
ans -= (i * ops * 2);
counter[i] -= ops;
counter[-i] += ops;
k -= ops;
if (k == 0) break;
}
}
if (k > 0 && k % 2 == 1 && !counter[0]) {
for (int i = 1; i < 101; ++i) {
if (counter[i]) {
ans -= 2 * i;
break;
}
}
}
return ans;
}
};
func largestSumAfterKNegations(nums []int, k int) int {
ans := 0
counter := make(map[int]int)
for _, num := range nums {
ans += num
counter[num]++
}
for i := -100; i < 0; i++ {
if counter[i] > 0 {
ops := min(counter[i], k)
ans -= (i * ops * 2)
counter[i] -= ops
counter[-i] += ops
k -= ops
if k == 0 {
break
}
}
}
if k > 0 && k%2 == 1 && counter[0] == 0 {
for i := 1; i < 101; i++ {
if counter[i] > 0 {
ans -= 2 * i
break
}
}
}
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}