Quesiton
from lintcode
Given an array of integers, find a contiguous subarray which has the largest sum.
Notice
The subarray should contain at least one number.
Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Idea
Math trick. Sum from x to y = (sum from 0 - y) - (sum from 0 to x - 1)
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
if (nums.length == 0) return 0;
int max = Integer.MIN_VALUE;
int sum = 0;
int minSum = 0;
for (int i = 0; i < nums.length; i++) {
// sum of 0-index to i-index elements
sum += nums[i];
// FORMULA
// e.g.
// sum(3 to 6) = sum(0 to 6) - sum(0 to 2)
// to maximize subarray, gonna minimize the subtraction
int subArraySum = sum - minSum;
// update the subarray sum which has the smallest sum
// from 0th to x-th
minSum = Math.min(minSum, sum);
max = Math.max(max, subArraySum);
}
return max;
}
}