Skip to content
Related Articles

Related Articles

Improve Article

Subarray with largest sum after excluding its maximum element

  • Difficulty Level : Hard
  • Last Updated : 08 Jun, 2021

Given an array arr[], the task is to find the starting and ending indices of the subarray with the largest sum after excluding its maximum element.
Examples: 

Input: arr[] = {5, -2, 10, -1, 4} 
Output: 1 5 
Explanation: 
Subarray[1:5] = {5, -2, 10, -1, 4} 
Sum of subarray excluding maximum element = 5 + (-2) + (-1) + 4 = 6
Input: arr[] = {5, 2, 5, 3, -30, -30, 6, 9} 
Output: 1 4 
Explanation: 
Subarray[1:4] = {5, 2, 5, 3} 
Sum of subarray excluding maximum element = 5 + 2 + 3 = 10 
 

Approach: The idea is to use the Kadane algorithm to solve this problem. 

  1. As in this problem we have to choose one element which is the maximum in the subarray.
  2. Therefore, we can choose all the positive elements from the array, and each time we can make elements greater than that element to INT_MIN, such that it is not included in the array.
  3. Finally, apply the Kadane algorithm to find the maximum sum subarray.
  4. If there are no positive elements in the array then we can choose any one element from the array to get the maximum sum as 0.

Below is the implementation of the above approach:
 

C++




// C++ implementation to find the
// maximum sum subarray such by
// excluding the maximum element
// from the subarray
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
// subarray by excluding the maximum
// element from the array
void maximumSumSubarray(int arr[], int n)
{
    unordered_map<int, int> mp;
 
    // Loop to store all the positive
    // elements in the map
    for (int i = 0; i < n; i++) {
 
        if (arr[i] >= 0
            && mp.find(arr[i])
                == mp.end())
 
            mp[arr[i]] = 1;
    }
 
    int first = 0;
    int last = 0;
    int ans = 0;
    int INF = 1e6;
 
    // Loop to iterating over the map
    // and considering as the maximum
    // element of the current including
    // subarray
    for (auto i : mp) {
 
        // Make the current
        // element maximum
        int mx = i.first;
 
        int curr = 0;
        int curr_start;
 
        // Iterate through array and
        // apply kadane's algorithm
        for (int j = 0; j < n; j++) {
            if (curr == 0)
                curr_start = j;
 
            // Condition if current element is
            // greater than mx then make
            // the element -infinity
            int val = arr[j] > mx
                        ? -INF
                        : arr[j];
 
            curr += val;
 
            if (curr < 0)
                curr = 0;
 
            if (curr > ans) {
                ans = curr;
 
                // Store the indices
                // in some variable
                first = curr_start;
                last = j;
            }
        }
    }
 
    cout << first + 1
        << " " << last + 1;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, -2, 10, -1, 4 };
 
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maximumSumSubarray(arr, size);
    return 0;
}

Java




// Java implementation to find the
// maximum sum subarray such by
// excluding the maximum element
// from the subarray
import java.util.*;
 
class GFG{
     
// Function to find the maximum sum
// subarray by excluding the maximum
// element from the array
static void maximumSumSubarray(int arr[], int n)
{
    Map<Integer, Integer> mp = new HashMap<>();
     
    // Loop to store all the positive
    // elements in the map
    for(int i = 0; i < n; i++)
    {
        if (arr[i] >= 0)
            mp.put(arr[i], 1);
    }
     
    int first = 0;
    int last = 0;
    int ans = 0;
    int INF = (int)1e6;
     
    // Loop to iterating over the map
    // and considering as the maximum
    // element of the current including
    // subarray
    for (Map.Entry<Integer,
                   Integer> i : mp.entrySet())
    {
         
        // Make the current
        // element maximum
        int mx = i.getKey();
        int curr = 0;
        int curr_start = -1;
         
        // Iterate through array and
        // apply kadane's algorithm
        for(int j = 0; j < n; j++)
        {
            if (curr == 0)
                curr_start = j;
                 
            // Condition if current element is
            // greater than mx then make
            // the element -infinity
            int val = arr[j] > mx ? -INF : arr[j];
            curr += val;
             
            if (curr < 0)
                curr = 0;
             
            if (curr > ans)
            {
                ans = curr;
                 
                // Store the indices
                // in some variable
                first = curr_start;
                last = j;
            }
        }
    }
    System.out.print((first + 1) + " " +
                      (last + 1));
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 5, -2, 10, -1, 4 };
    int size = arr.length;
     
    // Function call
    maximumSumSubarray(arr, size);
}
}
 
// This code is contributed by offbeat

Python3




# Python3 implementation to find
# the maximum sum subarray such
# by excluding the maximum
# element from the subarray
 
# Function to find the maximum sum
# subarray by excluding the maximum
# element from the array
def maximumSumSubarray(arr, n):
    mp = {}
 
    # Loop to store all the positive
    # elements in the map
    for i in range(n):
 
        if (arr[i] >= 0 and
            arr[i] not in mp):
            mp[arr[i]] = 1
 
    first = 0
    last = 0
    ans = 0
    INF = 1e6
 
    # Loop to iterating over the map
    # and considering as the maximum
    # element of the current including
    # subarray
    for i in mp:
 
        # Make the current
        # element maximum
        mx = i
 
        curr = 0
 
        # Iterate through array and
        # apply kadane's algorithm
        for j in range(n):
            if (curr == 0):
                curr_start = j
 
            # Condition if current element
            # is greater than mx then make
            # the element -infinity
            if arr[j] > mx:
                val =- INF
            else:
                val= arr[j];
 
            curr += val
 
            if (curr < 0):
                curr = 0
 
            if (curr > ans):
                ans = curr
 
                # Store the indices
                # in some variable
                first = curr_start
                last = j
 
    print(first + 1, last + 1)
 
# Driver Code
if __name__ == "__main__":
     
    arr = [ 5, -2, 10, -1, 4 ]
    size = len(arr)
 
    # Function Call
    maximumSumSubarray(arr, size)
 
# This code is contributed by chitranayal

C#




// C# implementation to find the
// maximum sum subarray such by
// excluding the maximum element
// from the subarray
using System;
using System.Collections.Generic;
class GFG{
     
// Function to find the maximum sum
// subarray by excluding the maximum
// element from the array
static void maximumSumSubarray(int []arr,
                               int n)
{
  Dictionary<int,
             int> mp = new Dictionary<int,
                                      int>();
 
  // Loop to store all the positive
  // elements in the map
  for(int i = 0; i < n; i++)
  {
    if (arr[i] >= 0)
      mp.Add(arr[i], 1);
  }
 
  int first = 0;
  int last = 0;
  int ans = 0;
  int INF = (int)1e6;
 
  // Loop to iterating over the map
  // and considering as the maximum
  // element of the current including
  // subarray
  foreach (KeyValuePair<int,
                        int> i in mp)
  {
    // Make the current
    // element maximum
    int mx = i.Key;
    int curr = 0;
    int curr_start = -1;
 
    // Iterate through array and
    // apply kadane's algorithm
    for(int j = 0; j < n; j++)
    {
      if (curr == 0)
        curr_start = j;
 
      // Condition if current element is
      // greater than mx then make
      // the element -infinity
      int val = arr[j] > mx ?
                -INF : arr[j];
      curr += val;
 
      if (curr < 0)
        curr = 0;
 
      if (curr > ans)
      {
        ans = curr;
 
        // Store the indices
        // in some variable
        first = curr_start;
        last = j;
      }
    }
  }
  Console.Write((first + 1) + " " +
                (last + 1));
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {5, -2, 10, -1, 4};
  int size = arr.Length;
 
  // Function call
  maximumSumSubarray(arr, size);
}
}
 
// This code is contributed by shikhasingrajput

Javascript




<script>
 
// JavaScript implementation to find the
// maximum sum subarray such by
// excluding the maximum element
// from the subarray
 
 
// Function to find the maximum sum
// subarray by excluding the maximum
// element from the array
function maximumSumSubarray(arr, n)
{
    var mp = new Map();
 
    // Loop to store all the positive
    // elements in the map
    for (var i = 0; i < n; i++) {
 
        if (arr[i] >= 0
            && !mp.has(arr[i]))
            mp.set(arr[i] , 1);
    }
 
    var first = 0;
    var last = 0;
    var ans = 0;
    var INF = 1000000;
 
    // Loop to iterating over the map
    // and considering as the maximum
    // element of the current including
    // subarray
    mp.forEach((value, key) => {
         
        // Make the current
        // element maximum
        var mx = key;
 
        var curr = 0;
        var curr_start;
 
        // Iterate through array and
        // apply kadane's algorithm
        for (var j = 0; j < n; j++) {
            if (curr == 0)
                curr_start = j;
 
            // Condition if current element is
            // greater than mx then make
            // the element -infinity
            var val = arr[j] > mx
                        ? -INF
                        : arr[j];
 
            curr += val;
 
            if (curr < 0)
                curr = 0;
 
            if (curr > ans) {
                ans = curr;
 
                // Store the indices
                // in some variable
                first = curr_start;
                last = j;
            }
        }
    });
 
    document.write( first + 1
        + " " + (last + 1));
}
 
// Driver Code
 
var arr = [5, -2, 10, -1, 4];
var size = arr.length;
 
// Function Call
maximumSumSubarray(arr, size);
 
 
</script>
Output: 
1 5

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :