classSolution{ publicintmaxSubArray(int[] nums){ if(nums.length == 0||nums == null){ return0; } //初始化 int[] ans = newint[nums.length]; ans[0] = nums[0]; int res = ans[0]; //依次求出以第n个数为结束点的子序列最大和 for(int i = 1;i<nums.length;i++){ ans[i] = Math.max(ans[i-1]+nums[i],nums[i]); //求出最大和 res = Math.max(res,ans[i]); } return res;
}
}
方法2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicintmaxSubArray(int[] nums){ if(nums.length == 0||nums == null){ return0; } int ans = Integer.MIN_VALUE; int cur = 0; for(int i = 0;i<nums.length;i++){ cur = cur + nums[i]; ans = Math.max(cur,ans); cur = cur < 0 ? 0 : cur; } return ans; } }