最小/大子数组

本文介绍了一种高效算法,用于寻找整数数组中具有最小或最大和的子数组,并返回该和。通过动态规划的方法,实现了对任意长度数组的有效处理。

给定一个整数数组,找到一个具有最小/大和的子数组。返回其最小/大和。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值