Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 152 · Kadane / Subarray DP

Maximum Product Subarray

LeetCode 152 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

The best product is always a prefix or a suffix of some zero-free segment.

మధ్యస్థంArrayDynamic Programming
LeetCode లో తెరవండి ↗

నేను Maximum Product Subarray (LeetCode 152) ను ఇలా పరిష్కరించాను — Kadane / Subarray DP ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

A negative number flips the sign of a product, and a zero wipes it out. Scanning a running product from the left and another from the right covers both 'drop the stuff before the last negative' and 'drop the stuff after it', and resetting at zero starts a fresh segment.

Approach

  1. 1

    Keep a running prefix product (left to right) and suffix product (right to left) in the same loop.

  2. 2

    If either product has become 0, reset it to 1 — a zero ends the segment.

  3. 3

    Multiply in the next number on each side.

  4. 4

    Track the best of prefix and suffix seen so far.

నేను ఎలా పరిష్కరించాను

Prefix × suffix scanPythonO(n) time · O(1) space
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        max_product = float("-inf")
        prefix=1
        suffix=1
        n = len(nums)
        for i,num in enumerate(nums):
            if prefix==0:
                prefix = 1
            if suffix==0:
                suffix = 1
            prefix = prefix*num
            suffix=suffix*nums[n-i-1]
            max_product = max(max_product,max(prefix,suffix))
        return max_product
స్టెప్-త్రూ లోడ్ అవుతోంది…

Maximum Product Subarray — తరచూ అడిగే ప్రశ్నలు

Maximum Product Subarray వెనుక ఉన్న intuition ఏమిటి?

A negative number flips the sign of a product, and a zero wipes it out. Scanning a running product from the left and another from the right covers both 'drop the stuff before the last negative' and 'drop the stuff after it', and resetting at zero starts a fresh segment.

Maximum Product Subarray (LeetCode 152) ను ఎలా పరిష్కరించాలి?

1. Keep a running prefix product (left to right) and suffix product (right to left) in the same loop. 2. If either product has become 0, reset it to 1 — a zero ends the segment. 3. Multiply in the next number on each side. 4. Track the best of prefix and suffix seen so far.

Maximum Product Subarray యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Prefix × suffix scan.)

Maximum Product Subarray లో సాధారణ పొరపాట్లు ఏమిటి?

Initialise the answer to −∞, not 0 — an all-negative single element like [-2] must return -2. The reset happens before multiplying, so a 0 element itself is still counted once.