标签:经典dp 组元 turn its 直接 amp c代码 nat als
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.
解答:经典DP问题,需注意数组元素全部小于0时直接输出数组元素的最大值即可。
AC代码:
class Solution { public: int maxSubArray(vector<int>& nums) { bool flag=false; int sum=INT_MIN,tmp=0; for(int i=0;i<nums.size();i++) { if(nums[i]>=0) { flag=true; break; } if(sum<nums[i]) sum=nums[i]; } if(flag) { for(int i=0;i<nums.size();i++) { tmp=tmp+nums[i]; if(tmp>sum) sum=tmp; if(tmp<0) tmp=0; } } return sum; } };
标签:经典dp 组元 turn its 直接 amp c代码 nat als
原文地址:https://www.cnblogs.com/guoshuai1995/p/10397151.html