Passes Problem

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

  • Need 2 variables to record positive and negative numbers

  • Swap if num < -1

  • Math.max & Math.min are used to handle corner case if num==0

def maxProduct(self, nums: List[int]) -> int:
    ans = pProduct = nProduct = nums[0]
    
    for n in nums[1:]:
        if n < 0:
            pProduct, nProduct = nProduct, pProduct
        
        # nProduct is max either current num * previous product or number itself
        pProduct = max(n, pProduct*n)
        nProduct = min(n, nProduct*n)
        
        ans = max(ans, pProduct)       
    return ans

238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

698. Partition to K Equal Sum Subset

Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.

Explain

  1. 可以處理負數

  2. corner case: sum=0, 用 count > 0 紀錄加總個數

472. Concatenated Words

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

Last updated

Was this helpful?