Maximum Product Subarray
Find contiguous subarray with largest product. Handle negative numbers.
Visualization
Interactive visualization for Maximum Product Subarray
Maximum Product Subarray
Array:
• Time: O(n)
• Tracks both max and min products
• Handles negative numbers
Interactive visualization with step-by-step execution
Implementation
1function maxProduct(nums: number[]): number {
2 let maxProd = nums[0];
3 let minProd = nums[0];
4 let result = nums[0];
5
6 for (let i = 1; i < nums.length; i++) {
7 const temp = maxProd;
8 maxProd = Math.max(nums[i], nums[i] * maxProd, nums[i] * minProd);
9 minProd = Math.min(nums[i], nums[i] * temp, nums[i] * minProd);
10 result = Math.max(result, maxProd);
11 }
12 return result;
13}Deep Dive
Theoretical Foundation
Track both max and min (negatives can flip). maxProd = max(num, num×maxPrev, num×minPrev). Similar for minProd. Handle 0s.
Complexity
Time
O(n)
O(n)
O(n)
Space
O(1)
Applications
Use Cases
Related Algorithms
0/1 Knapsack Problem
A classic optimization problem where you must select items with given weights and values to maximize total value without exceeding the knapsack's capacity. Each item can be taken only once (0 or 1). This is a fundamental problem in combinatorial optimization, resource allocation, and decision-making scenarios.
Longest Common Subsequence (LCS)
Finds the longest subsequence common to two sequences. A subsequence is a sequence that appears in the same relative order but not necessarily contiguously. This is fundamental in diff utilities, DNA sequence analysis, and version control systems like Git.
Edit Distance (Levenshtein Distance)
Edit Distance, also known as Levenshtein Distance, computes the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform one string into another. Named after Soviet mathematician Vladimir Levenshtein who introduced it in 1965, this fundamental algorithm has applications in spell checking, DNA sequence analysis, natural language processing, and plagiarism detection.
Longest Increasing Subsequence (LIS)
Longest Increasing Subsequence (LIS) finds the length of the longest subsequence in an array where all elements are in strictly increasing order. Unlike a subarray, a subsequence doesn't need to be contiguous - elements can be selected from anywhere as long as their order is preserved. This classic DP problem has two solutions: O(n²) dynamic programming and O(n log n) binary search with patience sorting. Applications include stock price analysis, scheduling, Box Stacking Problem, and Building Bridges Problem.