Leetcode-152. Maximum Product Subarray

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

这个题目想的不是很清楚,改了好几次,但是最终还是弄对了,时间复杂度O(n),空间复杂度O(n) Your runtime beats 49.72% of java submissions.

public class Solution {
    public int maxProduct(int[] nums) {
        int max = nums[0];
        int[] positive = new int[nums.length];
        int[] negetive = new int[nums.length];
        positive[0] = 1;
        negetive[0] = 1;
        if(nums[0] > 0) positive[0] = nums[0];
        else if(nums[0] < 0) negetive[0] = nums[0];
        for(int i = 1; i <nums.length ; i ++){
            if(nums[i] > 0){
                positive[i] = positive[i-1] * nums[i];
                if(negetive[i-1] != 1) negetive[i] = negetive[i-1] * nums[i];
                else negetive[i] = 1;
                max = positive[i] > max ? positive[i] : max;
            }else if(nums[i] < 0){
                if(negetive[i-1] != 1) {
                    positive[i] = negetive[i-1] * nums[i];
                    max = positive[i] > max ? positive[i] : max;
                }
                else positive[i] = 1;
                negetive[i] = nums[i] * positive[i-1];
                max = negetive[i] > max ? negetive[i] : max;
            }
            else{
                positive[i] = 1;
                negetive[i] = 1;
                max = max >= 0 ? max : 0;
            }


        }
        return max;
    }
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值