1. 线性DP 53. 最大子序和.
53. 最大子序和. https://leetcode-cn.com/problems/maximum-subarray/
func maxSubArray(nums []int) int { dp := make([]int,len(nums)) dp[0] = nums[0] for i:=1;i<len(nums);i++{ dp[i] = MAX(dp[i-1],0)+nums[i] } res := nums[0] for i:=1;i<len(nums);i++{ res = MAX(res,dp[i]) } return res } func MAX(i,j int) int{ if i>j{ return i }else{ return j } }
下面优化:使用常量空间复杂度O(1)
func maxSubArray(nums []int) int { pre,res := nums[0],nums[0] for i:=1;i<len(nums);i++{ cur := MAX(pre,0)+nums[i] pre = cur if cur > res{ res = cur } } return res } func MAX(i,j int) int{ if i>j{ return i }else{ return j } }