Open In App

JavaScript Program for K-th Largest Sum Contiguous Subarray

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

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

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

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

Using Sliding Window with Min-Heap

Idea:

  1. Use a Min-Heap to keep track of the top K largest sums while iterating through subarrays.
  2. Sliding Window Technique is used to calculate the sums of subarrays efficiently.

Steps:

  1. Initialize a Min-Heap to keep track of the K largest sums.
  2. Iterate over all starting points of subarrays.
  3. For each starting point, compute the sum of subarrays ending at each possible end point.
  4. Maintain the top K largest sums in the Min-Heap. If the size of the heap exceeds K, remove the smallest sum (heap root).
  5. After processing all subarrays, the root of the Min-Heap will be the K-th largest sum.

Example:

JavaScript
class MinHeap {
    constructor() {
        this.heap = [];
    }

    push(val) {
        this.heap.push(val);
        this._heapifyUp(this.heap.length - 1);
    }

    pop() {
        if (this.heap.length <= 1) return this.heap.pop();
        const root = this.heap[0];
        this.heap[0] = this.heap.pop();
        this._heapifyDown(0);
        return root;
    }

    peek() {
        return this.heap[0];
    }

    _heapifyUp(index) {
        let parentIndex = Math.floor((index - 1) / 2);
        while (index > 0 && this.heap[index] < this.heap[parentIndex]) {
            [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
            index = parentIndex;
            parentIndex = Math.floor((index - 1) / 2);
        }
    }

    _heapifyDown(index) {
        let leftChild = 2 * index + 1;
        let rightChild = 2 * index + 2;
        let smallest = index;

        if (leftChild < this.heap.length && this.heap[leftChild] < this.heap[smallest]) {
            smallest = leftChild;
        }
        if (rightChild < this.heap.length && this.heap[rightChild] < this.heap[smallest]) {
            smallest = rightChild;
        }
        if (smallest !== index) {
            [this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
            this._heapifyDown(smallest);
        }
    }
}

function kthLargestSum(arr, k) {
    let n = arr.length;
    let prefixSum = new Array(n + 1).fill(0);
    let minHeap = new MinHeap();

    // Compute prefix sums
    for (let i = 1; i <= n; i++) {
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1];
    }

    // Iterate over all starting points
    for (let start = 0; start < n; start++) {
        let currentSum = 0;
        for (let end = start; end < n; end++) {
            currentSum += arr[end];
            if (minHeap.heap.length < k) {
                minHeap.push(currentSum);
            } else if (currentSum > minHeap.peek()) {
                minHeap.pop();
                minHeap.push(currentSum);
            }
        }
    }
    return minHeap.peek();
}

let arr = [10, -10, 20, -40];
let k = 6;
console.log(kthLargestSum(arr, k));

Output
-10

Next Article

Similar Reads