Skip to content

Commit b577d76

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 5054a1f + 682c786 commit b577d76

136 files changed

Lines changed: 5289 additions & 93 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// naive하게 풀면, time limit 초과함
2+
// O(n^2) 풀이가 되기 때문..
3+
const maxProfit_naive = function (prices) {
4+
let profit = 0;
5+
6+
for (let i = 0; i < prices.length - 1; i++) {
7+
const buy = prices[i];
8+
for (let j = i + 1; j < prices.length; j++) {
9+
const newProfit = prices[j] - buy;
10+
if (newProfit > profit) {
11+
profit = newProfit;
12+
}
13+
}
14+
}
15+
16+
return profit;
17+
};
18+
19+
// 투포인터 사용하여 풀기
20+
// tc: O(n)
21+
// sc: O(1)
22+
const maxProfit = function (prices) {
23+
let buyIdx = 0;
24+
let sellIdx = 1;
25+
let profit = 0;
26+
27+
while (sellIdx < prices.length) {
28+
let buyPrice = prices[buyIdx];
29+
let sellPrice = prices[sellIdx];
30+
31+
// 더 낮은 가격에 매수 가능한 날을 찾으면 바로 거기서부터 재탐색
32+
if (buyPrice > sellPrice) {
33+
buyIdx = sellIdx;
34+
} else {
35+
let newProfit = sellPrice - buyPrice;
36+
profit = Math.max(profit, newProfit);
37+
}
38+
39+
sellIdx++;
40+
}
41+
42+
return profit;
43+
};
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
3+
4+
5+
6+
7+
//O(n)에 증가 한 경우 profitMax를 갱신시키며 판단 -> time limit
8+
public int maxProfit(int[] prices) {
9+
int profitMax = 0;
10+
/*
11+
for(int i=0; i< prices.length - 1; i++){
12+
int buy= prices[i];
13+
14+
15+
for(int d =i+1; d < prices.length; d++){
16+
int sellCandid = prices[d];
17+
if (sellCandid - buy > profitMax){
18+
profitMax = sellCandid - buy;
19+
}
20+
21+
}
22+
}//end of for
23+
24+
*/
25+
26+
int priceMin = Integer.MAX_VALUE;
27+
for(int i =0; i < prices.length; i++){
28+
if (prices[i] < priceMin){
29+
priceMin = prices[i];
30+
}
31+
else{
32+
profitMax = Math.max(profitMax, prices[i] - priceMin);
33+
}
34+
}
35+
36+
return profitMax;
37+
38+
}
39+
40+
}
41+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
// TC : O(n)
3+
// SC : O(1)
4+
public int maxProfit(int[] prices) {
5+
int maximumProfit = 0;
6+
int cursor = 0;
7+
8+
// 전체를 순회하면서 이익을 검증
9+
for(int i = 0; i < prices.length; i++){
10+
int profit = prices[i] - prices[cursor];
11+
12+
// 만약 현재 값이 커서의 값보다 더 작다면 현재 값부터 비교하기 시작
13+
if(profit < 0){
14+
cursor = i;
15+
continue;
16+
}
17+
18+
// 이전에 커서로 추정한 값이 높더라도 Math.max로 보존됨
19+
maximumProfit = Math.max(profit, maximumProfit);
20+
}
21+
22+
return maximumProfit;
23+
}
24+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
# Approach
3+
지금까지의 최저 가격을 갱신함과 동시에 최선의 이익도 업데이트합니다.
4+
5+
# Complexity
6+
- Time complexity: O(N)
7+
8+
- Space complexity: O(1)
9+
"""
10+
11+
12+
class Solution:
13+
def maxProfit(self, prices: list[int]) -> int:
14+
min_price = float("inf")
15+
answer = 0
16+
17+
for price in prices:
18+
min_price = min(min_price, price)
19+
answer = max(answer, price - min_price)
20+
21+
return answer
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
[결과 요약]
3+
# 시도한 로직 수: 2
4+
1. if/else 문으로 분기 처리(시간: O(n) / 공간: O(1))
5+
-
6+
2. if문 대신 min / max를 계속 계산하는 로식
7+
- None 대신 float(inf)를 사용하여 None 검증 분기 제거
8+
- inf 사용을 위해서 마지막 return에 int() 타입 변환 필요
9+
- 성능은 1과 큰 차이 없으며 코드가 간소화
10+
"""
11+
12+
13+
class Solution:
14+
def maxProfit(self, prices: list[int]) -> int:
15+
max_profit = 0
16+
min_price = float("inf")
17+
18+
for p in prices:
19+
min_price = min(min_price, p)
20+
max_profit = max(max_profit, p - min_price)
21+
22+
return int(max_profit)
23+
24+
25+
if __name__ == "__main__":
26+
test_cases = [
27+
([7, 1, 5, 3, 6, 4], 5),
28+
([7, 6, 4, 3, 1], 0),
29+
([2, 4, 1], 2),
30+
([1, 2, 4, 10000, 2, 1, 3], 9999),
31+
]
32+
33+
solution = Solution()
34+
for idx, case_ in enumerate(test_cases):
35+
prices, answer = case_
36+
result = solution.maxProfit(prices)
37+
assert (
38+
answer == result
39+
), f"Test Case {idx} Failed: Expected {answer}, Got {result}"
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public:
3+
int maxProfit(vector<int>& prices) {
4+
int res = 0;
5+
int minPrice = prices[0];
6+
int len = prices.size();
7+
for (int i = 0; i < len; ++i)
8+
{
9+
res = max(res, prices[i] - minPrice); // 수익 최대화: 지금까지 가장 쌌던 날에 사서 오늘 팔기
10+
minPrice = min(minPrice, prices[i]); // '지금까지 가장 쌌던 날' 업데이트
11+
}
12+
13+
return res;
14+
}
15+
};
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
/**
4+
1. 하루에 팔아서 가장 최대 이익을 구하도록하는 max price return
5+
2. 조건
6+
- 미래 다른날짜에 판매 (이전 날짜에 판매 x)
7+
- choosing a single day
8+
- 배열 길이 min = 1, max = 10^5
9+
- 원소값 : min = 0, max = 10^4
10+
3. 풀이
11+
- 1)brtueforce: time complexity O(n^2), space: O(1)
12+
- 2)현재 값 - 이전 값 중 가장 최소값 -> maxProfit , 즉 min값을 계속 기억하다가 현재 값과의 차이 중 가장 큰 값을 구하면된다.
13+
- time: O(n)
14+
- space: O(1)
15+
*/
16+
17+
int maxProfit = 0;
18+
int minStock = Integer.MAX_VALUE;
19+
int n = prices.length;
20+
21+
for(int i = 0; i<n; i++) {
22+
if(prices[i] < minStock) {
23+
minStock = prices[i];
24+
}
25+
if(i > 0 && prices[i] - minStock > maxProfit) {
26+
maxProfit = Math.max(maxProfit, prices[i] - minStock);
27+
}
28+
}
29+
return maxProfit;
30+
31+
32+
// for(int i = 0; i < n; i++) {
33+
// int curStock = prices[i];
34+
// for(int j= i + 1; j < n; j++) {
35+
// if(curStock < prices[j]) {
36+
// int curProfit = prices[j] - curStock;
37+
// maxProfit = Math.max(maxProfit, curProfit);
38+
// }
39+
// }
40+
// }
41+
// return maxProfit;
42+
}
43+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
시간복잡도: O(n²)
3+
공간복잡도: O(1)
4+
class Solution {
5+
public int maxProfit(int[] prices) {
6+
int maxStock = 0;
7+
for(int i = 0; i < prices.length; i++) {
8+
for (int j = 0; j < prices.length; j++) {
9+
if (i <= j) break;
10+
if (prices[i] - prices[j] > maxStock) {
11+
maxStock = prices[i] - prices[j];
12+
}
13+
}
14+
}
15+
return maxStock;
16+
}
17+
}
18+
*/
19+
// 시간복잡도: O(n)
20+
// 공간복잡도: O(1)
21+
class Solution {
22+
public int maxProfit(int[] prices) {
23+
int maxStock = 0;
24+
int minPrice = prices[0];
25+
for (int price : prices) {
26+
if (price < minPrice) {
27+
minPrice = price;
28+
} else {
29+
maxStock = Math.max(price - minPrice, maxStock);
30+
}
31+
}
32+
return maxStock;
33+
}
34+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// TC: O(N)
2+
// SC: O(1)
3+
function maxProfit(prices: number[]): number {
4+
let maxProfit = 0
5+
let minPrice = Infinity
6+
7+
for(const price of prices) {
8+
maxProfit = Math.max(price - minPrice, maxProfit)
9+
minPrice = Math.min(price, minPrice)
10+
}
11+
12+
return maxProfit
13+
14+
};
15+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
# When length is 1, no profit possible
4+
if len(prices) == 1:
5+
return 0
6+
7+
buy = 10 ** 5
8+
profit = 0
9+
10+
# Iterate through prices
11+
for price in prices:
12+
# if price < buy:
13+
# buy = price
14+
15+
# for j in range(i + 1, len(prices)):
16+
# if prices[j] <= buy:
17+
# continue
18+
19+
# if prices[j] - buy > profit:
20+
# profit = prices[j] - buy
21+
buy = min(buy, price)
22+
profit = max(profit, price - buy)
23+
24+
return profit
25+
26+
# Time Complexity: O(n)
27+
# Space Complexity: O(1)

0 commit comments

Comments
 (0)