@[TOC](leetcode53 最大子数列之和Maximum subarray sum(JS))
刷题系列
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
// should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
动态规划DP
解题过程:
设sum[i]为以第i个元素结尾的最大的连续子数组的和。假设对于元素i,所有以它前面的元素结尾的子数组的长度都已经求得,那么以第i个元素结尾且和最大的连续子数组实际上,要么是以第i-1个元素结尾且和最大的连续子数组加上这个元素,要么是只包含第i个元素,即sum[i] = max(sum[i-1] + arr[i], arr[i])。可以通过判断sum[i-1] + arr[i]是否大于arr[i]来做选择,而这实际上等价于判断sum[i-1]是否大于0。由于每次运算只需要前一次的结果,因此并不需要像普通的动态规划那样保留之前所有的计算结果,只需要保留上一次的即可,因此算法的时间和空间复杂度都很小
Solution:
var maxSequence = function(arr){
// ...
if(arr == null || arr.length === 0){
return 0;
}
let global = arr[0];
let local = arr[0];
for(let i=1; i<arr.length; i++){
local = Math.max(arr[i],local+arr[i]);
global = Math.max(local,global);
}
if (global < 0){
global =0;
}
return global;
}
题目链接: Maximum subarray sum.