-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaxSubArray.js
More file actions
52 lines (46 loc) · 1.19 KB
/
maxSubArray.js
File metadata and controls
52 lines (46 loc) · 1.19 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
/**
* Given an integer array nums, find the contiguous subarray
* (containing at least one number) which has the largest sum
* and return it's sum.
*/
// https://www.youtube.com/watch?v=DF5azwm_LJc
function maxSubArray(nums) {
let solution = nums[0];
for (let i = 1; i < nums.length; i++) {
nums[i] = Math.max(nums[i], nums[i] + nums[i - 1]);
solution = Math.max(solution, nums[i]);
}
return solution;
}
// ===============================================================
// Sliding window pattern #33
// ===============================================================
function maxSubarraySum(arr, num) {
if (num > arr.length) {
return null;
}
var max = -Infinity;
for (let i = 0; i < arr.length - num + 1; i++) {
temp = 0;
for (let j = 0; j < num; j++) {
if (temp > max) {
max = temp;
}
}
}
return max;
}
function maxSubarraySum(arr, num) {
let maxSum = 0;
let tempSum = 0;
if (arr.length < num) return null;
for (let i = 0; i < num; i++) {
maxSum += arr[i];
}
tempSum = maxSum;
for (let i = num; i < arr.length; i++) {
tempSum = tempSum - arr[i - num] + arr[i];
maxSum = Math.max(maxSum, tempSum);
}
return maxSum;
}