|
| 1 | +from typing import List |
| 2 | +from unittest import TestCase, main |
| 3 | + |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def maxProduct(self, nums: List[int]) -> int: |
| 7 | + return self.solveWithDP(nums) |
| 8 | + |
| 9 | + """ |
| 10 | + Runtime: 71 ms (Beats 61.13%) |
| 11 | + Time Complexity: O(n) |
| 12 | + - dp 배열 초기화를 위한 nums.copy()에 O(n) |
| 13 | + - range(1, L) 조회하며 조건에 따라 연산에 O(n - 1) |
| 14 | + - range(L) 조회하며 max 계산에 O(n) |
| 15 | + > O(n) + O(n - 1) + O(n) ~= O(n) |
| 16 | +
|
| 17 | + Memory: 17.75 MB (Beats 11.09%) |
| 18 | + Space Complexity: O(n) |
| 19 | + - 크기가 n인 배열 2개 사용했으므로 2 * O(n) |
| 20 | + > O(2n) ~= O(n) |
| 21 | + """ |
| 22 | + def solveWithDP(self, nums: List[int]) -> int: |
| 23 | + L = len(nums) |
| 24 | + forward_product, backward_product = nums.copy(), nums.copy() |
| 25 | + for i in range(1, L): |
| 26 | + if forward_product[i - 1] != 0: |
| 27 | + forward_product[i] *= forward_product[i - 1] |
| 28 | + |
| 29 | + if backward_product[L - i] != 0: |
| 30 | + backward_product[L - i - 1] *= backward_product[L - i] |
| 31 | + |
| 32 | + result = nums[0] |
| 33 | + for i in range(L): |
| 34 | + result = max(result, forward_product[i], backward_product[i]) |
| 35 | + |
| 36 | + return result |
| 37 | + |
| 38 | + |
| 39 | +class _LeetCodeTestCases(TestCase): |
| 40 | + def test_1(self): |
| 41 | + nums = [2,3,-2,4] |
| 42 | + output = 6 |
| 43 | + self.assertEqual(Solution.maxProduct(Solution(), nums), output) |
| 44 | + |
| 45 | + def test_2(self): |
| 46 | + nums = [-2,0,-1] |
| 47 | + output = 0 |
| 48 | + self.assertEqual(Solution.maxProduct(Solution(), nums), output) |
| 49 | + |
| 50 | + def test_3(self): |
| 51 | + nums = [-2] |
| 52 | + output = -2 |
| 53 | + self.assertEqual(Solution.maxProduct(Solution(), nums), output) |
| 54 | + |
| 55 | + def test_4(self): |
| 56 | + nums = [0,-3,-2,-3,-2,2,-3,0,1,-1] |
| 57 | + output = 72 |
| 58 | + self.assertEqual(Solution.maxProduct(Solution(), nums), output) |
| 59 | + |
| 60 | + def test_5(self): |
| 61 | + nums = [7, -2, -4] |
| 62 | + output = 56 |
| 63 | + self.assertEqual(Solution.maxProduct(Solution(), nums), output) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + main() |
0 commit comments