zoukankan      html  css  js  c++  java
  • LeetCode -- Maximum Product Subarray

    Question:

    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.

    Analysis:

    在一个数组中找出一个连续的数组(数组至少包含一个数字),可以产生最大的乘积。

    例如:给出数组[2, 3, -2, 4],则连续的子数组为[2, 3],产生的最大乘积为6.

    分析:刚开始解题时会错意了,以为要求的子数组只能是连续的数字而实际情况是只要后面的数字比当前数字大都可以视为连续数组。

     因此可以采用动态规划的思想:最大的乘积可在两种情况下产生。(The key to solve this problem)

    1)一个最大的数 * 一个正数

    2)一个最小的数 * 一个负数

    因此,我们分别用两个参数max,min记录到目前为止的最大正数与最小负数,分别为max和min,然后用product记录真实的最大的乘积。然而还要注意的一种特殊情况是,下面出现的一个数比当前累计的乘积的数还要大,那么product的值应该更新为当前数组元素的值,例如:[2,3,0,9]这种情况,2*3 < 9;反之,负数时亦然。

    Answer:

    public class Solution {
        public int maxProduct(int[] nums) {
           if(nums == null || nums.length == 0)
                return 0;
            int max = nums[0];
            int min = nums[0];
            int product = nums[0];
            for(int i=1; i<nums.length; i++) {
                int a = nums[i] * max;
                int b = nums[i] * min;
                max = Math.max(Math.max(a, b), nums[i]);
                min = Math.min(Math.min(a, b), nums[i]);
                product = Math.max(max, product);
            }
            return product; 
        }
    }
     
  • 相关阅读:
    【转】以太坊分片:Overview and Finality
    Raiden Network — Ethereum 区块链支付通道
    ERC 和 EIP 代表什么呢?
    【转】什么是加密经济学
    Ethereum Probabilistic Micropayments
    【转】以太坊钱包分析与介绍
    【转】用Python从零开始创建区块链
    【转】用 Go 构建一个区块链
    通用权限管理系统组件 (GPM
    通用权限管理系统组件 (GPM
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5203981.html
Copyright © 2011-2022 走看看