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:
Maximum sum of all elements of array after performing given operations
Next article icon

Maximize sum of array elements removed by performing the given operations

Last Updated : 31 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations:

  • Choose an index i and add max(arr[i], min[i]) to S.
  • Remove the chosen element from arr[] and its corresponding minimum value.
  • Decrease each remaining value by K if it is greater than its corresponding minimum value in min[].

Examples:

Input: arr[] = {2, 4, 5, 8}, min[] = {1, 4, 5, 5}, K = 3
Output: 18
Explanation:
Choose the elements in the following order:
Step 1: Choose element 8. Now, S = 8 and arr[] = {-1, 4, 5} and min[] = {1, 4, 5}
Step 2: Choose element 5. Now, S = 8 + 5 = 13 and arr[] = {-1, 4} and min[] = {1, 4}
Step 3: Choose element 5. Now, S = 8 + 5 + 4 = 17 and arr[] = {-1} and min[] = {1}
Step 4: Choose element -1, but -1 < min[0]. Therefore, choose 1.
Hence, S = 8 + 5 + 4 + 1 = 18.

Input: arr[] = {3, 5, 2, 1}, min[] = {3, 2, 1, 3}, K = 2
Output: 12
Explanation:
Choose the elements in the following order:
Step 1: Choose element 5. Now, S = 5 and arr[] = {3, 0, 1} and min[] = {3, 1, 3}
Step 2: Choose element 3. Now, S = 5 + 3 = 8 and arr[] = {0, 1} and min[] = {1, 3} 
Step 3: Choose element 3 from min[]. Now, S = 5 + 3 + 3 = 11 and arr[] = {0} and min[] = {1}
Step 4: Choose element 1 from min[].
Hence, S = 5 + 3 + 3 + 1 = 12.

Naive Approach: The simplest approach is to traverse the given array and perform the given operations in the array itself. Follow the steps below to solve the problem:

  1. Traverse the array and find the maximum array element.
  2. Add the maximum value in S and remove the maximum.
  3. Decrease the remaining element by K if they satisfy the above conditions.
  4. Repeat the above steps until the given array becomes empty.
  5. After traversing, print S.

Time Complexity: O(N2), where N is the length of the given array.
Auxiliary Space: O(N)

Efficient Approach: The idea is to sort the given array in decreasing order. Then, print the maximum value of S by choosing the elements greedily. Follow the steps below to solve the problem:

  1. Pair the elements of the array arr[] with their corresponding values in min[].
  2. Sort the array of pairs in decreasing order according to array arr[].
  3. Initially, choose the maximum element and increase K by its initial value.
  4. Now, choose the next maximum element by decreasing its value by the current K.
  5. Repeat the above steps, until all the array elements are traversed and print the value of S.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum of
// the array arr[] where each element
// can be reduced to at most min[i]
void findMaxSum(vector<int> arr, int n,
                vector<int> min, int k,
                int& S)
{
    // Stores the pair of arr[i] & min[i]
    vector<pair<int, int> > A;
 
    for (int i = 0; i < n; i++) {
        A.push_back({ arr[i], min[i] });
    }
 
    // Sorting vector of pairs
    sort(A.begin(), A.end(),
        greater<pair<int, int> >());
 
    int K = 0;
 
    // Traverse the vector of pairs
    for (int i = 0; i < n; i++) {
 
        // Add to the value of S
        S += max(A[i].first - K,
                A[i].second);
 
        // Update K
        K += k;
    }
}
 
// Driver Code
int main()
{
    vector<int> arr, min;
 
    // Given array arr[], min[]
    arr = { 3, 5, 2, 1 };
    min = { 3, 2, 1, 3 };
 
    int N = arr.size();
 
    // Given K
    int K = 3;
 
    int S = 0;
 
    // Function Call
    findMaxSum(arr, N, min, K, S);
 
    // Print the value of S
    cout << S;
 
    return 0;
}
 
 

Java




// Java program for the
// above approach
import java.util.*;
  
class GFG{
     
static int S;
 
// Function to find the maximum sum of
// the array arr[] where each element
// can be reduced to at most min[i]
static void findMaxSum(int[] arr, int n,
                       int[] min, int k)
{
     
    // Stores the pair of arr[i] & min[i]
    ArrayList<int[]> A = new ArrayList<>();
  
    for(int i = 0; i < n; i++)
    {
        A.add(new int[]{arr[i], min[i]});
    }
  
    // Sorting vector of pairs
    Collections.sort(A, (a, b) -> b[0] - a[0]);
  
    int K = 0;
  
    // Traverse the vector of pairs
    for(int i = 0; i < n; i++)
    {
         
        // Add to the value of S
        S += Math.max(A.get(i)[0] - K,
                      A.get(i)[1]);
  
        // Update K
        K += k;
    }
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given array arr[], min[]
    int[] arr = { 3, 5, 2, 1 };
    int[] min = { 3, 2, 1, 3 };
     
    int N = arr.length;
     
    // Given K
    int K = 3;
     
     S = 0;
     
    // Function Call
    findMaxSum(arr, N, min, K);
     
    // Print the value of S
    System.out.println(S);
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program for the above approach
 
# Function to find the maximum sum of
# the array arr[] where each element
# can be reduced to at most min[i]
def findMaxSum(arr, n, min, k, S):
     
    # Stores the pair of arr[i] & min[i]
    A = []
 
    for i in range(n):
        A.append((arr[i], min[i]))
 
    # Sorting vector of pairs
    A = sorted(A)
    A = A[::-1]
     
    K = 0
 
    # Traverse the vector of pairs
    for i in range(n):
 
        # Add to the value of S
        S += max(A[i][0] - K, A[i][1])
 
        # Update K
        K += k
 
    return S
     
# Driver Code
if __name__ == '__main__':
     
    arr, min = [], []
 
    # Given array arr[], min[]
    arr = [ 3, 5, 2, 1 ]
    min = [ 3, 2, 1, 3 ]
 
    N = len(arr)
 
    # Given K
    K = 3
     
    S = 0
 
    # Function Call
    S = findMaxSum(arr, N, min, K, S)
 
    # Print the value of S
    print(S)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
 
static int S;
 
// Function to find the maximum sum of
// the array arr[] where each element
// can be reduced to at most min[i]
static void findMaxSum(int[] arr, int n,
                       int[] min, int k)
{
     
    // Stores the pair of arr[i] & min[i]
    List<List<int>> A = new List<List<int>>();
    for(int i = 0; i < n; i++)
    {
        A.Add(new List<int>());
        A[i].Add(arr[i]);
        A[i].Add(min[i]);
    }
     
    // Sorting vector of pairs
    A = A.OrderBy(lst => lst[0]).ToList();
    A.Reverse();
     
    int K = 0;
     
    // Traverse the vector of pairs
    for(int i = 0; i < n; i++)
    {
         
        // Add to the value of S
        S += Math.Max(A[i][0] - K, A[i][1]);
         
        // Update K
        K += k;
    }
}
 
// Driver code
static public void Main()
{
     
    // Given array arr[], min[]
    int[] arr = { 3, 5, 2, 1 };
    int[] min = { 3, 2, 1, 3 };
  
    int N = arr.Length;
  
    // Given K
    int K = 3;
  
    S = 0;
  
    // Function Call
    findMaxSum(arr, N, min, K);
  
    // Print the value of S
    Console.WriteLine(S);
}
}
 
// This code is contributed by avanitrachhadiya2155
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
var S =0;
 
// Function to find the maximum sum of
// the array arr[] where each element
// can be reduced to at most min[i]
function findMaxSum(arr, n, min, k)
{
    // Stores the pair of arr[i] & min[i]
    var A = [];
 
    for (var i = 0; i < n; i++) {
        A.push([arr[i], min[i] ]);
    }
 
    // Sorting vector of pairs
    A.sort((a,b)=> b[0]-a[0]);
 
    var K = 0;
 
    // Traverse the vector of pairs
    for (var i = 0; i < n; i++) {
 
        // Add to the value of S
        S += Math.max(A[i][0] - K,
                A[i][1]);
 
        // Update K
        K += k;
    }
}
 
// Driver Code
var arr = [], min = [];
// Given array arr[], min[]
arr = [3, 5, 2, 1];
min = [3, 2, 1, 3];
var N = arr.length;
// Given K
var K = 3;
// Function Call
findMaxSum(arr, N, min, K, S);
// Print the value of S
document.write( S);
 
</script>
 
 
Output: 
12

 

Time Complexity: O(N*log N), where N is the length of the given array.
Auxiliary Space: O(N)

 



Next Article
Maximum sum of all elements of array after performing given operations
author
shawavisek35
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Searching
  • Sorting
  • cpp-vector
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Searching
  • Sorting

Similar Reads

  • Maximize first array element by performing given operations at most K times
    Given an array arr[] of size N an integer K, the task is to find the maximize the first element of the array by performing the following operations at most K times: Choose a pair of indices i and j (0 ? i, j ? N-1) such that |i ? j| = 1 and arri > 0.Set arri = arri ? 1 and arrj = arrj + 1 on thos
    7 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
    9 min read
  • Find the Maximum sum of the Array by performing the given operations
    Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
    5 min read
  • Maximum sum of all elements of array after performing given operations
    Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none
    7 min read
  • Maximize the sum of sum of the Array by removing end elements
    Given an array arr of size N, the task is to maximize the sum of sum, of the remaining elements in the array, by removing the end elements.Example: Input: arr[] = {2, 3} Output: 3 Explanation: At first we will delete 2, then sum of remaining elements = 3. Then delete 3. Therefore sum of sum = 3 + 0
    6 min read
  • Make the array elements equal by performing given operations minimum number of times
    Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
    7 min read
  • Reduce all array elements to zero by performing given operations thrice
    Given an array arr[] of size N, the task is to convert every array element to 0 by applying the following operations exactly three times: Select a subarray.Increment every element of the subarray by the integer multiple of its length. Finally, print the first and last indices of the subarray involve
    9 min read
  • Remove array end element to maximize the sum of product
    Given an array of N positive integers. We are allowed to remove element from either of the two ends i.e from the left side or right side of the array. Each time we remove an element, score is increased by value of element * (number of element already removed + 1). The task is to find the maximum sco
    9 min read
  • Maximise minimum element possible in Array after performing given operations
    Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. F
    11 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    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