Leetcode Two Maximum Subarray Questions

Leetcode 53. Maximum Subarray

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

分析:

题目要求在数组中找到一个连续的子数组,这个子数组的和最大。
第一个想法是,通过一个result数组来记录直到第i个元素且i必选的最大子数组的和,可以很容易写出状态转移方程如下:

if (result[i - 1] < 0) {
    result.push_back(nums[i]);
} else {
    result.push_back(result[i - 1] + nums[i]);
}

此时,可以看到,空间复杂度是O(n),时间复杂度也是O(n)。
考虑另外一种思路,Kadane’s algorithm,可以只需要O(1)的空间复杂度和O(n)的时间复杂度。
Kadane’s algorithm的思路就是:
对于当前遍历到的元素,这个元素可以加入到当前的连续子数组,作为最后一个元素,或者,舍弃之前的连续子数组,将当前元素作为新的子数组的第一个元素。
可以写出状态转移方程如下:

max_ending_here = max(nums[i], nums[i] + max_ending_here);

代码:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max_so_far = nums[0], max_ending_here = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            max_ending_here = max(nums[i], nums[i] + max_ending_here);
            max_so_far = max(max_so_far, max_ending_here);
        }
        return max_so_far;
    }
};

运行结果:

这里写图片描述

Leetcode 152. Maximum Product Subarray

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

分析:

这道题目是寻找数组中的一个连续子数组,使得这个连续子数组的乘积最大。
乍一看这道题目跟上面求子数组的最大和的题目没什么不同,甚至好像可以直接复用上面的代码。
但是,经过这样的尝试后,发现,并不可以!!!
因为乘法的性质,负负得正,而对于负数,在我们不能知道下一个数时,往往就将负数丢弃了。
经过上面的Kadane’s algorithm的方法的启发,我们可以通过记录直到当前位置的两个数,来获得最大的乘积,首先是需要保存是直到当前(包括当前元素)的最大乘积,以及直到当前(包括当前元素)的最小乘积。因为即使是乘法有负负得正的性质,要想获得最大的乘积,那么负数的数值也需要是最小的。因此可以通过保存最小的乘积来保存。
这样的算法,时间复杂度是O(n),空间复杂度是O(1)。

代码:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int max_so_far = nums[0], max_ending_here = nums[0];
        int min_ending_here = nums[0];
        for (int i = 1; i < nums.size(); i++) {
          int temp1 = max_ending_here, temp2 = min_ending_here;
          max_ending_here = max(nums[i], min_ending_here * nums[i]);
          max_ending_here = max(temp1 * nums[i], max_ending_here);
          min_ending_here = min(temp1 * nums[i], nums[i]);
          min_ending_here = min(temp2 * nums[i], min_ending_here);
          max_so_far = max(max_ending_here, max_so_far);
        }
        return max_so_far;
    }
};

运行结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值