Minimum Subarray
原题链接: http://lintcode.com/zh-cn/problem/minimum-subarray/#
Given an array of integers, find the subarray with smallest sum.
Return the sum of the subarray.
注意
The subarray should contain at least one integer.
样例
For [1, -1, -2, 1], return -3
标签 Expand
SOLUTION 1:
1. 我们把整个array * -1,把它转化为求最大和的题目。
2. 然后我们可以使用Sliding window的方法来做。记录一个sum,如果发现sum<0 则丢弃,否则不断把当前的值累加到sum,
3. 每计算一次sum,求一次max.
4. 返回-max即可。
public class Solution {
/**
* @param nums: a list of integers
* @return: A integer indicate the sum of minimum subarray
*/
public int minSubArray(ArrayList<Integer> nums) {
// write your code int len = nums.size(); int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < len; i++) {
if (sum < 0) {
sum = -nums.get(i);
} else {
sum += -nums.get(i);
} max = Math.max(max, sum);
} return -max;
}
}
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java