Skip to content

Commit

Permalink
add post '(Leetcode) 54 - Maximum Subarray'
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-jonghoonpark committed May 8, 2024
1 parent aea6468 commit ebee137
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion _posts/2024-05-07-leetcode-15.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class Solution {

![first-approach](/assets/images/2024-05-07-leetcode-15/first-approach.png)

## 개선해보기
### 개선해보기

case3 의 속도가 문제다. case3 에 대해서 아래와 같이 개선해보았다.

Expand Down
44 changes: 44 additions & 0 deletions _posts/2024-05-07-leetcode-54.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
layout: post
title: (Leetcode) 54 - Maximum Subarray
categories: [스터디-알고리즘]
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, array, 배열]
date: 2024-05-07 23:59:59 +0900
toc: true
---

[New Year Gift - Curated List of Top 75 LeetCode Questions to Save Your Time](https://www.teamblind.com/post/New-Year-Gift---Curated-List-of-Top-75-LeetCode-Questions-to-Save-Your-Time-OaM1orEU)

위 링크에 있는 추천 문제들을 시간이 있을때마다 풀어보려고 한다.

---

[https://leetcode.com/problems/maximum-subarray/description](https://leetcode.com/problems/maximum-subarray/description)

크게 어렵지 않은 문제인데 너무 복잡하게 생각해서 여러번 시도를 해야했던 문제이다.

## 모범답안

```java
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;

for (int i = 0; i < nums.length; i++) {
currentSum += nums[i];
maxSum = Math.max(maxSum, currentSum);
currentSum = Math.max(currentSum, 0);
}

return maxSum;
}
}
```

- currentSum이 maxSum보다 클 경우 maxSum을 갱신한다.
- currentSum은 음수일 경우 (0보다 작을 경우) 0으로 초기화 한다.

### TC, SC

시간 복잡도는 O(n), 공간 복잡도는 O(1) 이다.

0 comments on commit ebee137

Please sign in to comment.