Skip to content
Related Articles

Related Articles

K-th Largest Sum Contiguous Subarray

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 17 Oct, 2022
Improve Article
Save Article

Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers that has both negative and positive numbers.

Examples: 

Input: a[] = {20, -5, -1}, K = 3
Output: 14
Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) 
so the 3rd largest sum is 14.

Input: a[] = {10, -10, 20, -40}, k = 6
Output: -10
Explanation: The 6th largest sum among
sum of all contiguous subarrays is -10.

Brute force Approach: Store all the contiguous sums in another array and sort it and print the Kth largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order)

Kth largest sum contiguous subarray using Min-Heap:

The key idea is to store the pre-sum of the array in a sum[] array. One can find the sum of contiguous subarray from index i to j as sum[j] – sum[i-1]. Now generate all possible contiguous subarray sums and push them into the Min-Heap only if the size of Min-Heap is less than K or the current sum is greater than the root of the Min-Heap. In the end, the root of the Min-Heap is the required answer

Follow the given steps to solve the problem using the above approach:

  • Create a prefix sum array of the input array
  • Create a Min-Heap that stores the subarray sum
  • Iterate over the given array using the variable i such that 1 <= i <= N, here i denotes the starting point of the subarray
    • Create a nested loop inside this loop using a variable j such that i <= j <= N, here j denotes the ending point of the subarray
      • Calculate the sum of the current subarray represented by i and j, using the prefix sum array
      • If the size of the Min-Heap is less than K, then push this sum into the heap
      • Otherwise, if the current sum is greater than the root of the Min-Heap, then pop out the root and push the current sum into the Min-Heap
  • Now the root of the Min-Heap denotes the Kth largest sum, Return it

Below is the implementation of the above approach:

C++




// C++ program to find the K-th largest sum
// of subarray
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate Kth largest element
// in contiguous subarray sum
int kthLargestSum(int arr[], int N, int K)
{
    // array to store prefix sums
    int sum[N + 1];
    sum[0] = 0;
    sum[1] = arr[0];
    for (int i = 2; i <= N; i++)
        sum[i] = sum[i - 1] + arr[i - 1];
 
    // priority_queue of min heap
    priority_queue<int, vector<int>, greater<int> > Q;
 
    // loop to calculate the contiguous subarray
    // sum position-wise
    for (int i = 1; i <= N; i++) {
 
        // loop to traverse all positions that
        // form contiguous subarray
        for (int j = i; j <= N; j++) {
            // calculates the contiguous subarray
            // sum from j to i index
            int x = sum[j] - sum[i - 1];
 
            // if queue has less than k elements,
            // then simply push it
            if (Q.size() < K)
                Q.push(x);
 
            else {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                if (Q.top() < x) {
                    Q.pop();
                    Q.push(x);
                }
            }
        }
    }
 
    // the top element will be then kth
    // largest element
    return Q.top();
}
 
// Driver's code
int main()
{
    int a[] = { 10, -10, 20, -40 };
    int N = sizeof(a) / sizeof(a[0]);
    int K = 6;
 
    // Function call
    cout << kthLargestSum(a, N, K);
    return 0;
}


Java




// Java program to find the K-th
// largest sum of subarray
import java.util.*;
 
class KthLargestSumSubArray {
   
    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int arr[], int N, int K)
    {
        // array to store prefix sums
        int sum[] = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];
 
        // priority_queue of min heap
        PriorityQueue<Integer> Q
            = new PriorityQueue<Integer>();
 
        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {
 
            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];
 
                // if queue has less then k elements,
                // then simply push it
                if (Q.size() < K)
                    Q.add(x);
 
                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    if (Q.peek() < x) {
                        Q.poll();
                        Q.add(x);
                    }
                }
            }
        }
 
        // the top element will be then kth
        // largest element
        return Q.poll();
    }
 
    // Driver's Code
    public static void main(String[] args)
    {
        int a[] = new int[] { 10, -10, 20, -40 };
        int N = a.length;
        int K = 6;
 
        // Function call
        System.out.println(kthLargestSum(a, N, K));
    }
}
 
/* This code is contributed by Danish Kaleem */


Python3




# Python program to find the K-th largest sum
# of subarray
import heapq
 
# function to calculate Kth largest element
# in contiguous subarray sum
 
 
def kthLargestSum(arr, N, K):
 
    # array to store prefix sums
    sum = []
    sum.append(0)
    sum.append(arr[0])
    for i in range(2, N + 1):
        sum.append(sum[i - 1] + arr[i - 1])
 
    # priority_queue of min heap
    Q = []
    heapq.heapify(Q)
 
    # loop to calculate the contiguous subarray
    # sum position-wise
    for i in range(1, N + 1):
 
        # loop to traverse all positions that
        # form contiguous subarray
        for j in range(i, N + 1):
            x = sum[j] - sum[i - 1]
 
            # if queue has less then k elements,
            # then simply push it
            if len(Q) < K:
                heapq.heappush(Q, x)
            else:
                # it the min heap has equal to
                # k elements then just check
                # if the largest kth element is
                # smaller than x then insert
                # else its of no use
                if Q[0] < x:
                    heapq.heappop(Q)
                    heapq.heappush(Q, x)
 
    # the top element will be then kth
    # largest element
    return Q[0]
 
 
# Driver's code
if __name__ == "__main__":
    a = [10, -10, 20, -40]
    N = len(a)
    K = 6
 
    # Function call
    print(kthLargestSum(a, N, K))
 
 
# This code is contributed by Kumar Suman


C#




// C# program to find the K-th
// largest sum of subarray
 
using System;
using System.Collections.Generic;
public class KthLargestSumSubArray {
 
    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int[] arr, int N, int K)
    {
 
        // array to store prefix sums
        int[] sum = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];
 
        // priority_queue of min heap
        List<int> Q = new List<int>();
 
        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {
 
            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];
 
                // if queue has less then k elements,
                // then simply push it
                if (Q.Count < K)
                    Q.Add(x);
 
                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    Q.Sort();
                    if (Q[0] < x) {
                        Q.RemoveAt(0);
                        Q.Add(x);
                    }
                }
                Q.Sort();
            }
        }
 
        // the top element will be then Kth
        // largest element
        return Q[0];
    }
 
    // Driver's Code
    public static void Main(String[] args)
    {
        int[] a = new int[] { 10, -10, 20, -40 };
        int N = a.Length;
        int K = 6;
 
        // Function call
        Console.WriteLine(kthLargestSum(a, N, K));
    }
}
 
// This code contributed by Rajput-Ji


JavaScript




// Javascript program to find the k-th largest sum
// of subarray
 
// function to calculate kth largest element
// in contiguous subarray sum
function kthLargestSum(arr, n, k)
{
    // array to store prefix sums
    var sum = new Array(n + 1);
    sum[0] = 0;
    sum[1] = arr[0];
    for (var i = 2; i <= n; i++)
        sum[i] = sum[i - 1] + arr[i - 1];
 
    // priority_queue of min heap
    var Q = [];
 
    // loop to calculate the contiguous subarray
    // sum position-wise
    for (var i = 1; i <= n; i++)
    {
 
        // loop to traverse all positions that
        // form contiguous subarray
        for (var j = i; j <= n; j++)
        {
            // calculates the contiguous subarray
            // sum from j to i index
            var x = sum[j] - sum[i - 1];
 
            // if queue has less then k elements,
            // then simply push it
            if (Q.length < k)
                Q.push(x);
 
            else
            {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                Q.sort();
                if (Q[0] < x)
                {
                    Q.pop();
                    Q.push(x);
                }
            }
             
            Q.sort();
        }
    }
 
    // the top element will be then kth
    // largest element
    return Q[0];
}
 
// Driver program to test above function
var a = [ 10, -10, 20, -40 ];
var n = a.length;
var k = 6;
 
// calls the function to find out the
// k-th largest sum
document.write(kthLargestSum(a, n, k));


C++




// C++ program to find the K-th largest sum
// of subarray
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate Kth largest element
// in contiguous subarray sum
int kthLargestSum(int arr[], int N, int K)
{
    // array to store prefix sums
    int sum[N + 1];
    sum[0] = 0;
    sum[1] = arr[0];
    for (int i = 2; i <= N; i++)
        sum[i] = sum[i - 1] + arr[i - 1];
 
    // priority_queue of min heap
    priority_queue<int, vector<int>, greater<int> > Q;
 
    // loop to calculate the contiguous subarray
    // sum position-wise
    for (int i = 1; i <= N; i++) {
 
        // loop to traverse all positions that
        // form contiguous subarray
        for (int j = i; j <= N; j++) {
            // calculates the contiguous subarray
            // sum from j to i index
            int x = sum[j] - sum[i - 1];
 
            // if queue has less than k elements,
            // then simply push it
            if (Q.size() < K)
                Q.push(x);
 
            else {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                if (Q.top() < x) {
                    Q.pop();
                    Q.push(x);
                }
            }
        }
    }
 
    // the top element will be then kth
    // largest element
    return Q.top();
}
 
// Driver's code
int main()
{
    int a[] = { 10, -10, 20, -40 };
    int N = sizeof(a) / sizeof(a[0]);
    int K = 6;
 
    // Function call
    cout << kthLargestSum(a, N, K);
    return 0;
}


Java




// Java program to find the K-th
// largest sum of subarray
import java.util.*;
 
class KthLargestSumSubArray {
   
    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int arr[], int N, int K)
    {
        // array to store prefix sums
        int sum[] = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];
 
        // priority_queue of min heap
        PriorityQueue<Integer> Q
            = new PriorityQueue<Integer>();
 
        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {
 
            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];
 
                // if queue has less than k elements,
                // then simply push it
                if (Q.size() < K)
                    Q.add(x);
 
                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    if (Q.peek() < x) {
                        Q.poll();
                        Q.add(x);
                    }
                }
            }
        }
 
        // the top element will be then kth
        // largest element
        return Q.poll();
    }
 
    // Driver's Code
    public static void main(String[] args)
    {
        int a[] = new int[] { 10, -10, 20, -40 };
        int N = a.length;
        int K = 6;
 
        // Function call
        System.out.println(kthLargestSum(a, N, K));
    }
}
 
/* This code is contributed by Danish Kaleem */


Python3




# Python program to find the K-th largest sum
# of subarray
import heapq
 
# function to calculate Kth largest element
# in contiguous subarray sum
 
 
def kthLargestSum(arr, N, K):
 
    # array to store prefix sums
    sum = []
    sum.append(0)
    sum.append(arr[0])
    for i in range(2, N + 1):
        sum.append(sum[i - 1] + arr[i - 1])
 
    # priority_queue of min heap
    Q = []
    heapq.heapify(Q)
 
    # loop to calculate the contiguous subarray
    # sum position-wise
    for i in range(1, N + 1):
 
        # loop to traverse all positions that
        # form contiguous subarray
        for j in range(i, N + 1):
            x = sum[j] - sum[i - 1]
 
            # if queue has less than k elements,
            # then simply push it
            if len(Q) < K:
                heapq.heappush(Q, x)
            else:
                # it the min heap has equal to
                # k elements then just check
                # if the largest kth element is
                # smaller than x then insert
                # else its of no use
                if Q[0] < x:
                    heapq.heappop(Q)
                    heapq.heappush(Q, x)
 
    # the top element will be then kth
    # largest element
    return Q[0]
 
 
# Driver's code
if __name__ == "__main__":
    a = [10, -10, 20, -40]
    N = len(a)
    K = 6
 
    # Function call
    print(kthLargestSum(a, N, K))
 
 
# This code is contributed by Kumar Suman


C#




// C# program to find the K-th
// largest sum of subarray
 
using System;
using System.Collections.Generic;
public class KthLargestSumSubArray {
 
    // function to calculate Kth largest
    // element in contiguous subarray sum
    static int kthLargestSum(int[] arr, int N, int K)
    {
 
        // array to store prefix sums
        int[] sum = new int[N + 1];
        sum[0] = 0;
        sum[1] = arr[0];
        for (int i = 2; i <= N; i++)
            sum[i] = sum[i - 1] + arr[i - 1];
 
        // priority_queue of min heap
        List<int> Q = new List<int>();
 
        // loop to calculate the contiguous subarray
        // sum position-wise
        for (int i = 1; i <= N; i++) {
 
            // loop to traverse all positions that
            // form contiguous subarray
            for (int j = i; j <= N; j++) {
                // calculates the contiguous subarray
                // sum from j to i index
                int x = sum[j] - sum[i - 1];
 
                // if queue has less than k elements,
                // then simply push it
                if (Q.Count < K)
                    Q.Add(x);
 
                else {
                    // it the min heap has equal to
                    // k elements then just check
                    // if the largest kth element is
                    // smaller than x then insert
                    // else its of no use
                    Q.Sort();
                    if (Q[0] < x) {
                        Q.RemoveAt(0);
                        Q.Add(x);
                    }
                }
                Q.Sort();
            }
        }
 
        // the top element will be then Kth
        // largest element
        return Q[0];
    }
 
    // Driver's Code
    public static void Main(String[] args)
    {
        int[] a = new int[] { 10, -10, 20, -40 };
        int N = a.Length;
        int K = 6;
 
        // Function call
        Console.WriteLine(kthLargestSum(a, N, K));
    }
}
 
// This code contributed by Rajput-Ji


JavaScript




// Javascript program to find the k-th largest sum
// of subarray
 
// function to calculate kth largest element
// in contiguous subarray sum
function kthLargestSum(arr, n, k)
{
    // array to store prefix sums
    var sum = new Array(n + 1);
    sum[0] = 0;
    sum[1] = arr[0];
    for (var i = 2; i <= n; i++)
        sum[i] = sum[i - 1] + arr[i - 1];
 
    // priority_queue of min heap
    var Q = [];
 
    // loop to calculate the contiguous subarray
    // sum position-wise
    for (var i = 1; i <= n; i++)
    {
 
        // loop to traverse all positions that
        // form contiguous subarray
        for (var j = i; j <= n; j++)
        {
            // calculates the contiguous subarray
            // sum from j to i index
            var x = sum[j] - sum[i - 1];
 
            // if queue has less than k elements,
            // then simply push it
            if (Q.length < k)
                Q.push(x);
 
            else
            {
                // it the min heap has equal to
                // k elements then just check
                // if the largest kth element is
                // smaller than x then insert
                // else its of no use
                Q.sort();
                if (Q[0] < x)
                {
                    Q.pop();
                    Q.push(x);
                }
            }
             
            Q.sort();
        }
    }
 
    // the top element will be then kth
    // largest element
    return Q[0];
}
 
// Driver program to test above function
var a = [ 10, -10, 20, -40 ];
var n = a.length;
var k = 6;
 
// calls the function to find out the
// k-th largest sum
document.write(kthLargestSum(a, n, k));


Output

-10

Time Complexity: O(N2 log K) 
Auxiliary Space: O(N), but this can be reduced to O(K) for min-heap and we can store the prefix sum array in the input array itself as it is of no use.

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!