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
.
解题思路:
看题目,一次遍历肯定能搞定问题,只需使用一个sum计算遍历下来可能的最大的和,一个maxSum记录数目的最大值,maxSum即为所求,JAVA实现如下:
static public int maxSubArray(int[] nums) { int sum=nums[0],maxSum=sum; for(int i=1;i<nums.length;i++){ if(sum<=0) sum=nums[i]; else sum+=nums[i]; maxSum=Math.max(maxSum, sum); } return maxSum; }
时间: 2024-12-17 23:54:37