forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyolophg.js
More file actions
24 lines (19 loc) ยท 663 Bytes
/
yolophg.js
File metadata and controls
24 lines (19 loc) ยท 663 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
// Time Complexity: O(n)
// Space Complexity: O(1)
var maxProduct = function (nums) {
// the current maximum product, and the current minimum product
let maxProduct = nums[0];
let currMax = nums[0];
let currMin = nums[0];
// iterate through the array starting from the second element
for (let i = 1; i < nums.length; i++) {
let num = nums[i];
// update the current maximum and minimum products
currMax = Math.max(num, num * currMax);
currMin = Math.min(num, num * currMin);
// update the overall maximum product
maxProduct = Math.max(maxProduct, currMax);
}
// return the maximum product found
return maxProduct;
};