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
.
分析:这道题和152题有点类似。是求连续的子数组的和的最大值。是一道动态规划的题目。
代码如下:
public class Solution { public int MaxSubArray(int[] nums) { int max=int.MinValue,sum=int.MinValue; for(int i=0;i<nums.Length;i++) { if(sum>0) sum+=nums[i]; else sum=nums[i]; max=sum>max?sum:max; } return max; } }