add: 最大子序和

This commit is contained in:
yi-ge 2020-05-03 19:11:29 +08:00
parent 801073e385
commit e9fd76de1b
3 changed files with 23 additions and 0 deletions

View File

@ -229,6 +229,12 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 202. 快乐数 https://leetcode-cn.com/problems/happy-number/ - LeetCode 202. 快乐数 https://leetcode-cn.com/problems/happy-number/
- LintCode 488. 快乐数 https://www.lintcode.com/problem/happy-number/description - LintCode 488. 快乐数 https://www.lintcode.com/problem/happy-number/description
- [最大子序和](src/array/maximum-subarray.js)
- LeetCode 53. 最大子序和 https://leetcode-cn.com/problems/maximum-subarray/
- LintCode 41. 最大子数组 https://www.lintcode.com/problem/maximum-subarray/description
- LintCode 620. 最大子序列的和IV https://www.lintcode.com/problem/maximum-subarray-iv/description
## 栈 ## 栈
- [最大矩阵](src/stack/maximal-rectangle.js) - [最大矩阵](src/stack/maximal-rectangle.js)

View File

@ -0,0 +1,11 @@
/**
* @param {number[]} nums
* @return {number}
*/
export const maxSubArray = function (nums) {
let max = nums[0]
let tmp = 0
nums.forEach(n => { max = Math.max(tmp > 0 ? tmp += n : tmp = n, max) })
// 如果当前指针所指元素之前的和小于0则丢弃当前元素之前的数列
return max
}

View File

@ -0,0 +1,6 @@
import { maxSubArray } from '../../src/array/maximum-subarray'
test('最大子序和', () => {
expect(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toBe(6)
// expect(maxSubArray([-2, 2, -3, 4, -1, 2, 1, -5, 3])).toBe(5)
})