1. 程式人生 > >LeetCode:152. Maximum Product Subarray(最大的乘積下標)

LeetCode:152. Maximum Product Subarray(最大的乘積下標)

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4] Output: 6  Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1] Output: 0  Explanation:

 The result cannot be 2, because [-2,-1] is not a subarray.


方法1:

package leetcode;

import org.junit.Test;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: ProductSubarray
 * @Description: zhangyu
 * @date 2018/12/24 11:14
 **/


public class ProductSubarray {
    @Test
    public void fun() {
        int nums[] = {2, 3, -2, 4};
        int product = maxProduct(nums);
        System.out.println(product);
    }

    private int maxProduct(int[] nums) {
        int max = nums[0];
        int min = nums[0];
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int temp = max;
            max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
            min = Math.min(Math.min(temp * nums[i], min * nums[i]), nums[i]);
            if (max > result) {
                result = max;
            }
        }
        return result;
    }
}

時間複雜度:O(n)

空間複雜度:O(1)


原始碼github地址:https://github.com/zhangyu345293721/leetcode