Maximum Product Subarray
LeetCode 152 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
The best product is always a prefix or a suffix of some zero-free segment.
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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.