|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.PriorityQueue; |
| 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]. |
<
8000
td data-grid-cell-id="diff-8c78f76c11cba8c956bf5649fb47c89390e525ce1b8159f752442faa33f6e5b4-empty-24-0" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionNum-bgColor, var(--diffBlob-addition-bgColor-num));text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative left-side">
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 | +public class _1005 { |
| 38 | + public static class Solution1 { |
| 39 | + /**credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252228/A-very-simple-java-solution*/ |
| 40 | + public int largestSumAfterKNegations(int[] A, int K) { |
| 41 | + PriorityQueue<Integer> minHeap = new PriorityQueue<>(); |
| 42 | + for (int num : A) { |
| 43 | + minHeap.offer(num); |
| 44 | + } |
| 45 | + while (K-- > 0) { |
| 46 | + minHeap.offer(-minHeap.poll()); |
| 47 | + } |
| 48 | + int sum = 0; |
| 49 | + while (!minHeap.isEmpty()) { |
| 50 | + sum += minHeap.poll(); |
| 51 | + } |
| 52 | + return sum; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public static class Solution2 { |
| 57 | + /**credit: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252254/JavaC%2B%2BPython-Sort*/ |
| 58 | + public int largestSumAfterKNegations(int[] A, int K) { |
| 59 | + Arrays.sort(A); |
| 60 | + for (int i = 0; i < A.length && K > 0 && A[i] < 0; i++, K--) { |
| 61 | + A[i] = -A[i]; |
| 62 | + } |
| 63 | + int sum = 0; |
| 64 | + int min = Integer.MAX_VALUE; |
| 65 | + for (int i = 0; i < A.length; i++) { |
| 66 | + min = Math.min(min, A[i]); |
| 67 | + sum += A[i]; |
| 68 | + } |
| 69 | + return K % 2 == 0 ? sum : sum - min * 2; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments