Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize Array sum by replacing any K elements by its modulo with any positive integer
Next article icon

Maximize Array sum by adding multiple of another Array element in given ranges

Last Updated : 21 Feb, 2023
Comments
Improve
Suggest changes
Like Article
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.  
  • Sort Y[]. 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> using namespace std;  // Function to get maximum value after K // queries void maximumSum(int X[], int Y[], int N, int K,vector<int> &list) {   // Variable for holding maximum sum that can be   // obtained   long sum = 0;    // Loop for calculating initial sum of X[]   for (int i = 0; i < N; i++) {     sum += X[i];   }    // Start pointer for Y[]   int s = 0;    // End pointer of Y[]   int e = N - 1;    // Loop for Executing Queries in descending order of   // length   for (int i = list.size() - 1; i >= 0; i--) {      // Variable to hold length of subarray     int length = list[i];      // element needed to be add optimally     int element = 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 int main() {   int N = 3;   int X[] = { 1, 2, 3 };   int Y[] = { 4, 3, 1 };   int K = 2;    // Start[] and end[] of K length holds   // starting and ending indices   // of sub-array   int start[] = { 1, 1 };   int end[] = { 1, 3 };    // ArrayList of length of sub-arrays in each query   vector<int> list;   for (int i = 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);    return 0; }  // This code is contributed by Pushpesh Raj. 
Java
// Java code to implement the approach  import java.io.*; import java.lang.*; import java.util.*;  // User defined Pair class class Pair {      // Two variables to store start and end indices     // respectively     int x, y;      // Constructor of Pair class     Pair(int x, int y)     {         this.x = x;         this.y = y;     }      // Function for returning length of a Pair(Formally     // length of sub-array) According to 1 based indexing     int length() { return (this.y - this.x) + 1; } } class GFG {      // Function to get maximum Sum after     // K queries     static void maximumSum(int X[], int Y[], int N,                            ArrayList<Pair> list, int K)     {          // Variable to calculate overall sum         long sum = 0;          // Maintaining two pointers to get         // maximum and minimum element from         // Y[]         int s = 0;         int e = Y.length - 1;          // Loop for Traversing on Pairs         for (int i = 0; i < list.size(); i++) {              // Variable S holds start index             // of query             int S = list.get(i).x;              // Variable E holds start index             // of query             int E = list.get(i).y;              // length variable stores length             // of sub-array using S and             // E(1 based indexing)             int length = list.get(i).length();              // If length is even the minimum             // element will be store in             // "element" variable else Maximum             // element will be store in it             int element = length % 2 == 0 ? Y[s] : Y[e];              // Removing chose element from             // Y[]             if (length % 2 == 0) {                  s++;             }             else {                 e--;             }              // Counter initialized to 1             int counter = 1;              // Loop for traversing on given             // sub-array as queries             // 1 based indexing, Therefore, S-1 to <E             for (int j = S - 1; j < E; j++) {                  // The below if-else                 // conditions  is adding AP                 // of +ve and -ve elements                 if (counter % 2 != 0) {                      X[j] = X[j] + (counter * element);                 }                 else {                     X[j] = X[j] - (counter * element);                 }                  // Incrementing counter                 counter++;             }         }          // Loop for traversing on X[] after         // K Queries so that we can obtain         // its sum         for (int i = 0; i < N; i++) {              // Adding element of X[] into             // sum variable             sum += X[i];         }          // Printing value of sum         System.out.println(sum);     }      // Driver code     public static void main(String[] args)     {          int N = 3;         int[] X = { 1, 2, 3 };         int[] Y = { 1, 3, 4 };         int K = 2;          // Start[] and end[] of K length         // holds starting and ending indices         // of sub-array         int[] 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 = new ArrayList<>();          // Loop for initializing list as Pairs         for (int i = 0; i < K; i++) {             list.add(new Pair(start[i], end[i]));         }          // Sorting list in descending order using user         // defined Selection-sort function         SortList(list);          // sorting Y[] using in-built sort function         Arrays.sort(Y);          // function call for obtaining maximum sum         maximumSum(X, Y, N, list, K);     }      // User defined Function for sorting list(Selection Sort     // is used)     static void SortList(ArrayList<Pair> list)     {         for (int i = 0; i < list.size() - 1; i++) {             int max = i;             for (int j = i + 1; j < list.size(); j++) {                 if (list.get(max).length()                     < list.get(j).length()) {                     max = j;                 }             }             Pair temp                 = new Pair(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 implementation from typing import List  def maximumSum(X: List[int], Y: List[int], N: int, K: int, list: List[int]) -> None:     # Variable for holding maximum sum that can be obtained     sum = 0      # Loop for calculating initial sum of X[]     for i in range(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 length     for i in range(len(list) - 1, -1, -1):         # Variable to hold length of subarray         length = list[i]          # element needed to be add optimally         element = Y[s] if length % 2 == 0 else Y[e]          # Increasing or decreasing start and end pointers After using element at that pointers         if length % 2 == 0:             s += 1         else:             e -= 1          # 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     print(sum)  # Driver code   def main():     N = 3     X = [1, 2, 3]     Y = [4, 3, 1]     K = 2      # Start[] and end[] of K length holds starting and ending indices of sub-array     start = [1, 1]     end = [1, 3]      # ArrayList of length of sub-arrays in each query     arr_list = [(end[i] - start[i]) + 1 for i in range(K)]      # Sorting ArrayList     arr_list.sort()      # Sorting Y[] using in-built sort function     Y.sort()      # Function call for getting maximum Sum     maximumSum(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 // queries function maximumSum(X, Y, N, K, list) {   // Variable for holding maximum sum that can be   // obtained    sum = 0;    // Loop for calculating initial sum of X[]   for (let i = 0; i < N; i++) {     sum += X[i];   }    // Start pointer for Y[]   let s = 0;    // End pointer of Y[]   let e = N - 1;    // Loop for Executing Queries in descending order of   // length   for (let i = list.length - 1; i >= 0; i--) {      // Variable to hold length of subarray     let length = list[i];      // element needed to be add optimally     let element = length % 2 == 0 ? Y[s] : Y[e];      // Increasing or decreasing start and end     // poleters After using element at that poleters     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   document.write(sum); }  // Driver code    let N = 3;   let X = [ 1, 2, 3 ];   let Y = [4, 3, 1 ];   let K = 2;    // Start[] and end[] of K length holds   // starting and ending indices   // of sub-array   let start = [1, 1 ];   let end = [1, 3 ];    // ArrayList of length of sub-arrays in each query   let list=[];   for (let i = 0; i < K; i++) {     list.push((end[i] - start[i]) + 1);   }    // Sorting ArrayList   list.sort();    // Sorting Y[] using in-built sort function   Y.sort();      // Function call for getting maximum Sum   maximumSum(X, Y, N, K, list);      // This code is contributed by poojaagarwal2. 
C#
// C# implementation of the above approach using System; using System.Collections.Generic;  class GFG {          // Function to get maximum value after K     // queries     static void maximumSum(int[] X, int[] Y, int N, int K,List<int> list)     {              // Variable for holding maximum sum that can be       // obtained       long sum = 0;            // Loop for calculating initial sum of X[]       for (int i = 0; i < N; i++) {         sum += X[i];       }            // Start pointer for Y[]       int s = 0;            // End pointer of Y[]       int e = N - 1;            // Loop for Executing Queries in descending order of       // length       for (int i = list.Count - 1; i >= 0; i--) {              // Variable to hold length of subarray         int length = list[i];              // element needed to be add optimally         int element = 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       Console.Write(sum);     }           static public void Main()     {     // Driver code       int N = 3;       int[] X = { 1, 2, 3 };       int[] Y = { 4, 3, 1 };       int K = 2;            // Start[] and end[] of K length holds       // starting and ending indices       // of sub-array       int[] start = { 1, 1 };       int[] end = { 1, 3 };            // ArrayList of length of sub-arrays in each query       List<int> list=new List<int>();       for (int i = 0; i < K; i++) {         list.Add((end[i] - start[i]) + 1);       }            // Sorting ArrayList       list.Sort();            // Sorting Y[] using in-built sort function       Array.Sort(Y);               // Function call for getting maximum Sum       maximumSum(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> using namespace std;  // Function to get maximum value after K // queries void maximumSum(int X[], int Y[], int N, int K,vector<int> &list) {   // Variable for holding maximum sum that can be   // obtained   long sum = 0;    // Loop for calculating initial sum of X[]   for (int i = 0; i < N; i++) {     sum += X[i];   }    // Start pointer for Y[]   int s = 0;    // End pointer of Y[]   int e = N - 1;    // Loop for Executing Queries in descending order of   // length   for (int i = list.size() - 1; i >= 0; i--) {      // Variable to hold length of subarray     int length = list[i];      // element needed to be add optimally     int element = 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 int main() {   int N = 3;   int X[] = { 1, 2, 3 };   int Y[] = { 4, 3, 1 };   int K = 2;    // Start[] and end[] of K length holds   // starting and ending indices   // of sub-array   int start[] = { 1, 1 };   int end[] = { 1, 3 };    // ArrayList of length of sub-arrays in each query   vector<int> list;   for (int i = 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);    return 0; }  // This code is contributed by sanjoy_62. 
Java
// Java code to implement the approach  import java.io.*; import java.lang.*; import java.util.*;  class GFG {      // Function to get maximum value after K     // queries     static void maximumSum(int X[], int Y[], int N, int K,                            ArrayList<Integer> list)     {         // Variable for holding maximum sum that can be         // obtained         long sum = 0;          // Loop for calculating initial sum of X[]         for (int i = 0; i < X.length; i++) {             sum += X[i];         }          // Start pointer for Y[]         int s = 0;          // End pointer of Y[]         int e = Y.length - 1;          // Loop for Executing Queries in descending order of         // length         for (int i = list.size() - 1; i >= 0; i--) {              // Variable to hold length of subarray             int length = list.get(i);              // element needed to be add optimally             int element = 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         System.out.println(sum);     }      // Driver code     public static void main(String[] args)     {         int N = 3;         int[] X = { 1, 2, 3 };         int[] Y = { 4, 3, 1 };         int K = 2;          // Start[] and end[] of K length holds         // starting and ending indices         // of sub-array         int[] start = { 1, 1 };         int[] end = { 1, 3 };          // ArrayList of length of sub-arrays in each query         ArrayList<Integer> list = new ArrayList<>();         for (int i = 0; i < K; i++) {             list.add((end[i] - start[i]) + 1);         }          // Sorting ArrayList         list.sort(null);          // Sorting Y[] using in-built sort function         Arrays.sort(Y);          // Function call for getting maximum Sum         maximumSum(X, Y, N, K, list);     } } 
Python3
# Function to get maximum value after K # queries def maximumSum(X, Y, N, K, list):   # Variable for holding maximum sum that can be   # obtained   sum = 0    # Loop for calculating initial sum of X[]   for i in range(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   # length   for i in reversed(range(len(list))):     # Variable to hold length of subarray     length = list[i]      # element needed to be add optimally     element = Y[s] if length % 2 == 0 else Y[e]       # Increasing or decreasing start and end     # pointers After using element at that pointers     if length%2 == 0:       s += 1     else:       e -= 1      # 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   print(sum)                     # Driver code  if __name__ == "__main__":    N = 3   X = [1, 2, 3]   Y = [4, 3, 1]   K = 2    # Start[] and end[] of K length holds   # starting and ending indices   # of sub-array   start = [1, 1]   end = [1, 3]    # ArrayList of length of sub-arrays in each query   list = []   for i in range(0, K):     list.append((end[i] - start[i]) + 1)    # Sorting ArrayList   list.sort()    # Sorting Y[] using in-built sort function   Y.sort()    # Function call for getting maximum Sum   maximumSum(X, Y, N, K, list)  # This code is contributed by sanjoy_62. 
C#
// C# code to implement the approach  using System; using System.Collections; using System.Collections.Generic;  public class GFG {    // Function to get maximum value after K   // queries   static void maximumSum(int[] X, int[] Y, int N, int K,                          ArrayList list)   {     // Variable for holding maximum sum that can be     // obtained     long sum = 0;      // Loop for calculating initial sum of X[]     for (int i = 0; i < X.Length; i++) {       sum += X[i];     }      // Start pointer for Y[]     int s = 0;      // End pointer of Y[]     int e = Y.Length - 1;      // Loop for Executing Queries in descending order of     // length     for (int i = list.Count - 1; i >= 0; i--) {        // Variable to hold length of subarray       int length = (int)list[i];        // element needed to be add optimally       int element = 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     Console.WriteLine(sum);   }    static public void Main()   {      // Code     int N = 3;     int[] X = { 1, 2, 3 };     int[] Y = { 4, 3, 1 };     int K = 2;      // Start[] and end[] of K length holds     // starting and ending indices     // of sub-array     int[] start = { 1, 1 };     int[] end = { 1, 3 };      // ArrayList of length of sub-arrays in each query     ArrayList list = new ArrayList();     for (int i = 0; i < K; i++) {       list.Add((end[i] - start[i]) + 1);     }      // Sorting ArrayList     list.Sort();      // Sorting Y[] using in-built sort function     Array.Sort(Y);      // Function call for getting maximum Sum     maximumSum(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 // queries function maximumSum(X, Y, N, K, list) {   // Variable for holding maximum sum that can be   // obtained   let sum = 0;    // Loop for calculating initial sum of X[]   for (let i = 0; i < N; i++) {     sum += X[i];   }    // Start pointer for Y[]   let s = 0;    // End pointer of Y[]   let e = N - 1;    // Loop for Executing Queries in descending order of   // length   for (let i = list.length - 1; i >= 0; i--) {      // Variable to hold length of subarray     let length = list[i];      // element needed to be add optimally     let element = 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   console.log(sum); }  // Driver code let N = 3; let X = [ 1, 2, 3 ]; let Y = [ 4, 3, 1 ]; let K = 2;  // Start[] and end[] of K length holds // starting and ending indices // of sub-array let start = [ 1, 1 ]; let end = [ 1, 3 ];  // ArrayList of length of sub-arrays in each query let list=new Array(); for (let i = 0; i < K; i++) {     list.push((end[i] - start[i]) + 1); }  // Sorting ArrayList list.sort();  // Sorting Y[] using in-built sort function Y.sort();  // Function call for getting maximum Sum maximumSum(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.

Related Articles:

  • Introduction to Arrays - Data Structures and Algorithms Tutorials

Next Article
Maximize Array sum by replacing any K elements by its modulo with any positive integer
author
pradeep6036ymca
Improve
Article Tags :
  • Mathematical
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2022
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array
    Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible wa
    15 min read
  • Maximize the sum of Array by formed by adding pair of elements
    Given an array a[] of 2*N integers, The task is to make the array a[] of size N i.e, reducing it to half size such that, a[i] = ?(a[j] + a[k]) / N?, 0 < j, k < 2*N - 1. and form the array so that the sum of all the elements of the array a[], will be maximum. Output the maximum sum. Examples: I
    6 min read
  • Maximize Array sum by replacing any K elements by its modulo with any positive integer
    Given an array of positive integer arr[], and a number K. the task is to maximize the sum of the array by replacing any K elements of the array by taking modulus with any positive integer which is less than arr[i] i.e, (arr[i] = arr[i]%X where X ≤ arr[i]). Examples: Input: arr[] = {5, 7, 18, 12, 11,
    5 min read
  • Maximize subarray sum of given Array by adding X in range [L, R] for Q queries
    Given an array arr[] of N integers and M update queries of the type (L, R, X), the task is to find the maximum subarray sum after each update query where in each query, add integer X to every element of the array arr[] in the range [L, R]. Examples: Input: arr[] = {-1, 5, -2, 9, 3, -3, 2}, query[] =
    8 min read
  • Maximize score by multiplying elements of given Array with given multipliers
    Given two arrays array[] and multipliers[] of size N and M where N is always greater than equal to M. There are M operations to be performed. In each operation, choose multiplier[i] and an element from the array arr[] either from the start or the end let's say K then add multiplier[i]*K to the total
    9 min read
  • Maximum Subarray sum of A[] by adding any element of B[] at any end
    Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it: Choose either the leftmost or rightmost
    15 min read
  • Sum of multiples of Array elements within a given range [L, R]
    Given an array arr[] of positive integers and two integers L and R, the task is to find the sum of all multiples of the array elements in the range [L, R]. Examples: Input: arr[] = {2, 7, 3, 8}, L = 7, R = 20 Output: 197 Explanation: In the range 7 to 20: Sum of multiples of 2: 8 + 10 + 12 + 14 + 16
    7 min read
  • Maximize every array element by repeatedly adding all valid i+a[i]th array element
    Given an array of integers, arr[] of size N, the task is to print all possible sum at each valid index, that can be obtained by adding i + a[i]th (1-based indexing) subsequent elements till i ? N. Examples: Input: arr[] = {4, 1, 4}Output: 4 5 4Explanation:For i = 1, arr[1] = 4.For i = 2, arr[2] = ar
    5 min read
  • Maximize the sum of array after multiplying a prefix and suffix by -1
    Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. Choose a prefix of the array and multiply all the elements by -1.Choose a suffix of the array and multiply all the elements by -1. Examples: Input:
    7 min read
  • Maximize 3rd element sum in quadruplet sets formed from given Array
    Given an array arr containing N values describing the priority of N jobs. The task is to form sets of quadruplets (W, X, Y, Z) to be done each day such that W >= X >= Y >= Z and in doing so, maximize the sum of all Y across all quadruplet sets. Note: N will always be a multiple of 4.Example
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences