给定一个整数数组,找到一个具有最小和的子数组。返回其最小和。
方法一:
public class Solution {
/*
* @param nums: a list of integers
* @return: A integer indicate the sum of minimum subarray
*/
public int min(int a,int b){
if(a<b)
return a;
else
return b;
}
public int minSubArray(List<Integer> nums) {
// write your code here
int len=nums.size();
List<Integer>a=new ArrayList<>();
List<Integer>b=new ArrayList<>();
for(int i=0;i<nums.size();i++){
if(i==0){
a.add(nums.get(i));
b.add(nums.get(i));
}
else{
int m=min(a.get(i-1)+nums.get(i),nums.get(i));
a.add(m);
int n=min(a.get(i),b.get(i-1));
b.add(n);
}
}
return b.get(len-1);
}
}
方法二:
public class Solution {
/*
* @param nums: a list of integers
* @return: A integer indicate the sum of minimum subarray
*/
public int minSubArray(List<Integer> nums) {
// write your code here
int result=Integer.MAX_VALUE;
int sum=0;
for(int i=0;i<nums.size();i++){
if(sum>0)
sum=nums.get(i);
else
sum+=nums.get(i);
if(result>sum)
result=sum;
}
return result;
}
}