Leetcode-152. Maximum Product Subarray

来源:互联网 发布:linux 清空回收站 编辑:程序博客网 时间:2024/05/02 04:32

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