Maximum Product Subarray / Maximum Subarray

Maximum Subarray

Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

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 here
        if (nums == null || nums.length == 0) {
            return Integer.MIN_VALUE;
        }
        
        int curSum = nums[0];
        int maxSum = nums[0];
        
        for (int i = 1; i < nums.length; i++) {
            curSum = curSum > 0 ? curSum + nums[i] : nums[i];
            maxSum = curSum > maxSum ? curSum : maxSum;
        }
        
        return maxSum;
    }
}

Maximum Product Subarray

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

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

public int maxProduct(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int minPre = nums[0], maxPre = nums[0];
        int max = nums[0], min = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i ++) {
            max = Math.max(nums[i], Math.max(maxPre * nums[i], minPre * nums[i]));
            min = Math.min(nums[i], Math.min(maxPre * nums[i], minPre * nums[i]));
            res = Math.max(res, max);
            maxPre = max;
            minPre = min;
        }
        return res;
    }
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,166评论 0赞 33
  • 亲人 我们来到这个世界上本就是身无遮物,赤裸裸的,好像我们生来就具有孤单的权力,还有个体的特性,是的,一切都好像应...
    简野文馆阅读 1,176评论 18赞 39
  • 实现类需要明确声明自己实现了某个接口 接口定义不知道实现者的具体需求 提供哪些接口好呢 如果两个雷实现了相同的接口...
    ww4u阅读 365评论 0赞 0
  • 2014-03-19 宁静致远和静水深流 ——小城散漫表达系列之“远、流” 火山 我们的存在想得到别人的认同,往往...
    朱明云阅读 586评论 0赞 3
  • 1 以前很天真,总认为世界上的事没什么是跨不过去的,只要你足够努力。 现在一样天真,虽然明白并不是所有的事情都能如...
    沐沐小狐狸阅读 470评论 0赞 2

友情链接更多精彩内容