Open In App

JavaScript Program for K-th Largest Sum Contiguous Subarray

Last Updated : 04 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about K-th Largest Sum Contiguous Subarray in JavaScript. K-th Largest Sum Contiguous Subarray refers to finding the K-th largest sum among all possible contiguous subarrays within a given array of numbers, It involves exploring different subarray lengths and positions to determine the K-th largest sum efficiently.

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.

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using Brute force

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)

Example: In this example, we are using the above-explained approach.

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)
{
    let result=[];
   
    // Generate all subarrays
    for (let i = 0; i < N; i++) {
        let sum = 0;
        for (let j = i; j < N; j++) {
            sum += arr[j];
            result.push(sum);
        }
    }
   
    // Sort in decreasing order
    result.sort();
    result.reverse();
   
    // return the Kth largest sum
    return result[K - 1];
}
   
// Driver's code
    let a = [20, -5, -1 ];
    let N = a.length;
    let K = 3;
   
    // Function call
    console.log(kthLargestSum(a, N, K));


Output

14

Approach 2: 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

Example: In this example we are using the abobe-explained approach.

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
    let sum = new Array(n + 1);
    sum[0] = 0;
    sum[1] = arr[0];
    for (let i = 2; i <= n; i++)
        sum[i] = sum[i - 1] + arr[i - 1];
  
    // Priority_queue of min heap
    let Q = [];
  
    // Loop to calculate the contiguous subarray
    // sum position-wise
    for (let i = 1; i <= n; i++) {
  
        // Loop to traverse all positions that
        // form contiguous subarray
        for (let j = i; j <= n; j++) {
            // calculates the contiguous subarray
            // sum from j to i index
            let 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 {
                // If 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
let a = [10, -10, 20, -40];
let n = a.length;
let k = 6;
  
// Calls the function to find out the
// k-th largest sum
console.log(kthLargestSum(a, n, k));


Output

-10

Approach 3: Using Prefix Sum and Sorting

The basic idea behind the Prefix Sum and Sorting approach is to create a prefix sum array and use it to calculate all possible subarray sums. The subarray sums are then sorted in decreasing order using the sort() function. Finally, the K-th largest sum of contiguous subarray is returned from the sorted vector of subarray sums.

Follow the Steps to implement the approach:

  • Create a prefix sum array of the given array.
  • Create a vector to store all possible subarray sums by subtracting prefix sums.
  • Sort the vector of subarray sums in decreasing order using the sort() function.
  • Return the K-th largest sum of contiguous subarray from the sorted vector of subarray sums.

Example: In this example we are using the above-explained approach.

Javascript




function kthLargestSum(arr, k) {
    let n = arr.length;
  
    // Create a prefix sum array.
    let prefixSum = new Array(n + 1).fill(0);
    prefixSum[0] = 0;
    for (let i = 1; i <= n; i++) {
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
    }
  
    // Create an array to store all possible subarray sums.
    let subarraySums = [];
    for (let i = 0; i <= n; i++) {
        for (let j = i + 1; j <= n; j++) {
            subarraySums.push(prefixSum[j] - prefixSum[i]);
        }
    }
  
    // Sort the subarray sums in decreasing order.
    subarraySums.sort((a, b) => b - a);
  
    // Return the K-th largest sum of contiguous subarray.
    return subarraySums[k - 1];
}
  
// Driver Code
let arr = [10, -10, 20, -40];
let k = 6;
console.log(kthLargestSum(arr, k));


Output

-10


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads