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.
solution1 optimization problem -DP
- optimization problem -DP
- the format of the sub problem(or the state of each sub problem).
- recursive
maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
动态规划。用循环做。
F(i)=numsi;
F(i)=nums[i]+F(i-1)(F(i-1)>0)
细节:nums只有{-1}时,所以开始sum=nums[0],然后从第二个开始循环。
class Solution {
public:
int FindGreatestSumOfSubArray(vector