Skip to content

Commit ebee137

Browse files
add post '(Leetcode) 54 - Maximum Subarray'
1 parent aea6468 commit ebee137

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

_posts/2024-05-07-leetcode-15.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ class Solution {
9898

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

101-
## 개선해보기
101+
### 개선해보기
102102

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

_posts/2024-05-07-leetcode-54.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 54 - Maximum Subarray
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, array, 배열]
6+
date: 2024-05-07 23:59:59 +0900
7+
toc: true
8+
---
9+
10+
[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)
11+
12+
위 링크에 있는 추천 문제들을 시간이 있을때마다 풀어보려고 한다.
13+
14+
---
15+
16+
[https://leetcode.com/problems/maximum-subarray/description](https://leetcode.com/problems/maximum-subarray/description)
17+
18+
크게 어렵지 않은 문제인데 너무 복잡하게 생각해서 여러번 시도를 해야했던 문제이다.
19+
20+
## 모범답안
21+
22+
```java
23+
class Solution {
24+
public int maxSubArray(int[] nums) {
25+
int maxSum = Integer.MIN_VALUE;
26+
int currentSum = 0;
27+
28+
for (int i = 0; i < nums.length; i++) {
29+
currentSum += nums[i];
30+
maxSum = Math.max(maxSum, currentSum);
31+
currentSum = Math.max(currentSum, 0);
32+
}
33+
34+
return maxSum;
35+
}
36+
}
37+
```
38+
39+
- currentSum이 maxSum보다 클 경우 maxSum을 갱신한다.
40+
- currentSum은 음수일 경우 (0보다 작을 경우) 0으로 초기화 한다.
41+
42+
### TC, SC
43+
44+
시간 복잡도는 O(n), 공간 복잡도는 O(1) 이다.

0 commit comments

Comments
 (0)