53. 最大子数组和
代码
javascript
// 53. 最大子数组和:https://leetcode.cn/problems/maximum-subarray/description/
// 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
// 输出:6
export function maximumSubarray (nums) {
let maxSum = nums[0]
let preSum = nums[0]
for (let i = 1, len = nums.length; i < len; i++) {
const cur = nums[i]
preSum = Math.max(preSum + cur, cur)
maxSum = Math.max(maxSum, preSum)
}
return maxSum
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
typescript
// 53. 最大子数组和:https://leetcode.cn/problems/maximum-subarray/description/
// 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
// 输出:6
export function maximumSubarray (nums: number[]): number {
let maxSum = nums[0]
let preSum = nums[0]
for (let i = 1, len = nums.length; i < len; i++) {
const cur = nums[i]
preSum = Math.max(preSum + cur, cur)
maxSum = Math.max(maxSum, preSum)
}
return maxSum
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
测试代码
ts
import { expect, test } from 'vitest'
import { maximumSubarray } from './typescript.ts'
import { maximumSubarray as maximumSubarrayJs } from './javascript.js'
test(`maximumSubarray`, () => {
expect(maximumSubarray([-2,1,-3,4,-1,2,1,-5,4])).toBe(6)
})
test(`maximumSubarrayJs`, () => {
expect(maximumSubarrayJs([-2,1,-3,4,-1,2,1,-5,4])).toBe(6)
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11