Leetcode 1005 Maximize Sum Of Array After K Negations Solution in java | Hindi Coding Community

0

 


Given an integer array nums and an integer k, modify the array in the following way:

choose an index i and replace nums[i] with -nums[i].

You should apply this process exactly k times. You may choose the same index i multiple times.


Return the largest possible sum of the array after modifying it in this way.


Example 1:

Input: nums = [4,2,3], k = 1

Output: 5

Explanation: Choose index 1 and nums becomes [4,-2,3].




public int largestSumAfterKNegations(int[] arr, int k) {
Arrays.sort(arr);
int sum = 0, len = arr.length, minIndex = 0;
while (k > 0) {
arr[minIndex] *= -1;
k--;
if (minIndex + 1 < len && arr[minIndex] > arr[minIndex + 1]) minIndex++;
}
for (int i : arr) sum += i;
return sum;
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !