给定一个整数数组,找到一个具有最小/大和的子数组。返回其最小/大和。
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
if(nums == null)
return 0;
int len = nums.size();
int[] imin = new int[len];//以第i个数为结尾的最小连续子数组的和
int[] res = new int[len];//前i个数的最小子数组和,不一定包含第i个数
imin[0] = res[0] = nums.get(0);//初始化
for(int i = 1;i<len;i++){
imin[i] = Math.min(imin[i-1]+nums.get(i),nums.get(i));
res[i] = Math.min(res[i-1],imin[i]);
}
return res[len-1];
}
}
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
// write your code
if(nums == null)
return 0;
int len = nums.length;
int[] imax = new int[len];
int[] res = new int[len];
imax[0] = res[0] = nums[0];//初始化
for(int i = 1;i<len;i++){
imax[i] = Math.max(imax[i-1]+nums[i],nums[i]);
res[i] = Math.max(res[i-1],imax[i]);
}
return res[len-1];
}
}
本文介绍了一种高效算法,用于寻找整数数组中具有最小或最大和的子数组,并返回该和。通过动态规划的方法,实现了对任意长度数组的有效处理。
2060

被折叠的 条评论
为什么被折叠?



