给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3]
,符合要求的子数组为[4,−1,2,1]
,其最大和为6
//先使用动态规划维护一个符合连续数组条件的每个位置的值的数组。然后遍历该数组,找出其中最大的值。
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(ArrayList<Integer> nums) {
// write your code
int[] f=new int[nums.size()+1];
f[0]=0;
for(int i=1;i<=nums.size();i++){
if(f[i-1]<=0){
f[i]=nums.get(i-1);
}else{
f[i]=f[i-1]+nums.get(i-1);
}
}
int max=Integer.MIN_VALUE;
for(int i=1;i<=nums.size();i++){
if(f[i]>max){
max=f[i];
}
}
return max;
}
}