• 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.

    使用动态规划,但是要注意,避免正负数出错,应该保存当前最大值和当前最小值 如[-2,3,-4]
     1 public int maxProduct(int[] nums) {//dp mytip
     2         if(null==nums||0==nums.length){
     3             return 0;
     4         }
     5         int max = nums[0];
     6         int min = nums[0];
     7         int re = nums[0];
     8         for(int i=1;i<nums.length;i++){//max=Max(max*nums[i],min*nums[i],nums[i])
     9 //min=Min(max*nums[i],min*nums[i],nums[i])
    10             int p = max*nums[i];
    11             int q = min*nums[i];
    12             if(p>q){
    13                 max = p;
    14                 min = q;
    15             }
    16             else{
    17                 min =p;
    18                 max = q;
    19             }
    20             max = max>nums[i]?max:nums[i];
    21             min = min>nums[i]?nums[i]:min;
    22             re = re>max?re:max;
    23         }
    24         return re;
    25     }
  • 相关阅读:
    树的直径教学思路
    dfs序3树上差分
    DFS序与欧拉序的区别
    DFS序2
    树的重心教学思路
    loadrunner11并发注册码
    JPA 添加 converter
    银行信贷账户管理任务
    《如何启动黄金圈思维》笔记
    《野蛮进化》笔记
  • 原文地址:https://www.cnblogs.com/zhacai/p/10644095.html
Copyright © 2020-2023  润新知