Skip to content

Commit 69c9e82

Browse files
Merge remote-tracking branch 'upstream/main' into feature/week-6
2 parents 98a55c0 + f35bdd7 commit 69c9e82

File tree

124 files changed

+4403
-123
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

124 files changed

+4403
-123
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* [Problem]: [121] Best Time to Buy and Sell Stock
3+
*
4+
* (https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
5+
*/
6+
function maxProfit(prices: number[]): number {
7+
//시간복잡도: O(n^2);
8+
//공간복잡도: O(1);
9+
// Time Limit Exceeded
10+
function doublyLoopFunc(prices: number[]): number {
11+
let result = 0;
12+
for (let i = 0; i < prices.length; i++) {
13+
for (let j = i + 1; j < prices.length; j++) {
14+
let profit = prices[j] - prices[i];
15+
result = Math.max(profit, result);
16+
}
17+
}
18+
19+
return result;
20+
}
21+
22+
// 시간 복잡도: O(n)
23+
// 공간 복잡도: O(1)
24+
function twoPointerFunc(prices: number[]): number {
25+
let minPrice = prices[0];
26+
let maxProfit = 0;
27+
28+
for (let i = 1; i < prices.length; i++) {
29+
if (prices[i] < minPrice) {
30+
minPrice = prices[i];
31+
} else {
32+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
33+
}
34+
}
35+
36+
return maxProfit;
37+
}
38+
39+
return twoPointerFunc(prices);
40+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* 시간 복잡도: O(n) - 배열을 한 번만 순회함
3+
* 공간 복잡도: O(1) - 추가 배열 없이 변수만 사용하므로 입력 크기와 무관한 상수 공간
4+
*/
5+
/**
6+
* @param {number[]} prices
7+
* @return {number}
8+
*/
9+
var maxProfit = function (prices) {
10+
let minPrice = prices[0]; // 지금까지 본 가장 낮은 가격
11+
let maxProfit = 0; // 최대 이익
12+
for (let i = 1; i < prices.length; i++) {
13+
if (prices[i] > minPrice) {
14+
// 현재 가격이 minPrice보다 큰 경우에 이익 갱신
15+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
16+
} else {
17+
// 그렇지 않다면 최소 가격 갱신
18+
minPrice = prices[i];
19+
}
20+
}
21+
return maxProfit;
22+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time Complexity: O(n), where n is the length of the prices array
2+
// Space Complexity: O(1)
3+
4+
function maxProfit(prices: number[]): number {
5+
// input: an array prices, prices[i] = the stock price of ith day
6+
// output: the maximum profit || 0
7+
8+
// prices = [7, 1, 5, 3, 6, 4]
9+
// buy = 1, sell = 6, profit = 6 -1 = 5
10+
11+
let minBuy = prices[0];
12+
let maxProfit = 0;
13+
14+
for (let i = 1; i < prices.length; i++) {
15+
minBuy = Math.min(prices[i], minBuy);
16+
maxProfit = Math.max(prices[i] - minBuy, maxProfit);
17+
}
18+
19+
return maxProfit;
20+
}
21+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// time: O(n) space: O(n)
2+
class Solution {
3+
func maxProfit(_ prices: [Int]) -> Int {
4+
guard !prices.isEmpty else { return 0 }
5+
var result = [Int]()
6+
var current = prices[0]
7+
8+
for price in prices {
9+
if current > price {
10+
current = price
11+
continue
12+
}
13+
result.append(price - current)
14+
}
15+
return result.max() ?? 0
16+
}
17+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
[문제풀이]
3+
- 작은수를 두고, 큰수에 뺀 값을 구하자.
4+
time: O(N), space: O(1)
5+
6+
[회고]
7+
이번 문제는 난이도가 easy인 덕분에 무리없이 풀었던 것 같다.
8+
*/
9+
class Solution {
10+
public int maxProfit(int[] prices) {
11+
int min = prices[0];
12+
int max = 0;
13+
for (int i = 1; i < prices.length; i++) {
14+
min = Math.min(min, prices[i]);
15+
max = Math.max(max, prices[i] - min);
16+
}
17+
return max;
18+
}
19+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// NOTE: tc --> O(n)
2+
class Solution {
3+
public int maxProfit(int[] prices) {
4+
5+
int curMax = 0;
6+
int gMax = 0;
7+
8+
if(prices.length == 0) return 0;
9+
10+
int sell = prices[0];
11+
for(int i = 1; i < prices.length; i++) {
12+
curMax = Math.max(0, prices[i] - sell);
13+
14+
// NOTE: 새롭게 시작하는게 더 좋은경우
15+
if(curMax == 0) {
16+
sell = prices[i];
17+
}
18+
19+
gMax = Math.max(curMax, gMax);
20+
}
21+
22+
return gMax;
23+
}
24+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
class Solution:
3+
"""
4+
- Time Complexity: O(n), n = len(prices)
5+
- Space Complexity: O(1)
6+
"""
7+
def maxProfit(self, prices: List[int]) -> int:
8+
min_price = float("inf")
9+
max_profit = 0
10+
11+
for price in prices:
12+
min_price = min(min_price, price)
13+
max_profit = max(max_profit, price - min_price)
14+
15+
return max_profit
16+
17+
tc = [
18+
([7,1,5,3,6,4], 5),
19+
([7,6,4,3,1], 0)
20+
]
21+
22+
for i, (prices, e) in enumerate(tc, 1):
23+
sol = Solution()
24+
r = sol.maxProfit(prices)
25+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
let minPrice = Infinity;
7+
let maxProfit = 0;
8+
9+
for (let i = 0; i < prices.length; i++) {
10+
if (prices[i] < minPrice) {
11+
minPrice = prices[i]; // 지금까지 가장 싼 날
12+
} else if (prices[i] - minPrice > maxProfit) {
13+
maxProfit = prices[i] - minPrice; // 현재 이익이 최대 이익보다 클 때 maxProfit 갱신
14+
}
15+
}
16+
17+
return maxProfit;
18+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func maxProfit(_ prices: [Int]) -> Int {
3+
guard var anchor = prices.first, prices.count > 1 else {
4+
return 0
5+
}
6+
7+
var result = 0
8+
for price in prices {
9+
if price < anchor {
10+
anchor = price
11+
} else if price - anchor > result {
12+
result = price - anchor
13+
}
14+
}
15+
16+
return result
17+
}
18+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 연관 링크
2+
- [문제 풀이 스케줄](https://github.com/orgs/DaleStudy/projects/6/views/5)
3+
- [답안 코드 제출법](https://github.com/DaleStudy/leetcode-study/wiki/%EB%8B%B5%EC%95%88-%EC%A0%9C%EC%B6%9C-%EA%B0%80%EC%9D%B4%EB%93%9C)
4+
5+
# Problem
6+
- 문제 링크 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
7+
- 문제 이름 : Best Time to Buy and Sell Stock
8+
- 문제 번호 : 121
9+
- 난이도 : easy
10+
- 카테고리 :
11+
12+
# 문제 설명
13+
14+
15+
# 아이디어
16+
- 어떤 방법으로 접근했는지 서술
17+
- 포스 vs 최적화 아이디어 차이 등
18+
- 잡도에 대한 고려
19+
20+
# ✅ 코드 (Solution)
21+
22+
```cpp
23+
class Solution {
24+
public:
25+
int maxProfit(vector<int>& prices) {
26+
int localMax = prices[prices.size()-1];
27+
int res = 0;
28+
for(int i=prices.size()-2;i>=0;i--){
29+
localMax = max(localMax, prices[i]);
30+
res = max(res, localMax-prices[i]);
31+
}
32+
33+
return res;
34+
}
35+
};
36+
```
37+
38+
# 🔍 코드 설명
39+
40+
- local max를 설정
41+
42+
# 최적화 포인트 (Optimality Discussion)
43+
• 최적화한 이유와 원리
44+
• 더 줄일 수 있는 여지는 있는가?
45+
• 기존 방법 대비 얼마나 효율적이었는지
46+
47+
# 🧪 테스트 & 엣지 케이스
48+
49+
# 📚 관련 지식 복습
50+
51+
# 🔁 회고
52+
53+

0 commit comments

Comments
 (0)