【题目】
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
【思路】
- Kadane's Algorithm 位置的移动通过判断cur正负,为负置0。
leetcode121 best time buy and sell
https://blog.csdn.net/sinat_34976604/article/details/80970936
update 2021.08.22 DP动态规划
从后往前倒推,握手问题
第一个数的最长序列L1=MAX(L1本身值,后面数最长序列L2+L1本身值)
答案ans=MAX(当前ans,当前数最长序列Ln)
【代码】
Kadane's Algorithm 原代码
class Solution { public int maxSubArray(int[] nums) { int sum=Integer.MIN_VALUE; int cur=0; for(int i=0;i<nums.length;i++){ cur+=nums[i]; sum=Math.max(sum,cur); cur=cur<0?0:cur; } return sum; } }
动态规划 二刷
public int maxSubArray(int[] nums) { if(nums.length==1) return nums[0]; int sum[]=new int[nums.length]; sum[nums.length-1]=nums[nums.length-1]; int ans=sum[nums.length-1];//注意ans最初赋值 for(int i=nums.length-1;i>0;i--){ sum[i-1]=Math.max(nums[i-1]+sum[i],nums[i-1]); ans=Math.max(sum[i-1],ans); } return ans; }