-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
55 lines (45 loc) · 1.2 KB
/
res.ts
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
function maxSubArray(nums: number[]): number {
if (nums.length === 0) {
return 0;
}
if (nums.length === 1) {
return nums[0];
}
const maxI = [nums[0]];
nums.forEach((num, i) => {
if (!i) {
return ;
}
maxI[i] = Math.max(maxI[i-1]+num, num);
})
return Math.max(...maxI);
};
function Status(lSum: number, rSum: number, mSum: number, iSum: number) {
return {
lSum,
rSum,
mSum,
iSum,
};
}
function getSum(nums: number[], start: number, end: number) {
if (start === end) {
return Status(nums[start], nums[start], nums[start], nums[start]);
}
const mIndex = Math.floor((start + end) / 2);
const leftSum = getSum(nums, start, mIndex);
const rightSum = getSum(nums, mIndex+1, end);
return Status(
Math.max(leftSum.lSum, leftSum.iSum + rightSum.lSum),
Math.max(rightSum.rSum, rightSum.iSum + leftSum.rSum),
Math.max(leftSum.mSum, rightSum.mSum, leftSum.rSum + rightSum.lSum),
leftSum.iSum+rightSum.iSum
)
}
/**
* 线段树
* @param nums
*/
function maxSubArray2(nums: number[]): number {
return getSum(nums, 0, nums.length-1).mSum;
};