leetcode 1005. Maximize Sum Of Array After K Negations
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue();
for (int num: nums){
heap.offer(num);
}
while (k-- >0){
heap.offer(-heap.poll()); //poll the smallest of minheap and negate it, then put it back, it will not be the smallest of the new minheap anymore, keep going till k==0
}
int sum=0;
while(!heap.isEmpty()){
sum+=heap.poll();
}
return sum;
}
}