dippersinan-note-数组

数组

连续子数组

最大连续子数组和

  • f(n)为以第n个数结尾的连续子数组的最大和
  • 步骤:
    • 如果f(n-1)<0,那第n个数就没必要连上前面的数组了,f(n)=nums[n]
    • 如果f(n-1)>0,那第n个数继续连上,说不定可以变得更大呢,f(n)=nums[n]+f(n-1)
public int maxSubArray(int[] nums) {
    int max = Integer.MIN_VALUE, pre = 0;
    for (int num : nums) {
        pre = pre < 0 ? num : pre + num;
        max = Math.max(max, pre);
    }
    return max;
}

最大连续子数组乘积

  • f(n)为以第n个数结尾的连续子数组的最大乘积
  • 在判断第n个到底和前面的数组连不连上中,和最大连续子数组和不同,需要记录最大和最小值两个
  • 步骤:
    • 如果f(n-1)的最大值和最小值分别乘以第n个数,没有第n个数大,那么那第n个数就没必要连上前面的数组了
    • 如果f(n-1)的最大值和最小值分别乘以第n个数,比第n个数大,那第n个数继续连上
  • 最大值和最小值都这样计算
public int maxProduct(int[] nums) {
    int ans = nums[0], max = ans, min = ans;
    for (int i = 1; i < nums.length; i++) {
        int mx = Math.max(nums[i], Math.max(max * nums[i], min * nums[i]));
        int mn = Math.min(nums[i], Math.min(max * nums[i], min * nums[i]));
        max = mx;
        min = mn;
        ans = Math.max(ans, max);
    }
    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值