We modify the array in the following way: we choose i and replace A[i] with -A[i] and we repeat this process K times in total. (We may choose the same index i multiple times.)
Find the largest possible sum of the array after modifying it in this way.
Example:
Input: arr[]={4,2,3}, K=1
Output: 5 // {4,-2,3} i.e sum=4-2+3=5
Approach
Java
import java.util.Arrays;public class MaxSumArrayAfterKNeg {public static void main(String[] args) {int arr[] = { 4, 2, 3 };int K = 1;int sum = maxSum(arr, K);System.out.println(sum);}private static int maxSum(int[] arr, int k) {// sort the arrayArrays.sort(arr);// iterate till the end of the array// and K>0for (int i = 0; i < arr.length && k > 0; i++) {// if negative number then make// multiply by -1 and decrement kif (arr[i] < 0) {arr[i] = -1 * arr[i];k--;}// else breakelsebreak;}int flag = 0;for (int i = 0; i < arr.length; i++) {if (arr[i] == 0) {flag = 1;break;}}Arrays.sort(arr);if (k > 0) {k = k % 2;if (k > 0 && flag == 0)arr[0] = -arr[0];}int sum = 0;// find the sum of array elementfor (int i = 0; i < arr.length; i++)sum += arr[i];return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the sum of array//after K negationint largestSumAfterKNegations(vector<int>& A, int K){//sort the arraysort(A.begin(),A.end());//iterate till the end of the array//and K>0for(int i=0;i<A.size()&&K>0;i++){//if negative number then make//multiply by -1 and decrement kif(A[i]<0){A[i]=-1*A[i];K--;}//else breakelsebreak;}int flag=0;for(int i=0;i<A.size();i++){if(A[i]==0){flag=1;break;}}sort(A.begin(),A.end());if(K>0){K=K%2;if(K>0&&flag==0)A[0]=-A[0];}int sum=0;//find the sum of array elementfor(int i=0;i<A.size();i++)sum+=A[i];return sum;}int main(){vector<int> A ={4,2,3};int K = 1;int maximumSum=largestSumAfterKNegations(A,K);cout<<maximumSum<<"\n";return 0;}
No comments:
Post a Comment