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:
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Next article icon

Maximize deletions by removing prefix and suffix of Array with same sum

Last Updated : 16 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array Arr[] of size N, the cost of removing ith element is Arr[i]. The task is to remove the maximum number of elements by removing the prefix and the suffix of the same length and having the same total cost.

Examples:

Input: Arr[] = {80, 90, 81, 80}
Output: 2 
Explanation: If we choose 80 from front ( left side cost = 80),  
and choose 80 from back (right side cost = 80), both are same.
But when we choose 90 from front or 81 from back 
the costs would not remain same. 
So maximum 2 elements can be removed from the array.

Input:  Arr[] = { 8, 5, 7, 8, 7, 6, 7}
Output: 6
Explanation: It will be optimal to select 8, 5, 7 from the front 
( left side cost = 20), and 7, 6, 7 from the back (right side cost = 20),  
which results in a maximum of 6 elements ( {8, 5, 7}, {7, 6, 7} ) 
that can be removed from the array.

Approach: To solve the problem use the following idea:

Since we have to equalize the cost of removing elements, we should know the sum of costs from both ends. Sum needs to be calculated from front and back for each element, so prefix sum and suffix sum can be used to store the sums from both ends.

Then traverse the suffix sum array and find the lower bound if the same in the prefix sum array. The maximum number of elements found is the required answer.

Follow the below illustration for a better understanding.

Illustration:

Consider the array Arr[] = {8, 5, 7, 8, 7, 6, 7}

Prefix sum array = {8, 13, 20, 28, 35, 41, 48}
Suffix sum array = {48, 40, 35, 28, 20, 13, 7} 

For 7 in suffix array:
        => The lower bound is 8 in the prefix array.
        => No elements can be deleted.

For 13 in suffix array:
        => The lower bound is 13 in the prefix array.
        => Elements deleted = 2 + 2 = 4.

For 20 in suffix array:
        => The lower bound is 20 in the prefix array.
        => Elements deleted = 3+3 = 6.

For 28 in suffix array:
        => The lower bound is 28 in the prefix array.
        => The index for both of them is same, that is the same element is considered twice.

Hence maximum 6 elements can be deleted.

Follow the given steps to solve the problem:

  • Initialize prefix sum and suffix sum array of size N, and assign their each element equal to the given array element.
  • Calculate the prefix sum and suffix sum and store them in their respective arrays.
  • iterate over the suffix sum array from end:
    • Perform lower bound on prefix sum array for that sum.
    • Get the index of the lower bound.
    • If the lower bound value and suffix sum are the same, calculate the total number of elements deleted.
  • Update the answer to store the maximum number of elements.

Below is the implementation for the above approach.

C++
// C++ code to implement the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the maximum number // of elements that can be deleted void solve(int v[], int n) {     vector<int> pref(n);     vector<int> suff(n);      // Storing the same value of the array in     // prefix and suffix array     for (int i = 0; i < n; i++) {         pref[i] = suff[i] = v[i];     }      // Calculating prefix sum     for (int i = 1; i < n; i++) {         pref[i] = pref[i] + pref[i - 1];     }      // Calculating suffix sum     for (int i = n - 2; i >= 0; i--) {         suff[i] = suff[i] + suff[i + 1];     }      // Initializing answer with 0     int ans = 0;      for (int i = n - 1; i >= 1; i--) {          // Finding the lower bound of the         // element with suffix sum         auto z = lower_bound(pref.begin(),                              pref.begin() + i - 1, suff[i]);          // Calculating the index         int idx = z - pref.begin();          // If the value at index matches with         // suffix sum we will calculate the         // total number of elements         if (pref[idx] == suff[i]) {             int temp = 0;             temp = temp + (n - i);             temp = temp + (idx + 1);              // Updating the answer to store             // the maximum             ans = max(ans, temp);         }     }      // Printing answer     cout << ans; }  // Driver code int main() {     int arr[] = { 70, 80, 85, 70, 80 };     int N = sizeof(arr) / sizeof(arr[0]);      // Function call     solve(arr, N);      return 0; } 
Java
// Java code to implement the above approach import java.io.*;  class GFG {   public static int lower_bound(int arr[], int l, int r,                                 int key)   {     int low = l;     int high = r - 1;     while (low < high) {       int mid = low + (high - low) / 2;       if (arr[mid] >= key) {         high = mid;       }       else {         low = mid + 1;       }     }     return low;   }   // Function to find the maximum number   // of elements that can be deleted   public static void solve(int v[], int n)   {     int pref[] = new int[n];     int suff[] = new int[n];      // Storing the same value of the array in     // prefix and suffix array     for (int i = 0; i < n; i++) {       pref[i] = suff[i] = v[i];     }      // Calculating prefix sum     for (int i = 1; i < n; i++) {       pref[i] = pref[i] + pref[i - 1];     }      // Calculating suffix sum     for (int i = n - 2; i >= 0; i--) {       suff[i] = suff[i] + suff[i + 1];     }      // Initializing answer with 0     int ans = 0;      for (int i = n - 1; i >= 1; i--) {        // Finding the lower bound of the       // element with suffix sum       int idx = lower_bound(pref, 0, i - 1, suff[i]);        // If the value at index matches with       // suffix sum we will calculate the       // total number of elements       if (pref[idx] == suff[i]) {         int temp = 0;         temp = temp + (n - i);         temp = temp + (idx + 1);          // Updating the answer to store         // the maximum         ans = Math.max(ans, temp);       }     }      // Printing answer     System.out.print(ans);   }    // Driver Code   public static void main(String[] args)   {     int arr[] = { 70, 80, 85, 70, 80 };     int N = arr.length;      // Function call     solve(arr, N);   } }  // This code is contributed by Rohit Pradhan 
Python3
# python3 code to implement the above approach from bisect import bisect_left  # Function to find the maximum number # of elements that can be deleted def solve(v, n):      pref = [0 for _ in range(n)]     suff = [0 for _ in range(n)]      # Storing the same value of the array in     # prefix and suffix array     for i in range(0, n):         pref[i] = suff[i] = v[i]      # Calculating prefix sum     for i in range(1, n):         pref[i] = pref[i] + pref[i - 1]      # Calculating suffix sum     for i in range(n-2, -1, -1):         suff[i] = suff[i] + suff[i + 1]      # Initializing answer with 0     ans = 0      for i in range(n-1, 0, -1):          # Finding the lower bound of the         # element with suffix sum         z = bisect_left(pref, suff[i], lo=0, hi=i - 1)          # Calculating the index         idx = z          # If the value at index matches with         # suffix sum we will calculate the         # total number of elements         if (pref[idx] == suff[i]):             temp = 0             temp = temp + (n - i)             temp = temp + (idx + 1)              # Updating the answer to store             # the maximum             ans = max(ans, temp)      # Printing answer     print(ans)  # Driver code if __name__ == "__main__":      arr = [70, 80, 85, 70, 80]     N = len(arr)      # Function call     solve(arr, N)      # This code is contributed by rakeshsahni 
C#
// C# program for the above approach using System; using System.Collections.Generic;  public class GFG{    public static int lower_bound(int[] arr, int l, int r,                                 int key)   {     int low = l;     int high = r - 1;     while (low < high) {       int mid = low + (high - low) / 2;       if (arr[mid] >= key) {         high = mid;       }       else {         low = mid + 1;       }     }     return low;   }   // Function to find the maximum number   // of elements that can be deleted   public static void solve(int[] v, int n)   {     int[] pref = new int[n];     int[] suff = new int[n];      // Storing the same value of the array in     // prefix and suffix array     for (int i = 0; i < n; i++) {       pref[i] = suff[i] = v[i];     }      // Calculating prefix sum     for (int i = 1; i < n; i++) {       pref[i] = pref[i] + pref[i - 1];     }      // Calculating suffix sum     for (int i = n - 2; i >= 0; i--) {       suff[i] = suff[i] + suff[i + 1];     }      // Initializing answer with 0     int ans = 0;      for (int i = n - 1; i >= 1; i--) {        // Finding the lower bound of the       // element with suffix sum       int idx = lower_bound(pref, 0, i - 1, suff[i]);        // If the value at index matches with       // suffix sum we will calculate the       // total number of elements       if (pref[idx] == suff[i]) {         int temp = 0;         temp = temp + (n - i);         temp = temp + (idx + 1);          // Updating the answer to store         // the maximum         ans = Math.Max(ans, temp);       }     }      // Printing answer     Console.Write(ans);   }    static public void Main ()   {     int[] arr = { 70, 80, 85, 70, 80 };     int N = arr.Length;      // Function call     solve(arr, N);   } }  // This code is contributed by sanjoy_62. 
JavaScript
// JavaScript code to implement the above approach  let lowerBound = (A,N, T) => {   let i = 0,       j = N;   while (i < j) {       let k = Math.floor((i + j) / 2);       if (A[k] < T)           i = k + 1;       else           j = k;   }   return i; };  // Function to find the maximum number // of elements that can be deleted function solve( v,  n) {     let pref = new Array(n);     let suff = new Array(n);      // Storing the same value of the array in     // prefix and suffix array     for (let i = 0; i < n; i++) {         pref[i] = suff[i] = v[i];     }      // Calculating prefix sum     for (let i = 1; i < n; i++) {         pref[i] = pref[i] + pref[i - 1];     }      // Calculating suffix sum     for (let i = n - 2; i >= 0; i--) {         suff[i] = suff[i] + suff[i + 1];     }      // Initializing answer with 0     let ans = 0;      for (let i = n - 1; i >= 1; i--) {          // Finding the lower bound of the         // element with suffix sum         let z = lowerBound(pref,                               i - 1, suff[i]);          // Calculating the index         let idx = z;          // If the value at index matches with         // suffix sum we will calculate the         // total number of elements         if (pref[idx] == suff[i]) {             let temp = 0;             temp = temp + (n - i);             temp = temp + (idx + 1);              // Updating the answer to store             // the maximum             ans = Math.max(ans, temp);         }     }      // Printing answer     console.log(ans); }  // Driver code      let arr = [ 70, 80, 85, 70, 80 ];     let N = arr.length;      // Function call     solve(arr, N); 

Output
4

Time Complexity: O(N * logN)
Space Complexity: O(N)


Next Article
Rearrange array elements to maximize the sum of MEX of all prefix arrays

H

heyy2001
Improve
Article Tags :
  • Greedy
  • DSA
  • Arrays
  • Binary Search
  • prefix-sum
Practice Tags :
  • Arrays
  • Binary Search
  • Greedy
  • prefix-sum

Similar Reads

  • 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
  • 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
  • Maximize non decreasing Array size by replacing Subarray with sum
    Given an array arr[] of size N. In one operation only one subarray can be selected and replaced with the sum of the subarray. The task is to find the maximum size of the array after making it non-decreasing. Examples: Input: N = 5, arr[] = {5, 1, 6, 6, 6}Output: 4Explanation: maximum size non-decrea
    15+ min read
  • Rearrange array elements to maximize the sum of MEX of all prefix arrays
    Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
    7 min read
  • Index with Minimum sum of prefix and suffix sums in an Array
    Given an array of integers. The task is to find the index [Tex]i [/Tex]in the array at which the value of prefixSum(i) + suffixSum(i) is minimum.Note: PrefixSum(i) = The sum of first i numbers of the array.SuffixSum(i) = the sum of last N - i + 1 numbers of the array.1-based indexing is considered f
    10 min read
  • Minimum common sum from K arrays after removing some part of their suffix
    Given K (K > 2) arrays of different sizes in a 2D list arr[][] where elements in each array are non-negative. Find the minimum common sum of K arrays after removing part of the suffix(possibly none) from each array. Examples: Input: K = 3, arr = {{5, 2, 4}, {1, 4, 1, 1}, {2, 3}}Output: 5Explanati
    7 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 sum of array elements removed by performing the given operations
    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 an
    8 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
  • Maximize point to reduce Array by replacing Subarray with its sum
    Given an array arr[] of size, N, the task is to maximize the score to reduce the array to a single element by replacing any subarray with its sum where the score of one such operation is the product of subarray length and the minimum value of that subarray. Examples:Input: N = 2, arr[] = {1, 5}Outpu
    15 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