Maximize Array sum by adding multiple of another Array element in given ranges
Last Updated : 21 Feb, 2023
Comments
Improve
Suggest changes
3 Likes
Like
Report
Given two arrays X[] and Y[] of length N along with Q queries each of type [L, R] that denotes the subarray of X[] from L to R. The task is to find the maximum sum that can be obtained by applying the following operation for each query:
Choose an element from Y[].
Add multiples with alternate +ve and -ve signs to the elements of the subarray. i.e., if the chosen element is 4, then modify the subarray as {XL+ 4, XL+1 - 8, . . . (till Rth) index}
Delete the element chosen from Y.
Note: 1-based indexing is used here.
Examples:
Input: N = 4, X[] = {1, 2, 3, 4}, Y[] = {2, 3, 5, 6}, K = 1, query = {{3, 3}} Output: 16 Explanation: Number of queries = 1 Sub-array from start to end index of X[]: {3} Chose 6 from Y[] and then add alternative series of multiple of 6 = {3 + 6} = {9}. Rest of the elements except the sub-array will remain the same, Therefore, new X[] is: {1, 2, 9, 4}. The maximum sum that can obtain from X[] = 1+ 2+ 9+ 4 = 16
Input: N = 5, X[] = {5, 7, 2, 1, 8}, Y[] = {1, 2, 3, 4, 5}, K = 2, queries = {{1, 4}, {1, 5}} Output: 36 Explanation: start = 1, end = 4 The subarray = {7, 2, 1, 8} Lets chose 1 from Y[] and add series of multiple of 1 in subarray = {7 + 1, 2 - 2, 1 + 3, 8 - 4} = {8, 0, 4, 4}. X[]:{5, 8, 0, 4, 4} Now, start = 1, end = 5 The subarray = {5, 8, 0, 4, 4} lets chose 5 from Y[] and add series of multiple of 5 in subarray = {5 + 5, 8 - 10, 0 + 15, 4 - 20, 4 + 25} = {10, -2, 15, -16, 29}. Now updated X[] will be: {10, -2, 15, -16, 29}. Overall sum of X[] is : (10 - 2 + 15 - 16 + 29) = 36. It can be verified that this sum is maximum possible.
Intuition: The intuition behind the approach is provided below
Let us take an example of series of multiple of an integer let say K. Then the series will be as the picture below:
Series of multiple of K
It can be seen clearly that if subarray of series is of odd length then it will contribute a positive sum in the overall sum, While series of even length will contribute negative sum to the total sum.
So the optimal idea is to add the multiples of the biggest value to the largest odd length subarray and the multiples of the smallest value to the largest even length subarray.
Naive Approach:
In this method, we will do the same as mentioned in the problem statement. We will traverse on each sub-array by the given start and end indices in each query and add series of multiple of the optimal element at that current state so that our sum is maximized.
Follow the steps mentioned below to implement the idea:
Make ArrayList of Pairs<Start, End> DataType and initialize it with Pairs of start and end indices of given sub-arrays in query.
Sort Queries in ArrayList according to the length of sub-arrays, Formally arrange Pairs in descending order of length.
SortY[]. It will be convenient to get minimum and maximum elements and delete them after use.
Run a loop number of times queries are asked then do the following steps:
Calculate the length of the current subarray. If the length is even take a minimum element of Y[] else take the maximum.
Traverse on sub-array and add the series of Multiple into it.
Delete the used element of Y[].
Calculate the overall sum of elements present in the X[] by traversing array X[]
Print the sum as the required answer.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// Function to get maximum value after K// queriesvoidmaximumSum(intX[],intY[],intN,intK,vector<int>&list){// Variable for holding maximum sum that can be// obtainedlongsum=0;// Loop for calculating initial sum of X[]for(inti=0;i<N;i++){sum+=X[i];}// Start pointer for Y[]ints=0;// End pointer of Y[]inte=N-1;// Loop for Executing Queries in descending order of// lengthfor(inti=list.size()-1;i>=0;i--){// Variable to hold length of subarrayintlength=list[i];// element needed to be add optimallyintelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumcout<<sum;}// Driver codeintmain(){intN=3;intX[]={1,2,3};intY[]={4,3,1};intK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayintstart[]={1,1};intend[]={1,3};// ArrayList of length of sub-arrays in each queryvector<int>list;for(inti=0;i<K;i++){list.push_back((end[i]-start[i])+1);}// Sorting ArrayListsort(list.begin(),list.end());// Sorting Y[] using in-built sort functionsort(Y,Y+N);// Function call for getting maximum SummaximumSum(X,Y,N,K,list);return0;}// This code is contributed by Pushpesh Raj.
// Loop for Executing Queries in descending order of
// length
for (inti=list.size() -1; i>=0; i--) {
// Variable to hold length of subarray
intlength=list[i];
// element needed to be add optimally
intelement=length%2==0?Y[s] : Y[e];
// Increasing or decreasing start and end
// pointers After using element at that pointers
if (length%2==0) {
s++;
}
else {
e--;
}
// Condition when length is even
if (length%2==0) {
// Subtracting from the
// overall sum
sum=sum- ((length/2) *element);
}
else {
// Adding increment in
// overall sum
sum=sum+ (((length+1) /2) *element);
}
}
// Printing value of sum
cout<<sum;
}
// Driver code
intmain()
{
intN=3;
intX[] = { 1, 2, 3 };
intY[] = { 4, 3, 1 };
intK=2;
// Start[] and end[] of K length holds
// starting and ending indices
// of sub-array
intstart[] = { 1, 1 };
intend[] = { 1, 3 };
// ArrayList of length of sub-arrays in each query
vector<int>list;
for (inti=0; i<K; i++) {
list.push_back((end[i] -start[i]) +1);
}
// Sorting ArrayList
sort(list.begin(),list.end());
// Sorting Y[] using in-built sort function
sort(Y,Y+N);
// Function call for getting maximum Sum
maximumSum(X, Y, N, K, list);
return0;
}
// This code is contributed by Pushpesh Raj.
Java
// Java code to implement the approachimportjava.io.*;importjava.lang.*;importjava.util.*;// User defined Pair classclassPair{// Two variables to store start and end indices// respectivelyintx,y;// Constructor of Pair classPair(intx,inty){this.x=x;this.y=y;}// Function for returning length of a Pair(Formally// length of sub-array) According to 1 based indexingintlength(){return(this.y-this.x)+1;}}classGFG{// Function to get maximum Sum after// K queriesstaticvoidmaximumSum(intX[],intY[],intN,ArrayList<Pair>list,intK){// Variable to calculate overall sumlongsum=0;// Maintaining two pointers to get// maximum and minimum element from// Y[]ints=0;inte=Y.length-1;// Loop for Traversing on Pairsfor(inti=0;i<list.size();i++){// Variable S holds start index// of queryintS=list.get(i).x;// Variable E holds start index// of queryintE=list.get(i).y;// length variable stores length// of sub-array using S and// E(1 based indexing)intlength=list.get(i).length();// If length is even the minimum// element will be store in// "element" variable else Maximum// element will be store in itintelement=length%2==0?Y[s]:Y[e];// Removing chose element from// Y[]if(length%2==0){s++;}else{e--;}// Counter initialized to 1intcounter=1;// Loop for traversing on given// sub-array as queries// 1 based indexing, Therefore, S-1 to <Efor(intj=S-1;j<E;j++){// The below if-else// conditions is adding AP// of +ve and -ve elementsif(counter%2!=0){X[j]=X[j]+(counter*element);}else{X[j]=X[j]-(counter*element);}// Incrementing countercounter++;}}// Loop for traversing on X[] after// K Queries so that we can obtain// its sumfor(inti=0;i<N;i++){// Adding element of X[] into// sum variablesum+=X[i];}// Printing value of sumSystem.out.println(sum);}// Driver codepublicstaticvoidmain(String[]args){intN=3;int[]X={1,2,3};int[]Y={1,3,4};intK=2;// Start[] and end[] of K length// holds starting and ending indices// of sub-arrayint[]start={1,1};int[]end={3,1};// ArrayList of Pair type to store given start and// end indices as Pair<start, end>ArrayList<Pair>list=newArrayList<>();// Loop for initializing list as Pairsfor(inti=0;i<K;i++){list.add(newPair(start[i],end[i]));}// Sorting list in descending order using user// defined Selection-sort functionSortList(list);// sorting Y[] using in-built sort functionArrays.sort(Y);// function call for obtaining maximum summaximumSum(X,Y,N,list,K);}// User defined Function for sorting list(Selection Sort// is used)staticvoidSortList(ArrayList<Pair>list){for(inti=0;i<list.size()-1;i++){intmax=i;for(intj=i+1;j<list.size();j++){if(list.get(max).length()<list.get(j).length()){max=j;}}Pairtemp=newPair(list.get(i).x,list.get(i).y);list.get(i).x=list.get(max).x;list.get(i).y=list.get(max).y;list.get(max).x=temp.x;list.get(max).y=temp.y;}}}
Python3
# Python implementationfromtypingimportListdefmaximumSum(X:List[int],Y:List[int],N:int,K:int,list:List[int])->None:# Variable for holding maximum sum that can be obtainedsum=0# Loop for calculating initial sum of X[]foriinrange(N):sum+=X[i]# Start pointer for Y[]s=0# End pointer of Y[]e=N-1# Loop for Executing Queries in descending order of lengthforiinrange(len(list)-1,-1,-1):# Variable to hold length of subarraylength=list[i]# element needed to be add optimallyelement=Y[s]iflength%2==0elseY[e]# Increasing or decreasing start and end pointers After using element at that pointersiflength%2==0:s+=1else:e-=1# Condition when length is eveniflength%2==0:# Subtracting from the overall sumsum=sum-((length//2)*element)else:# Adding increment in overall sumsum=sum+(((length+1)//2)*element)# Printing value of sumprint(sum)# Driver codedefmain():N=3X=[1,2,3]Y=[4,3,1]K=2# Start[] and end[] of K length holds starting and ending indices of sub-arraystart=[1,1]end=[1,3]# ArrayList of length of sub-arrays in each queryarr_list=[(end[i]-start[i])+1foriinrange(K)]# Sorting ArrayListarr_list.sort()# Sorting Y[] using in-built sort functionY.sort()# Function call for getting maximum SummaximumSum(X,Y,N,K,arr_list)if__name__=='__main__':main()# This code is contributed by ksam24000
JavaScript
// JavaScript code to implement the approach// Function to get maximum value after K// queriesfunctionmaximumSum(X,Y,N,K,list){// Variable for holding maximum sum that can be// obtainedsum=0;// Loop for calculating initial sum of X[]for(leti=0;i<N;i++){sum+=X[i];}// Start pointer for Y[]lets=0;// End pointer of Y[]lete=N-1;// Loop for Executing Queries in descending order of// lengthfor(leti=list.length-1;i>=0;i--){// Variable to hold length of subarrayletlength=list[i];// element needed to be add optimallyletelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// poleters After using element at that poletersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumdocument.write(sum);}// Driver codeletN=3;letX=[1,2,3];letY=[4,3,1];letK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayletstart=[1,1];letend=[1,3];// ArrayList of length of sub-arrays in each queryletlist=[];for(leti=0;i<K;i++){list.push((end[i]-start[i])+1);}// Sorting ArrayListlist.sort();// Sorting Y[] using in-built sort functionY.sort();// Function call for getting maximum SummaximumSum(X,Y,N,K,list);// This code is contributed by poojaagarwal2.
C#
// C# implementation of the above approachusingSystem;usingSystem.Collections.Generic;classGFG{// Function to get maximum value after K// queriesstaticvoidmaximumSum(int[]X,int[]Y,intN,intK,List<int>list){// Variable for holding maximum sum that can be// obtainedlongsum=0;// Loop for calculating initial sum of X[]for(inti=0;i<N;i++){sum+=X[i];}// Start pointer for Y[]ints=0;// End pointer of Y[]inte=N-1;// Loop for Executing Queries in descending order of// lengthfor(inti=list.Count-1;i>=0;i--){// Variable to hold length of subarrayintlength=list[i];// element needed to be add optimallyintelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumConsole.Write(sum);}staticpublicvoidMain(){// Driver codeintN=3;int[]X={1,2,3};int[]Y={4,3,1};intK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayint[]start={1,1};int[]end={1,3};// ArrayList of length of sub-arrays in each queryList<int>list=newList<int>();for(inti=0;i<K;i++){list.Add((end[i]-start[i])+1);}// Sorting ArrayListlist.Sort();// Sorting Y[] using in-built sort functionArray.Sort(Y);// Function call for getting maximum SummaximumSum(X,Y,N,K,list);}}// This code is contributed by ratiagrawal.
Output
17
Time Complexity: O(N2), As Selection Sort is used Auxiliary Space: O(K), As ArrayList of Pair is used of Size K
Efficient Approach:
In this method, we will not be traversing on sub-array for each query. We will direct obtain the increment or decrement using a direct mathematical formula. From the intuition we can conclude that:
If length of sub-array is odd, Then increment in overall sum of X[] will be = (((length + 1) / 2) * element)
If the length of the sub-array is even, Then the decrement in overall sum of X[] will be = - ((length / 2) * element)
Here element is chosen element from Y[], and length is length of sub-array in query.
Follow the steps mentioned below to implement the idea:
Create a variable sum and calculate the overall sum of the elements initially present in X[].
Create a list and initialize it with the length of subarrays in K queries.
Sort list and the array Y[].
Run a loop from the back to the front of the list(Formally Descending order length) and do the following:
If length is odd add (((length+1)/2)*element) in sum variable else subtract ((length/2)*element) from sum variable.
Print the value of the sum variable.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// Function to get maximum value after K// queriesvoidmaximumSum(intX[],intY[],intN,intK,vector<int>&list){// Variable for holding maximum sum that can be// obtainedlongsum=0;// Loop for calculating initial sum of X[]for(inti=0;i<N;i++){sum+=X[i];}// Start pointer for Y[]ints=0;// End pointer of Y[]inte=N-1;// Loop for Executing Queries in descending order of// lengthfor(inti=list.size()-1;i>=0;i--){// Variable to hold length of subarrayintlength=list[i];// element needed to be add optimallyintelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumcout<<sum;}// Driver codeintmain(){intN=3;intX[]={1,2,3};intY[]={4,3,1};intK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayintstart[]={1,1};intend[]={1,3};// ArrayList of length of sub-arrays in each queryvector<int>list;for(inti=0;i<K;i++){list.push_back((end[i]-start[i])+1);}// Sorting ArrayListsort(list.begin(),list.end());// Sorting Y[] using in-built sort functionsort(Y,Y+N);// Function call for getting maximum SummaximumSum(X,Y,N,K,list);return0;}// This code is contributed by sanjoy_62.
// Loop for Executing Queries in descending order of
// length
for (inti=list.size() -1; i>=0; i--) {
// Variable to hold length of subarray
intlength=list[i];
// element needed to be add optimally
intelement=length%2==0?Y[s] : Y[e];
// Increasing or decreasing start and end
// pointers After using element at that pointers
if (length%2==0) {
s++;
}
else {
e--;
}
// Condition when length is even
if (length%2==0) {
// Subtracting from the
// overall sum
sum=sum- ((length/2) *element);
}
else {
// Adding increment in
// overall sum
sum=sum+ (((length+1) /2) *element);
}
}
// Printing value of sum
cout<<sum;
}
// Driver code
intmain()
{
intN=3;
intX[] = { 1, 2, 3 };
intY[] = { 4, 3, 1 };
intK=2;
// Start[] and end[] of K length holds
// starting and ending indices
// of sub-array
intstart[] = { 1, 1 };
intend[] = { 1, 3 };
// ArrayList of length of sub-arrays in each query
vector<int>list;
for (inti=0; i<K; i++) {
list.push_back((end[i] -start[i]) +1);
}
// Sorting ArrayList
sort(list.begin(),list.end());
// Sorting Y[] using in-built sort function
sort(Y,Y+N);
// Function call for getting maximum Sum
maximumSum(X, Y, N, K, list);
return0;
}
// This code is contributed by sanjoy_62.
Java
// Java code to implement the approachimportjava.io.*;importjava.lang.*;importjava.util.*;classGFG{// Function to get maximum value after K// queriesstaticvoidmaximumSum(intX[],intY[],intN,intK,ArrayList<Integer>list){// Variable for holding maximum sum that can be// obtainedlongsum=0;// Loop for calculating initial sum of X[]for(inti=0;i<X.length;i++){sum+=X[i];}// Start pointer for Y[]ints=0;// End pointer of Y[]inte=Y.length-1;// Loop for Executing Queries in descending order of// lengthfor(inti=list.size()-1;i>=0;i--){// Variable to hold length of subarrayintlength=list.get(i);// element needed to be add optimallyintelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumSystem.out.println(sum);}// Driver codepublicstaticvoidmain(String[]args){intN=3;int[]X={1,2,3};int[]Y={4,3,1};intK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayint[]start={1,1};int[]end={1,3};// ArrayList of length of sub-arrays in each queryArrayList<Integer>list=newArrayList<>();for(inti=0;i<K;i++){list.add((end[i]-start[i])+1);}// Sorting ArrayListlist.sort(null);// Sorting Y[] using in-built sort functionArrays.sort(Y);// Function call for getting maximum SummaximumSum(X,Y,N,K,list);}}
Python3
# Function to get maximum value after K# queriesdefmaximumSum(X,Y,N,K,list):# Variable for holding maximum sum that can be# obtainedsum=0# Loop for calculating initial sum of X[]foriinrange(N):sum+=X[i]# Start pointer for Y[]s=0# End pointer of Y[]e=N-1# Loop for Executing Queries in descending order of# lengthforiinreversed(range(len(list))):# Variable to hold length of subarraylength=list[i]# element needed to be add optimallyelement=Y[s]iflength%2==0elseY[e]# Increasing or decreasing start and end# pointers After using element at that pointersiflength%2==0:s+=1else:e-=1# Condition when length is eveniflength%2==0:# Subtracting from the# overall sumsum=sum-((length/2)*element)else:# Adding increment in# overall sumsum=sum+(((length+1)//2)*element)# Printing value of sumprint(sum)# Driver code if__name__=="__main__":N=3X=[1,2,3]Y=[4,3,1]K=2# Start[] and end[] of K length holds# starting and ending indices# of sub-arraystart=[1,1]end=[1,3]# ArrayList of length of sub-arrays in each querylist=[]foriinrange(0,K):list.append((end[i]-start[i])+1)# Sorting ArrayListlist.sort()# Sorting Y[] using in-built sort functionY.sort()# Function call for getting maximum SummaximumSum(X,Y,N,K,list)# This code is contributed by sanjoy_62.
C#
// C# code to implement the approachusingSystem;usingSystem.Collections;usingSystem.Collections.Generic;publicclassGFG{// Function to get maximum value after K// queriesstaticvoidmaximumSum(int[]X,int[]Y,intN,intK,ArrayListlist){// Variable for holding maximum sum that can be// obtainedlongsum=0;// Loop for calculating initial sum of X[]for(inti=0;i<X.Length;i++){sum+=X[i];}// Start pointer for Y[]ints=0;// End pointer of Y[]inte=Y.Length-1;// Loop for Executing Queries in descending order of// lengthfor(inti=list.Count-1;i>=0;i--){// Variable to hold length of subarrayintlength=(int)list[i];// element needed to be add optimallyintelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumConsole.WriteLine(sum);}staticpublicvoidMain(){// CodeintN=3;int[]X={1,2,3};int[]Y={4,3,1};intK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayint[]start={1,1};int[]end={1,3};// ArrayList of length of sub-arrays in each queryArrayListlist=newArrayList();for(inti=0;i<K;i++){list.Add((end[i]-start[i])+1);}// Sorting ArrayListlist.Sort();// Sorting Y[] using in-built sort functionArray.Sort(Y);// Function call for getting maximum SummaximumSum(X,Y,N,K,list);}}// This code is contributed by lokesh
JavaScript
// Javascript code to implement the approach// Function to get maximum value after K// queriesfunctionmaximumSum(X,Y,N,K,list){// Variable for holding maximum sum that can be// obtainedletsum=0;// Loop for calculating initial sum of X[]for(leti=0;i<N;i++){sum+=X[i];}// Start pointer for Y[]lets=0;// End pointer of Y[]lete=N-1;// Loop for Executing Queries in descending order of// lengthfor(leti=list.length-1;i>=0;i--){// Variable to hold length of subarrayletlength=list[i];// element needed to be add optimallyletelement=length%2==0?Y[s]:Y[e];// Increasing or decreasing start and end// pointers After using element at that pointersif(length%2==0){s++;}else{e--;}// Condition when length is evenif(length%2==0){// Subtracting from the// overall sumsum=sum-((length/2)*element);}else{// Adding increment in// overall sumsum=sum+(((length+1)/2)*element);}}// Printing value of sumconsole.log(sum);}// Driver codeletN=3;letX=[1,2,3];letY=[4,3,1];letK=2;// Start[] and end[] of K length holds// starting and ending indices// of sub-arrayletstart=[1,1];letend=[1,3];// ArrayList of length of sub-arrays in each queryletlist=newArray();for(leti=0;i<K;i++){list.push((end[i]-start[i])+1);}// Sorting ArrayListlist.sort();// Sorting Y[] using in-built sort functionY.sort();// Function call for getting maximum SummaximumSum(X,Y,N,K,list);
Output
17
Time Complexity: O(Y * log Y), As sorting is performed on Y[]. Auxiliary Space: O(K), As an ArrayList of size K is used.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.