Largest sum subarray with at-least k numbers

Given an array, find the subarray (containing at least k numbers) which has the largest sum.

Examples:

Input : arr[] = {-4, -2, 1, -3} 
            k = 2
Output : -1
The sub array is {-2, 1}

Input : arr[] = {1, 1, 1, 1, 1, 1} 
            k = 2
Output : 6 
The sub array is {1, 1, 1, 1, 1, 1}

Asked in : Facebook



This problem is an extension of Largest Sum Subarray Problem.

1) We first compute maximum sum till every index and store it in an array maxSum[].
2) After filling the array, we use the sliding window concept of size k. Keep track of sum of current k elements. To compute sum of current window, remove first element of previous window and add current element. After getting the sum of current window, we add the maxSum of the previous window, if it is greater than current max, then update it else not.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find largest subarray sum with
// at-least k elements in it.
#include<bits/stdc++.h>
using namespace std;
  
// Returns maximum sum of a subarray with at-least
// k elements.
int maxSumWithK(int a[], int n, int k)
{
    // maxSum[i] is going to store maximum sum
    // till index i such that a[i] is part of the
    // sum.
    int maxSum[n];
    maxSum[0] = a[0];
  
    // We use Kadane's algorithm to fill maxSum[]
    // Below code is taken from method 3 of
    int curr_max = a[0];
    for (int i = 1; i < n; i++)
    {
        curr_max = max(a[i], curr_max+a[i]);
        maxSum[i] = curr_max;
    }
  
    // Sum of first k elements
    int sum = 0;
    for (int i = 0; i < k; i++)
        sum += a[i];
  
    // Use the concept of sliding window
    int result = sum;
    for (int i = k; i < n; i++)
    {
        // Compute sum of k elements ending
        // with a[i].
        sum = sum + a[i] - a[i-k];
  
        // Update result if required
        result = max(result, sum);
  
        // Include maximum sum till [i-k] also
        // if it increases overall max.
        result = max(result, sum + maxSum[i-k]);
    }
    return result;
}
  
// Driver code
int main()
{
    int a[] = {1, 2, 3, -10, -3};
    int k = 4;
    int n = sizeof(a)/sizeof(a[0]);
    cout << maxSumWithK(a, n, k);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find largest subarray sum with
// at-least k elements in it.
class Test
{
    // Returns maximum sum of a subarray with at-least
    // k elements.
    static int maxSumWithK(int a[], int n, int k)
    {
        // maxSum[i] is going to store maximum sum
        // till index i such that a[i] is part of the
        // sum.
        int maxSum[] = new int [n];
        maxSum[0] = a[0];
  
        // We use Kadane's algorithm to fill maxSum[]
        // Below code is taken from method 3 of
        int curr_max = a[0];
        for (int i = 1; i < n; i++)
        {
            curr_max = Math.max(a[i], curr_max+a[i]);
            maxSum[i] = curr_max;
        }
  
        // Sum of first k elements
        int sum = 0;
        for (int i = 0; i < k; i++)
            sum += a[i];
  
        // Use the concept of sliding window
        int result = sum;
        for (int i = k; i < n; i++)
        {
            // Compute sum of k elements ending
            // with a[i].
            sum = sum + a[i] - a[i-k];
  
            // Update result if required
            result = Math.max(result, sum);
  
            // Include maximum sum till [i-k] also
            // if it increases overall max.
            result = Math.max(result, sum + maxSum[i-k]);
        }
        return result;
    }
  
    // Driver method
    public static void main(String[] args)
    {
        int arr[] = {1, 2, 3, -10, -3};
        int k = 4;
        System.out.println(maxSumWithK(arr, arr.length, k));;
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find largest subarray 
# sum with at-least k elements in it.
  
# Returns maximum sum of a subarray
#  with at-least k elements.
def maxSumWithK(a, n, k):
   
    # maxSum[i] is going to store 
    # maximum sum till index i such
    # that a[i] is part of the sum.
    maxSum = [0 for i in range(n)]
    maxSum[0] = a[0]
  
    # We use Kadane's algorithm to fill maxSum[]
    # Below code is taken from method3 of
    curr_max = a[0]
    for i in range(1, n):
      
        curr_max = max(a[i], curr_max + a[i])
        maxSum[i] = curr_max
  
    # Sum of first k elements
    sum = 0
    for i in range(k):
        sum += a[i]
  
    # Use the concept of sliding window
    result = sum
    for i in range(k, n):
      
        # Compute sum of k elements 
        # ending with a[i].
        sum = sum + a[i] - a[i-k]
  
        # Update result if required
        result = max(result, sum)
  
        # Include maximum sum till [i-k] also
        # if it increases overall max.
        result = max(result, sum + maxSum[i-k])
      
    return result
  
# Driver code
a = [1, 2, 3, -10, -3]
k = 4
n = len(a)
print(maxSumWithK(a, n, k))
  
# This code is contributed by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find largest subarray sum with
// at-least k elements in it.
  
using System;
class Test
{
    // Returns maximum sum of a subarray with at-least
    // k elements.
    static int maxSumWithK(int[] a, int n, int k)
    {
        // maxSum[i] is going to store maximum sum
        // till index i such that a[i] is part of the
        // sum.
        int[] maxSum = new int [n];
        maxSum[0] = a[0];
   
        // We use Kadane's algorithm to fill maxSum[]
        // Below code is taken from method 3 of
        int curr_max = a[0];
        for (int i = 1; i < n; i++)
        {
            curr_max = Math.Max(a[i], curr_max+a[i]);
            maxSum[i] = curr_max;
        }
   
        // Sum of first k elements
        int sum = 0;
        for (int i = 0; i < k; i++)
            sum += a[i];
   
        // Use the concept of sliding window
        int result = sum;
        for (int i = k; i < n; i++)
        {
            // Compute sum of k elements ending
            // with a[i].
            sum = sum + a[i] - a[i-k];
   
            // Update result if required
            result = Math.Max(result, sum);
   
            // Include maximum sum till [i-k] also
            // if it increases overall max.
            result = Math.Max(result, sum + maxSum[i-k]);
        }
        return result;
    }
   
    // Driver method
    public static void Main()
    {
        int[] arr = {1, 2, 3, -10, -3};
        int k = 4;
        Console.Write(maxSumWithK(arr, arr.Length, k));;
    }
}

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find largest subarray 
// sum with at-least k elements in it.
  
// Returns maximum sum of a subarray
// with at-least k elements.
function maxSumWithK($a, $n, $k)
{
      
    // maxSum[i] is going to 
    // store maximum sum till
    // index i such that a[i]
    // is part of the sum.
    $maxSum[0] = $a[0];
  
    // We use Kadane's algorithm
    // to fill maxSum[] 
    $curr_max = $a[0];
    for ($i = 1; $i < $n; $i++)
    {
        $curr_max = max($a[$i], $curr_max+$a[$i]);
        $maxSum[$i] = $curr_max;
    }
  
    // Sum of first k elements
    $sum = 0;
    for ($i = 0; $i < $k; $i++)
        $sum += $a[$i];
  
    // Use the concept of 
    // sliding window
    $result = $sum;
    for ($i = $k; $i < $n; $i++)
    {
        // Compute sum of k 
        // elements ending
        // with a[i].
        $sum = $sum + $a[$i] - $a[$i - $k];
  
        // Update result if required
        $result = max($result, $sum);
  
        // Include maximum sum till [i-k] also
        // if it increases overall max.
        $result = max($result, $sum +
                    $maxSum[$i - $k]);
    }
    return $result;
}
  
    // Driver code
    $a= array (1, 2, 3, -10, -3);
    $k = 4;
    $n = sizeof($a);
    echo maxSumWithK($a, $n, $k);
  
// This code is contributed by m_kit
?>

chevron_right



Output:

-4

Time Complexity: O(n)

This article is contributed by Rakesh Kumar. 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 : jit_t, Ita_c