题目:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
题目链接题意:
给一个数组,找到它的连续最大子串和是多少,并返回最大和。
我们采用dp的办法,对于非首的节点,都有两种选择,延续之前的或者另开一个子串,判断条件就是,假如之前的子串和大于零,那么对于这个点而言,不论正负,延续前子串是最大的办法,而假如前子串和是小于0的,那么另开一个子串是最大办法,相当于假如要在负数和0之间选择,那会选择0而不会选择负数。
代码如下:
class Solution { public: int dp[20000]; int maxSubArray(vector<int>& nums) { int ans = nums[0]; dp[0] = nums[0]; for (int i = 1; i < nums.size(); i++) { if (dp[i-1] < 0) dp[i] = nums[i]; else dp[i] = dp[i-1] + nums[i]; ans = max(ans, dp[i]); } return ans; } };