> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-23-2022-1005.md).

# 02/23/2022 1005

class Solution { public int largestSumAfterKNegations(int\[] nums, int k) {

```
    PriorityQueue<Integer> bq = new PriorityQueue<>();
    for(int n: nums){
        bq.add(n);
}
    while(k > 0){
        bq.add(-bq.poll());
        k--;
    }
    int sum = 0;
    
    for(int i = 0; i <nums.length; i++){
        
        sum += bq.poll();

    }
    return sum;
}
```

}

Method: Convert the int array to Integer array and then sort it by the absolute value with descending order. Iterate the array and if the element is negative and k > 0, negate it. After the for loop, if k > 0. Then check if it is odd. If it is odd, we only need to negate the last element. If it is even, we don't do anything. Finally get the sum of the elements.

Time O(nlogn)

Space O(n)

class Solution { public int largestSumAfterKNegations(int\[] nums, int k) {

```
    Integer[]  newNums = new Integer[nums.length];
    
    for (int i = 0; i < newNums.length; i++){
        newNums[i] = nums[i];
    }
    
    Arrays.sort(newNums, (a,b) -> Math.abs(b) - Math.abs(a));
    
    for(int i = 0; i < newNums.length; i++){
        if(newNums[i] < 0 && k > 0){
            newNums[i] = -newNums[i];
            k--;
        }
    }
    
    if(k % 2 == 1){
        newNums[newNums.length -1] = - newNums[newNums.length - 1];
    }
    int sum = 0;
    for(int a: newNums){
        sum += a;
    }
    return sum;
    
}
```

}
