-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSubarraySum.js
More file actions
36 lines (32 loc) · 820 Bytes
/
maxSubarraySum.js
File metadata and controls
36 lines (32 loc) · 820 Bytes
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
const maxSubarraySum = (arr, num) => {
if(arr.length < num) {
return null;
}
let max = -Infinity
for (let i = 0; i < arr.length - num + 1; i++) {
let tempSum = 0
for (let j = 0; j < num; j++) {
tempSum += arr[i + j]
}
max = Math.max(tempSum, max)
}
return max;
}
console.log(maxSubarraySum([1, 2, 5, 2, 8, 1, 5], 2))
const maxSubarraySumOptimised = (arr, num) => {
if(arr.length < num) {
return null;
}
let max = 0
let tempSum = 0
for (let i = 0; i < num; i++) {
max += arr[i]
}
tempSum = max
for(let j = num; j < arr.length - num + 1; j++) {
tempSum = tempSum - arr[j - num ] + arr[j]
max= Math.max(tempSum, max)
}
return max;
}
console.log(maxSubarraySumOptimised([1, 2, 5, 2, 8, 1, 5], 2))