3
3
import java .util .Arrays ;
4
4
import java .util .PriorityQueue ;
5
5
6
- /**
7
- * 1005. Maximize Sum Of Array After K Negations
8
- *
9
- * Given an array A of integers, we must modify the array in the following way:
10
- * we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.
11
- * (We may choose the same index i multiple times.)
12
- *
13
- * Return the largest possible sum of the array after modifying it in this way.
14
- *
15
- * Example 1:
16
- * Input: A = [4,2,3], K = 1
17
- * Output: 5
18
- * Explanation: Choose indices (1,) and A becomes [4,-2,3].
19
- *
20
- * Example 2:
21
- * Input: A = [3,-1,0,2], K = 3
22
- * Output: 6
23
- * Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].
24
- * Example 3:
25
- *
26
- * Input: A = [2,-3,-1,5,-4], K = 2
27
- * Output: 13
28
- * Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].
29
- *
30
- *
31
- * Note:
32
- *
33
- * 1 <= A.length <= 10000
34
- * 1 <= K <= 10000
35
- * -100 <= A[i] <= 100
36
- * */
37
6
public class _1005 {
38
7
public static class Solution1 {
39
- /**credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252228/A-very-simple-java-solution*/
8
+ /**
9
+ * credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252228/A-very-simple-java-solution
10
+ */
40
11
public int largestSumAfterKNegations (int [] A , int K ) {
41
12
PriorityQueue <Integer > minHeap = new PriorityQueue <>();
42
13
for (int num : A ) {
@@ -54,7 +25,9 @@ public int largestSumAfterKNegations(int[] A, int K) {
54
25
}
55
26
56
27
public static class Solution2 {
57
- /**credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252254/JavaC%2B%2BPython-Sort*/
28
+ /**
29
+ * credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252254/JavaC%2B%2BPython-Sort
30
+ */
58
31
public int largestSumAfterKNegations (int [] A , int K ) {
59
32
Arrays .sort (A );
60
33
for (int i = 0 ; i < A .length && K > 0 && A [i ] < 0 ; i ++, K --) {
0 commit comments