forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path152 Maximum Product Subarray.js
More file actions
39 lines (30 loc) · 996 Bytes
/
152 Maximum Product Subarray.js
File metadata and controls
39 lines (30 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Find the contiguous subarray within an array (containing at least one number) which has the largest product.
// For example, given the array [2,3,-2,4],
// the contiguous subarray [2,3] has the largest product = 6.
// Hide Company Tags LinkedIn
// Hide Tags Array Dynamic Programming
// Show Similar Problems
// Leetcode #152
// Language: Javascript
// Problem: https://leetcode.com/problems/maximum-product-subarray/
/**
* @param {number[]} nums
* @return {number}
*/
// reference: http://www.programcreek.com/2014/03/leetcode-maximum-product-subarray-java/
var maxProduct = function(nums) {
if(nums === null || nums.length === 0){
return 0;
}
var max = nums[0];
var min = max;
var ans = max;
for(var i = 1; i < nums.length; i++){
var tmax = nums[i]*max;
var tmin = nums[i]*min;
max = Math.max(Math.max(tmax, nums[i]), tmin);
min = Math.min(Math.min(tmax, nums[i]), tmin);
ans = Math.max(ans,max);
}
return ans
};