标签:leetcode one contain etc content http its element i++
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(dp):
感谢 卡卡 Density(https://leetcode.com/density/)提供的dp策略,简单易懂,在这里我就无耻的复制粘贴了。
思路:对于某个位置的nums[i]而言,如果该位置之前的总和为负数,那么该位置之前的值应该完全舍弃;如果该位置之前的值为正数,则应当加上该位置。(我一直在困惑的如果最优解是中间某段数字的情况其实就是第一种情况,该位置之前的所有元素和必为负数。。。果然我还是too yong too simple了)
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 vector<int> dp{nums[0]}; 5 for(int i = 1;i<nums.size();i++) 6 { 7 if(dp[i-1]<0) 8 { 9 dp.push_back(nums[i]); 10 } 11 else 12 { 13 dp.push_back(dp[i-1]+nums[i]); 14 } 15 } 16 return *max_element(dp.begin(),dp.end()); 17 } 18 };
solution2(divide & conquer):
思路:
最优解的三种可能:
1.完全在中间位置的左侧
2.完全在中间位置的右侧
3.包含中间位置
标签:leetcode one contain etc content http its element i++
原文地址:https://www.cnblogs.com/Swetchine/p/11223362.html