diff --git a/_posts/2024-07-09-leetcode-152.md b/_posts/2024-07-09-leetcode-152.md new file mode 100644 index 0000000..20abc00 --- /dev/null +++ b/_posts/2024-07-09-leetcode-152.md @@ -0,0 +1,85 @@ +--- +layout: post +title: (Leetcode) 152 - Maximum Product Subarray 풀이 +categories: [스터디-알고리즘] +tags: [자바, java, 리트코드, Leetcode, 알고리즘, array, subarray, product] +date: 2024-07-08 16:30:00 +0900 +toc: true +--- + +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. + +[https://neetcode.io/practice](https://neetcode.io/practice) + +--- + +[https://leetcode.com/problems/maximum-product-subarray/](https://leetcode.com/problems/maximum-product-subarray/) + +## 내가 작성한 풀이 + +그냥 모든 케이스를 고려하여 코드를 작성하였다. + +다음과 같은 부분들을 고려했다. + +- 0 을 만나면 구간이 끊킨다. +- 음수를 만나더라도 다음 음수를 만나면 양수가 될 수 있다. +- 음수를 만났을 때 다음 음수가 없다면, 이전 부분은 더 이상 쓸모가 없다. + +```java +class Solution { + public int maxProduct(int[] nums) { + int max = Integer.MIN_VALUE; + int temp = 0; + int lastZeroIndex = 0; + for (int i = 0; i < nums.length; i++) { + int current = nums[i]; + if (temp == 0) { + temp = current; + lastZeroIndex = i; + } else { + if (current == 0) { + temp = 0; + } else if (temp > 0 && current < 0) { + if (hasNextMinus(nums, i + 1)) { + temp = temp * current; + } else { + temp = temp * current; + for (int j = lastZeroIndex; j < i + 1; j++) { + temp = temp / nums[j]; + if (temp > 0) { + break; + } + } + } + } else { + temp = temp * current; + } + } + max = Math.max(max, temp); + if (temp < 0 && !hasNextMinus(nums, i + 1)) { + temp = 0; + } + } + return max; + } + + private boolean hasNextMinus(int[] nums, int i) { + for (; i < nums.length; i++) { + if (nums[i] < 0) { + return true; + } else if (nums[i] == 0) { + return false; + } + } + return false; + } +} +``` + +### TC, SC + +시간 복잡도는 O(n^2)이다. 공간 복잡도는 O(1)이다. hasNextMinus 이 적게 호출된다면 시간 복잡도는 O(n)에 가깝게 동작한다. + +![submit result](/assets/images/2024-07-09-leetcode-152/submit_result.png) + +beat 93.31% diff --git a/assets/images/2024-07-09-leetcode-152/submit_result.png b/assets/images/2024-07-09-leetcode-152/submit_result.png new file mode 100644 index 0000000..e57fffb Binary files /dev/null and b/assets/images/2024-07-09-leetcode-152/submit_result.png differ