-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33-MaxSubArraySum.js
More file actions
75 lines (66 loc) · 2.05 KB
/
33-MaxSubArraySum.js
File metadata and controls
75 lines (66 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Write a function which accepts an array of integers and a number called 'n'. The function should calculate the maximum sum of 'n' consecutive elements in the array.
*/
/**
*
* @param {Array<number>} array
* @param {number} n
* @returns {number}
*/
function maxSubarraySumNaive(array, n) {
if (array.length < n) return null;
let max = -Infinity;
let temp;
for (let i = 0; i < array.length - n + 1; i++) {
temp = 0;
for (let j = 0; j < n; j++) {
temp += array[i + j];
}
if (temp > max) {
max = temp;
}
}
return max;
}
/**
* Sliding window solution
* - Instead of starting the loop again, just minus the previous number and add the next number
* - Slide the box/window over to the right
* @param {number[]} array
* @param {number} n
* @returns {number | null}
*/
function maxSubarraySum(array, n) {
// If array has no values, return null
if (array.length < n) return null;
// Create two variables to hold indexes, where the no. of elements in the window" [a, _, _, b] is n
// If n=4, a=0, b=3, iterating through elements at index '0' and '3'
// "the window":
let a = 0;
let b = n - 1;
// Create two variables which will hold the sum of numbers and compare
let max = 0;
let temp = 0;
// While 'b' the upper index figure does not exceed array.length
while (b < array.length) {
// We reset temp to '0' each time
temp = 0;
// Iterate through the window of indexes and sum up the elements at each index
// if a = 0, b = 3
// we sum up the elements at index 0,1,2,3, and assing to temp
for (let i = a; i <= b; i++) {
temp += array[i];
}
// Se check if temp is larger than max, if so we update max to the value at temp
// this ensures that we always have the max value possible when adding up all the elements in the "window"
if (temp > max) {
max = temp;
}
// We repeat the process by increasing the index of 'a' and 'b' by 1, thereby shifting the window to the right, until 'b' reaches the array.length
a++;
b++;
}
// Return the max number
return max;
}
module.exports = { maxSubarraySumNaive, maxSubarraySum };