您的位置:首页 > 其它

Lintcode: Minimum Subarray 解题报告

2014-12-19 18:26 288 查看

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

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;
}
}


View Code
GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: