-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.maxsub.sum.js
More file actions
64 lines (56 loc) · 1.49 KB
/
array.maxsub.sum.js
File metadata and controls
64 lines (56 loc) · 1.49 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
/*
* @title: Max Sum Array
* @description: Find max sum of subarray
* @author: Thorsten Kober
* @email: [email protected]
*/
function maxSubArraySum(arr) {
if (arr.length === 0) return 0;
if (arr.length === 1) return arr[0];
let max = -Infinity;
let current = 0;
for (let i = 0; i < arr.length; i++) {
current += arr[i];
if (current > max) max = current;
if (current < 0) current = 0;
}
return max;
}
function maxSubArraySum1(arr) {
if (arr.length === 0) return 0;
if (arr.length === 1) return arr[0];
let maxSum = -Infinity;
let maxLength = 0;
let result = [];
let start = 0;
let end = 0;
let current = 0;
for (let i = 0; i < arr.length; i++) {
current += arr[i];
if (maxSum < current) {
maxSum = current;
end = i;
}
if (current < 0) {
current = 0;
start = i + 1;
}
}
maxLength = (end - start + 1);
result = arr.slice(start, end + 1);
console.log(`max sum: ${maxSum}, max length: ${maxLength}, sub array: ${result}`);
return maxSum;
}
// npx jest algorithms/array/array.maxsub.sum.js
test('maxSubArraySum()', () => {
expect(maxSubArraySum([-2, -3, 4, -1, -2, 1, 5, -3])).toEqual(7);
});
test('maxSubArraySum()', () => {
expect(maxSubArraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toEqual(6);
});
test('maxSubArraySum1()', () => {
expect(maxSubArraySum1([-2, -3, 4, -1, -2, 1, 5, -3])).toEqual(7);
});
test('maxSubArraySum1()', () => {
expect(maxSubArraySum1([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toEqual(6);
});