Maximize deletions by removing prefix and suffix of Array with same sum
Last Updated : 16 Sep, 2022
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);
Time Complexity: O(N * logN)
Space Complexity: O(N)
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