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.
public class Test08 { public static void main(String[] args) { int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; int[] sums = new int[nums.length]; int max = nums[0]; sums[0] = nums[0]; for (int i = 1; i < nums.length; i++) { sums[i] = Math.max(nums[i], nums[i] + sums[i - 1]); max = Math.max(max, sums[i]); } System.out.println(max); } }