Skip to content

Commit

Permalink
5. Maximum Product Subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Sep 6, 2024
1 parent d0efeef commit 2286ca9
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions maximum-product-subarray/whewchews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* ์กฐ๊ฑด
* ๊ฐ€์žฅ ํฐ ๋ฐฐ์—ด ๊ณฑ์„ ์ฐพ์•„์„œ return
* 32-bit integer
* -10<=num[i]<=10
* ์•„์ด๋””์–ด
* ์ด์ „ ์ตœ๋Œ€๊ฐ’, ์ตœ์†Œ๊ฐ’์„ ๊ตฌํ•ด๋‘”๋‹ค
* ์ตœ๋Œ€๊ณฑ์ด ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ
* 1) ์ตœ์†Œ๊ฐ’ ๊ณฑํ•œ๊ฒƒ(-*-)
* 2) ์ตœ๋Œ€๊ฐ’ ๊ณฑํ•œ๊ฒƒ(+*+)
* 3) ์ž๊ธฐ์ž์‹ ์ธ ๊ฒฝ์šฐ(+)
* ๋ฐฐ์—ด์„ ๋Œ๋ฉด์„œ ์„ธ ๊ฐ€์ง€ ์ค‘ ์ตœ๋Œ€์ตœ์†Œ๊ฐ’์„ ๊ฐฑ์‹ ํ•ด๋‚˜๊ฐ„๋‹ค
*
*/
function maxProduct(nums: number[]): number {
let max = nums[0];
let min = nums[0];
let result = nums[0];

for (let i = 1; i < nums.length; i++) {
const candidates = [nums[i] * max, nums[i], nums[i] * min];
let currMax = Math.max(...candidates);
let currMin = Math.min(...candidates);

max = currMax;
min = currMin;

result = Math.max(currMax, result);
}
return result;
}

// TC: O(n)
// SC: O(1)

0 comments on commit 2286ca9

Please sign in to comment.