Skip to content

Commit

Permalink
add: 找出给定数组的最大乘积的子数组
Browse files Browse the repository at this point in the history
  • Loading branch information
xldeng committed Nov 7, 2022
1 parent 0a87a0f commit 593598d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
22. [判断是否是数独](https://github.com/dengshasha/algorithm-study/blob/master/array/validSudoku.js) || [leetcode地址](https://leetcode.com/problems/valid-sudoku/submissions/)
23. [找出两个数组的公共元素](https://github.com/dengshasha/algorithm-study/blob/master/array/IntersectionOfTwoArr.js) || [leetcode地址](https://leetcode.com/problems/intersection-of-two-arrays-ii/)
24. [Game of life](https://github.com/dengshasha/algorithm-study/blob/master/array/gameOfLife.js) || [leetcode地址](https://leetcode.com/problems/game-of-life)
25. [找出给定数组的最大乘积的子数组](https://github.com/dengshasha/algorithm-study/blob/master/array/maxProductSubarr.js) || [leetcode地址](https://leetcode.com/problems/maximum-product-subarray/)


### 动态规划
Expand Down
39 changes: 39 additions & 0 deletions array/maxProductSubarr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Created by dengxuelian on 2022/11/7
*/

/**
* @param {number[]} nums
* @return {number}
*/
// 解法1:暴力解法(会超时)
var maxProduct = function(nums) {
let product = nums[0];
for(let i = 1; i < nums.length; i++) {
let cur = nums[i]
product = Math.max(product, cur)
for(let j = i-1; j >= 0; j--) {
cur *= nums[j]
product = Math.max(product, cur)
}
}
return product;
};

var maxProduct_1 = function(nums) {
let min = nums[0], max = nums[0], product = nums[0]
for(let i = 1; i < nums.length; i++) {
if(nums[i] < 0) {
let temp = min
min = max;
max = temp;
}
min = Math.min(nums[i] * min, nums[i])
max = Math.max(nums[i] * max, nums[i])
product = Math.max(product, max)
}
return product
}
console.log('6:', maxProduct_1([2,3,-2,4]))
console.log('2:', maxProduct_1([0,2,0]))
console.log('24:', maxProduct_1([2,-5,-2,-4,3]))
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
<title>Document</title>
</head>
<body>
<script src="array/gameOfLife.js"></script>
<script src="array/maxProductSubarr.js"></script>
</body>
</html>

0 comments on commit 593598d

Please sign in to comment.