zoukankan      html  css  js  c++  java
  • [LeetCode] 152. Maximum Product SubarrayeetCode] 152. Maximum Product Subarray(积最大的子数组)

    Description

    Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
    给定一个整数数组 nums,找到积最大的子数组(至少包含一个整数)。

    Examples

    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.
    

    Solution

    这题看上去和最大子数组类似,只是把和最大变成了积最大。但是做法就发生了变化,由于无论怎么乘,结果的绝对值都是递增的(当然,0 的情况需要单独讨论)。所以,只要算一遍前缀和,一遍后缀和,就能得到结果。代码如下:

    class Solution {
        fun maxProduct(nums: IntArray): Int {
            var result = nums[0]
            var left = 0
            var right = 0
    
            for (i in nums.indices) {
                left = (if (left == 0) 1 else left) * nums[i]
                right = (if (right == 0) 1 else right) * nums[nums.lastIndex - i]
    
                result = maxOf(result, left, right)
            }
    
            return result
        }
    }
    
  • 相关阅读:
    哈希表
    c++中的虚函数
    struct并不报错
    c风格的字符串
    动态数组
    常量指针和指针常量
    关于struct和typedef struct
    常量成员函数
    关于free的使用疑惑
    mutable用于修改const成员函数中的成员变量
  • 原文地址:https://www.cnblogs.com/zhongju/p/14124785.html
Copyright © 2011-2022 走看看