-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add post '(Leetcode) 54 - Maximum Subarray'
- Loading branch information
1 parent
aea6468
commit ebee137
Showing
2 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) 이다. |