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
.
click to show more PRactice.
Subscribe to see which companies asked this question.
public class Solution { public static int maxSubArray(int[] nums) { int sum = 0; int max_sum = Integer.MIN_VALUE; for (int i = 0; i < nums.length; ++i) { sum += nums[i]; sum = sum > nums[i] ? sum : nums[i]; max_sum = max_sum > sum ? max_sum : sum; } return max_sum; }}
新闻热点
疑难解答