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 sum of remaining elements after every removal of the array half with greater sum
Next article icon

Maximize the sum of sum of the Array by removing end elements

Last Updated : 27 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 3. 
We can also delete 3 first and then 2, but in this case, the sum of sum = 2 + 0 = 2 
But since 3 is larger, therefore the output is 3.
Input: arr[] = {3, 1, 7, 2, 1} 
Output: 39 
Explanation: 
At first we will delete 1 from last, then the sum of remaining elements 
will be 13. 
Then delete 2 from last, then the sum of remaining elements will be 11. 
Then delete 3 from the beginning, then the sum of remaining elements will be 8. 
Then we delete 1, the remaining sum is 7 and then delete 7. 
Therefore the Sum of all remaining sums is 13 + 11 + 8 + 7 = 39, which is the maximum case. 
 

 

Approach: The idea is to use Greedy Algorithm to solve this problem. 
 

  1. First to calculate the total sum of the array.
  2. Then compare the elements on both ends and subtract the minimum value among the two, from the sum. This will make the remaining sum maximum.
  3. Then, add remaining sum to the result.
  4. Repeat the above steps till all the elements have been removed from the array. Then print the resultant sum.

Below is the implementation of the above approach:
 

C++




// C++ program to maximize the sum
// of sum of the Array by
// removing end elements
 
#include <iostream>
using namespace std;
 
// Function to find
// the maximum sum of sum
int maxRemainingSum(int arr[], int n)
{
    int sum = 0;
 
    // compute the sum of the whole array
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    int i = 0;
    int j = n - 1;
 
    int result = 0;
 
    // Traverse and remove the
    // minimum value from an end
    // to maximize the sum value
    while (i < j)
    {
        // If the left end element
        // is smaller than the right end
        if (arr[i] < arr[j])
        {
 
            // remove the left end element
            sum -= arr[i];
 
            i++;
        }
 
        // If the right end element
        // is smaller than the left end
        else
        {
 
            // remove the right end element
            sum -= arr[j];
            j--;
        }
 
        // Add the remaining element
        // sum in the result
        result += sum;
    }
 
    // Return the maximum
    // sum of sum
    return result;
}
 
// Driver code
int main()
{
    int arr[] = {3, 1, 7, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << maxRemainingSum(arr, N);
 
    return 0;
}
 
 

Java




import java.util.Arrays;
 
public class MaxRemainingSum {
    // Function to find the maximum sum of the array
    // by removing end elements
    static int maxRemainingSum(int[] arr, int n) {
        int sum = Arrays.stream(arr).sum();
 
        int i = 0;
        int j = n - 1;
        int result = 0;
 
        // Traverse and remove the
        // minimum value from an end
        // to maximize the sum value
        while (i < j) {
            // If the left end element
            // is smaller than the right end
            if (arr[i] < arr[j]) {
                // remove the left end element
                sum -= arr[i];
                i++;
            } else {
                // remove the right end element
                sum -= arr[j];
                j--;
            }
 
            // Add the remaining element
            // sum in the result
            result += sum;
        }
 
        // Return the maximum sum of sum
        return result;
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {3, 1, 7, 2, 1 };
        int N = arr.length;
 
        System.out.println(maxRemainingSum(arr, N));
    }
}
 
 

Python3




def max_remaining_sum(arr, n):
    total_sum = sum(arr)
    i = 0
    j = n - 1
    result = 0
 
    # Traverse and remove the
    # minimum value from an end
    # to maximize the sum value
    while i < j:
        # If the left end element
        # is smaller than the right end
        if arr[i] < arr[j]:
            # remove the left end element
            total_sum -= arr[i]
            i += 1
        else:
            # remove the right end element
            total_sum -= arr[j]
            j -= 1
 
        # Add the remaining element
        # sum in the result
        result += total_sum
 
    # Return the maximum sum of sum
    return result
 
# Driver code
arr = [3, 1, 7, 2, 1 ]
N = len(arr)
 
print(max_remaining_sum(arr, N))
 
 

C#




using System;
 
class Program
{
    static int MaxRemainingSum(int[] arr, int n)
    {
        int sum = 0;
 
        // compute the sum of the whole array
        for (int i = 0; i < n; i++)
            sum += arr[i];
 
        int left = 0;
        int right = n - 1;
        int result = 0;
 
        // Traverse and remove the
        // minimum value from an end
        // to maximize the sum value
        while (left < right)
        {
            // If the left end element
            // is smaller than the right end
            if (arr[left] < arr[right])
            {
                // remove the left end element
                sum -= arr[left];
                left++;
            }
            else
            {
                // remove the right end element
                sum -= arr[right];
                right--;
            }
 
            // Add the remaining element
            // sum in the result
            result += sum;
        }
 
        // Return the maximum sum of sum
        return result;
    }
 
    static void Main()
    {
        int[] arr = {3, 1, 7, 2, 1  };
        int N = arr.Length;
 
        Console.WriteLine(MaxRemainingSum(arr, N));
    }
}
 
 

Javascript




function maxRemainingSum(arr) {
    let sum = 0;
 
    // Compute the sum of the whole array
    for (let i = 0; i < arr.length; i++)
        sum += arr[i];
 
    let left = 0;
    let right = arr.length - 1;
    let result = 0;
 
    // Traverse and remove the minimum value from an end
    // to maximize the sum value
    while (left < right) {
        // If the left end element is smaller than the right end
        if (arr[left] < arr[right]) {
            // Remove the left end element
            sum -= arr[left];
            left++;
        } else {
            // Remove the right end element
            sum -= arr[right];
            right--;
        }
 
        // Add the remaining element sum in the result
        result += sum;
    }
 
    // Return the maximum sum of sum
    return result;
}
 
// Test the function
const arr = [3, 1, 7, 2, 1 ];
console.log(maxRemainingSum(arr));
 
 
Output
39 

Time complexity: O(N), where N is the size of the given array.
Auxiliary space: O(1), as constant space is used.



Next Article
Maximize sum of remaining elements after every removal of the array half with greater sum
author
apurvaraj
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • 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
  • 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 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
  • 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 sum of remaining elements after every removal of the array half with greater sum
    Given an array arr[] consisting of N integers, the task is to maximize the resultant sum obtained after adding remaining elements after every removal of the array half with maximum sum. Array can be divided into two non-empty halves left[] and right[] where left[] contains the elements from the indi
    15+ min read
  • Maximize deletions by removing prefix and suffix of Array with same sum
    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 fr
    10 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
  • Maximize the sum of modulus with every Array element
    Given an array A[] consisting of N positive integers, the task is to find the maximum possible value of: F(M) = M % A[0] + M % A[1] + .... + M % A[N -1] where M can be any integer value Examples: Input: arr[] = {3, 4, 6} Output: 10 Explanation: The maximum sum occurs for M = 11. (11 % 3) + (11 % 4)
    4 min read
  • Maximize the cost of reducing array elements
    Given an array arr[] of N positive integers. We can choose any one index(say K) of the array and reduce all the elements of the array from index 0 to K - 1 by 1. The cost of this operation is K. If at any index(say idx) element is reduced to 0 then we can't perform this operation in the range [idx,
    6 min read
  • Maximize count of array elements required to obtain given sum
    Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1. Examples: Input: arr[] =
    8 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