Skip to content

Instantly share code, notes, and snippets.

@ankitwww
Last active March 5, 2021 15:20
Show Gist options
  • Save ankitwww/19e9368f3ac68d43279778ad0b6b6cd3 to your computer and use it in GitHub Desktop.
Save ankitwww/19e9368f3ac68d43279778ad0b6b6cd3 to your computer and use it in GitHub Desktop.

[Don't comment your code here - You will be immediately disqualified]

Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.

Example 1:

Input: [2, 1, 5, 1, 3, 2], k=3 Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3].

Example 2:

Input: [2, 3, 4, 1, 5], k=2 Output: 7 Explanation: Subarray with maximum sum is [3, 4].

@coderatiiita
Copy link

function maxSum(arr, k) {
let sum=0, res=Number.NEGATIVE_INFINITY;
for(let i=0; i<k; i++) {
sum+=arr[i];
}
res=sum;
for(let i=1; i+k<=arr.length; i++) {
sum-=arr[i-1];
sum+=arr[i+k-1];
res = Math.max(res, sum);
}
return res;
}

console.log(maxSum([2, 3, 4, 1, 5], 3));

@shiv76
Copy link

shiv76 commented Feb 15, 2021

function max_sub_array_of_size_k(k, arr) {
let maxSum = 0,
windowSum = 0;
// loop through start till array length - k
for (i = 0; i < arr.length - k + 1; i++) {
windowSum = 0;
// loop through i to i + k elements
for (j = i; j < i + k; j++) {
windowSum += arr[j];
}
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}

console.log(Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])})

@PragyanshuSharma
Copy link

Run solution at Code

@bhalla123
Copy link

bhalla123 commented Mar 4, 2021

function arrSum() {
    var arr = [2, 1, 5, 1, 3, 2];
    const k = 2;
    var number = [];
    var len = arr.length;

    if (k > 0) {

        if (k < len / 2) {

            number = arr.slice(k - 1, k + k - 1);
            var sum = number.reduce(function(a, b) {
                return a + b;
            }, 0);

        } else {

            number = arr.slice(0, k);
            var sum = number.reduce(function(a, b) {
                return a + b;
            }, 0);

        }
        console.log( "Sum: " + sum);
         console.log( "Number: " + [number]);


    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment