File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
3+
4+ Example 1:
5+
6+ Input: [2,3,-2,4]
7+ Output: 6
8+ Explanation: [2,3] has the largest product 6.
9+ Example 2:
10+
11+ Input: [-2,0,-1]
12+ Output: 0
13+ Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
14+ */
15+
16+ /**
17+ * @param {number[] } nums
18+ * @return {number }
19+ */
20+ var maxProduct = function ( nums ) {
21+ if ( ! nums . length ) return 0 ;
22+ let maxEnding = nums [ 0 ] ;
23+ let minEnding = nums [ 0 ] ;
24+ let res = nums [ 0 ] ;
25+ for ( let i = 1 ; i < nums . length ; i ++ ) {
26+ if ( nums [ i ] < 0 ) {
27+ let temp = minEnding ;
28+ minEnding = maxEnding ;
29+ maxEnding = temp ;
30+ }
31+
32+ maxEnding = Math . max ( maxEnding * nums [ i ] , nums [ i ] ) ;
33+ minEnding = Math . min ( minEnding * nums [ i ] , nums [ i ] ) ;
34+ res = Math . max ( res , maxEnding ) ;
35+ }
36+ return res ;
37+ } ;
Original file line number Diff line number Diff line change @@ -104,6 +104,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
104104| 15 | [ 3 Sum] ( https://leetcode.com/problems/3sum/ ) | [ Python] ( ./Python/ThreeNumbersSum.py ) | O( nLog(n) ) | O(1) | Medium | Array |
105105| 1200 | [ Minimum Absolute Difference] ( https://leetcode.com/problems/minimum-absolute-difference/ ) | [ Python] ( ./python/SmallestDifference.py ) | O(n) | O(1) | Easy | Array |
106106| 532 | [ K-diff Pairs in an Array] ( https://leetcode.com/problems/k-diff-pairs-in-an-array/ ) | [ C++] ( ./C++/k-diff-pairs-in-an-array.cpp ) | O(n) | O(n) | Medium | Array |
107+ | 152 | [ Maximum Product Subarray] ( https://leetcode.com/problems/maximum-product-subarray/ ) | [ Javascript] ( ./JavaScript/152.Maximum-Product-Subarray.js ) | O(n) | O(n) | Medium | Array |
107108
108109
109110<br />
You can’t perform that action at this time.
0 commit comments