JavaScript Program for K-th Largest Sum Contiguous Subarray
Last Updated :
26 Aug, 2024
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.
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));
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));
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));
Using Sliding Window with Min-Heap
Idea:
- Use a Min-Heap to keep track of the top K largest sums while iterating through subarrays.
- Sliding Window Technique is used to calculate the sums of subarrays efficiently.
Steps:
- Initialize a Min-Heap to keep track of the K largest sums.
- Iterate over all starting points of subarrays.
- For each starting point, compute the sum of subarrays ending at each possible end point.
- Maintain the top K largest sums in the Min-Heap. If the size of the heap exceeds K, remove the smallest sum (heap root).
- 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));
Similar Reads
JavaScript Program to Find Largest Subarray with a Sum Divisible by k
Finding the largest subarray with a sum divisible by a given integer 'k' is a common problem in JavaScript and other programming languages. This task involves identifying a contiguous subarray within an array of integers such that the sum of its elements is divisible by 'k' and is as long as possibl
5 min read
Max Length of Subarray with Given Sum Limit in JavaScript Array
Given an array, our task is to find the maximum length of a subarray whose sum does not exceed a given value. We can use different approaches like the Brute Force Approach and the Sliding Window Approach to find the maximum length of a subarray. Below are the approaches to find the maximum length of
3 min read
Maximum of all Subarrays of Size k using JavaScript
This problem is about finding the biggest number in all groups of k adjacent numbers in an array. In JavaScript, you'd go through the array, looking at each group of k numbers at a time, and picking out the biggest one. This task is pretty common and is useful for things like analyzing data or optim
5 min read
Javascript Program for Largest Sum Contiguous Subarray
Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. Kadane's Algorithm:Initialize: max_so_far = INT_MIN max_ending_here = 0Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_so_f
5 min read
PHP Program for Largest Sum Contiguous Subarray
Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum.  Recommended: Please solve it on âPRACTICE â first, before moving on to the solution.  Kadane's Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loo
4 min read
Javascript Program for Maximum circular subarray sum
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers. Examples: Input: a[] = {8, -8, 9, -9, 10, -11, 12}Output: 22 (12 + 8 - 8 + 9 - 9 + 10)Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1} Output: 23 (7 + 6 + 5 - 4 -1 + 10) Input: a[] = {-1, 40, -14, 7, 6,
5 min read
Largest Sum Contiguous Subarray in C
In this article, we will learn how to find the maximum sum of a contiguous subarray for a given array that contains both positive and negative integers in C language.Example:Input: arr = {-2, -3, 4, -1, -2, 1, 5, -3}Output: 7Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7.Maximum su
4 min read
Javascript Program to Find the subarray with least average
Given an array arr[] of size n and integer k such that k <= n.Examples : Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2Output: Sub
3 min read
Javascript Program for Size of The Subarray With Maximum Sum
An array is given, find length of the subarray having maximum sum.Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Leng
2 min read
Javascript Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array
Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:Â Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2,
5 min read