Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a3eec7a

Browse files
add: Maximum Product Subarray
1 parent 9430ae6 commit a3eec7a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
3535
|120|[Triangle](https://leetcode.com/problems/triangle/) | [JavaScript](./src/triangle/res.js)|Medium|
3636
|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [JavaScript](./src/surrounded-regions/res.js)|Medium|
3737
|136|[Single Number](https://leetcode.com/problems/single-number/) | [JavaScript](./src/single-number/res.js)|Easy|
38+
|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [JavaScript](./src/maximum-product-subarray/res.js)|Medium|
3839
|175|[Combine Two Tables](https://leetcode.com/problems/combine-two-tables/)| [SQL](./src/combine-two-tables/res.txt)|Easy|
3940
|176|[Second Highest Salary](https://leetcode.com/problems/second-highest-salary/)| [SQL](./src/second-highest-salary/res.txt)|Easy|
4041
|177|[Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/)| [SQL](./src/nth-highest-salary/res.txt)|Medium|

‎src/maximum-product-subarray/res.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017年04月13日 10:10:59
5+
*
6+
* Find the contiguous subarray within an array (containing at least one number) which has the largest product.
7+
* For example, given the array [2,3,-2,4],
8+
* the contiguous subarray [2,3] has the largest product = 6.
9+
*
10+
* Solution idea: https://discuss.leetcode.com/topic/3607/sharing-my-solution-o-1-space-o-n-running-time
11+
*
12+
* @param {number[]} nums
13+
* @return {number}
14+
*/
15+
let maxProduct = function(nums) {
16+
let len = nums.length;
17+
if (!len) {
18+
return 0;
19+
}
20+
21+
let maxPre = nums[0],
22+
maxNow = nums[0],
23+
minPre = nums[0];
24+
for (let i = 1; i < len; i++) {
25+
let maxVal = Math.max(maxPre * nums[i], minPre * nums[i], nums[i]),
26+
minVal = Math.min(minPre * nums[i], maxPre * nums[i], nums[i]);
27+
28+
maxNow = Math.max(maxVal, maxNow);
29+
maxPre = maxVal;
30+
minPre = minVal;
31+
}
32+
33+
return maxNow;
34+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /