Largest sum contiguous increasing subarray

Given an array of n positive distinct integers. The problem is to find the largest sum of contiguous increasing subarray in O(n) time complexity.

Examples :

Input : arr[] = {2, 1, 4, 7, 3, 6}
Output : 12
Contiguous Increasing subarray {1, 4, 7} = 12

Input : arr[] = {38, 7, 8, 10, 12}
Output : 38



A simple solution is to generate all subarrays and compute their sums. Finally return the subarray with maximum sum. Time complexity of this solution is O(n2).

An efficient solution is based on the fact that all elements are positive. So we consider longest increasing subarrays and compare their sums. To increasing subarrays cannot overlap, so our time complexity becomes O(n).

Algorithm:

Let arr be the array of size n
Let result be the required sum

int largestSum(arr, n) 
    result = INT_MIN  // Initialize result

    i = 0
    while i < n

        // Find sum of longest increasing subarray
        // starting with i
        curr_sum = arr[i];
    while i+1 < n && arr[i] < arr[i+1]
              curr_sum += arr[i+1];
          i++; 

        // If current sum is greater than current
        // result.
        if result < curr_sum
            result = curr_sum; 

        i++;
    return result

Below is the implementation of above algorithm.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of largest sum
// contiguous increasing subarray
#include <bits/stdc++.h>
using namespace std;
  
// Returns sum of longest
// increasing subarray.
int largestSum(int arr[], int n)
{
    // Initialize result
    int result = INT_MIN;
  
    // Note that i is incremented
    // by inner loop also, so overall
    // time complexity is O(n)
    for (int i = 0; i < n; i++)
    {
        // Find sum of longest 
        // increasing subarray 
        // starting from arr[i]
        int curr_sum = arr[i];
        while (i + 1 < n && 
               arr[i + 1] > arr[i])
        {
            curr_sum += arr[i + 1];
            i++;
        }
  
        // Update result if required
        if (curr_sum > result)
            result = curr_sum;
    }
  
    // required largest sum
    return result;
}
  
// Driver Code
int main()
{
    int arr[] = {1, 1, 4, 7, 3, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Largest sum = " 
         << largestSum(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of largest sum
// contiguous increasing subarray
  
class GFG
{
    // Returns sum of longest
    // increasing subarray.
    static int largestSum(int arr[], int n)
    {
        // Initialize result
        int result = -9999999
      
        // Note that i is incremented
        // by inner loop also, so overall
        // time complexity is O(n)
        for (int i = 0; i < n; i++)
        {
            // Find sum of longest 
            // increasing subarray
            // starting from arr[i]
            int curr_sum = arr[i];
            while (i + 1 < n && 
                   arr[i + 1] > arr[i])
            {
                curr_sum += arr[i + 1];
                i++;
            }
      
            // Update result if required
            if (curr_sum > result)
                result = curr_sum;
        }
      
        // required largest sum
        return result;
    }
      
    // Driver Code 
    public static void main (String[] args) 
    {
        int arr[] = {1, 1, 4, 7, 3, 6};
        int n = arr.length;
        System.out.println("Largest sum = "
                         largestSum(arr, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of largest 
# sum contiguous increasing subarray
  
# Returns sum of longest
# increasing subarray.
def largestSum(arr, n):
      
    # Initialize result
    result = -2147483648
  
    # Note that i is incremented 
    # by inner loop also, so overall
    # time complexity is O(n)
    for i in range(n):
      
        # Find sum of longest increasing 
        # subarray starting from arr[i]
        curr_sum = arr[i]
        while (i + 1 < n and 
               arr[i + 1] > arr[i]):
          
            curr_sum += arr[i + 1]
            i += 1
          
        # Update result if required
        if (curr_sum > result):
            result = curr_sum
      
    # required largest sum
    return result
  
# Driver Code
arr = [1, 1, 4, 7, 3, 6]
n = len(arr)
print("Largest sum = ", largestSum(arr, n))
  
# This code is contributed by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of largest sum
// contiguous increasing subarray
using System;
  
class GFG 
{
      
    // Returns sum of longest 
    // increasing subarray.
    static int largestSum(int []arr, 
                          int n)
    {
          
        // Initialize result
        int result = -9999999;
          
        // Note that i is incremented by 
        // inner loop also, so overall 
        // time complexity is O(n)
        for (int i = 0; i < n; i++)
        {
              
            // Find sum of longest increasing 
            // subarray starting from arr[i]
            int curr_sum = arr[i];
            while (i + 1 < n && 
                   arr[i + 1] > arr[i])
            {
                curr_sum += arr[i + 1];
                i++;
            }
      
            // Update result if required
            if (curr_sum > result)
                result = curr_sum;
        }
      
        // required largest sum
        return result;
    }
      
    // Driver code
    public static void Main () 
    {
        int []arr = {1, 1, 4, 7, 3, 6};
        int n = arr.Length;
        Console.Write("Largest sum = "
                    largestSum(arr, n));
    }
}
  
// This code is contributed 
// by Nitin Mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of largest sum
// contiguous increasing subarray
  
// Returns sum of longest 
// increasing subarray.
function largestSum($arr, $n)
{
    $INT_MIN = 0;
      
    // Initialize result
    $result = $INT_MIN
  
    // Note that i is incremented 
    // by inner loop also, so overall
    // time complexity is O(n)
    for ($i = 0; $i < $n; $i++)
    {
        // Find sum of longest 
        // increasing subarray
        // starting from arr[i]
        $curr_sum = $arr[$i];
        while ($i + 1 < $n && 
               $arr[$i + 1] > $arr[$i])
        {
            $curr_sum += $arr[$i + 1];
            $i++;
        }
  
        // Update result if required
        if ($curr_sum > $result)
            $result = $curr_sum;
    }
  
    // required largest sum
    return $result;
}
  
// Driver Code
{
    $arr = array(1, 1, 4, 7, 3, 6);
    $n = sizeof($arr) / sizeof($arr[0]);
    echo "Largest sum = "
          largestSum($arr, $n);
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

chevron_right



Output :

Largest sum = 12

Time Complexity : O(n)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : nitin mittal



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.