Skip to content

Commit 52805fa

Browse files
2 parents 7c7f32d + 57444a4 commit 52805fa

File tree

174 files changed

+6198
-39
lines changed

Some content is hidden

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

174 files changed

+6198
-39
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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
int maxProfit(vector<int>& prices) {
4+
int min = INT_MAX;
5+
int profit = 0;
6+
7+
for(int i = 0; i < prices.size(); i++){
8+
if(prices[i] < min)
9+
min = prices[i];
10+
11+
profit = max(profit, prices[i] - min);
12+
}
13+
14+
return profit;
15+
}
16+
};
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 주식 가격이 주어지는 prices 배열이 있을 때 최대 주식 이익을 구하시오
3+
* 주식을 산 날짜에는 팔 수 없으며 반드시 산 날짜의 이후 날짜부터(미래부터) 팔 수 있다.
4+
*/
5+
class Solution {
6+
public int maxProfit(int[] prices) {
7+
int maxProfit = 0;
8+
int min = prices[0];
9+
// 굳이 DP 배열 쓰지 않고 계산, 공간 복잡도 낮추기
10+
for (int i = 0; i < prices.length; i++) {
11+
int profit = prices[i] - min;
12+
maxProfit = Math.max(profit, maxProfit);
13+
min = Math.min(prices[i], min);
14+
}
15+
return maxProfit;
16+
}
17+
18+
// public int maxProfit(int[] prices) {
19+
// // 최저 구매
20+
// int[] dp = new int[prices.length];
21+
// dp[0] = prices[0];
22+
// for (int i = 1; i < prices.length; i++) {
23+
// dp[i] = Math.min(prices[i], dp[i - 1]);
24+
// }
25+
// // 최저 구매 배열 기준으로 당일 최대 이익 계산
26+
// int profit = 0;
27+
// for (int i = 1; i < prices.length; i++) {
28+
// profit = Math.max(prices[i] - dp[i - 1], profit);
29+
// }
30+
// return profit;
31+
// }
32+
}
33+
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: 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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* 시간 복잡도 O(n)
3+
* 공간 복잡도 O(1)
4+
*
5+
* 그리디 알고리즘
6+
* 현재까지의 최저 가격을 기억하고, 그 가격에 샀을 때의 이익을 계속 계산하여 최대 이익을 구함
7+
*/
8+
9+
/**
10+
* @param {number[]} prices
11+
* @return {number}
12+
*/
13+
var maxProfit = function (prices) {
14+
let minPrice = prices[0]; // 최저 가격 초기화 (첫 날 가격)
15+
let maxProfit = 0; // 최대 이익 초기화 (아직 이익 없음)
16+
17+
// 두 번째 날부터
18+
for (let i = 1; i < prices.length; i++) {
19+
minPrice = Math.min(minPrice, prices[i]); // 최저 가격 갱신
20+
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // 최대 이익 갱신
21+
}
22+
23+
return maxProfit;
24+
};
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: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function(prices) {
6+
let buy = prices[0]
7+
let maxVal = 0
8+
9+
for(let i = 1; i < prices.length; i++) {
10+
if(prices[i - 1] > prices[i]) {
11+
buy = Math.min(buy, prices[i])
12+
}
13+
14+
if(prices[i - 1] < prices[i]) {
15+
maxVal = Math.max(maxVal, prices[i] - buy)
16+
}
17+
}
18+
return maxVal
19+
};
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(1)
4+
5+
Dynamic programming
6+
"""
7+
8+
class Solution:
9+
def maxProfit(self, prices: List[int]) -> int:
10+
max_profit = 0
11+
min_price = prices[0]
12+
for p in prices:
13+
max_profit = max(max_profit, p - min_price)
14+
min_price = min(min_price, p)
15+
16+
return max_profit
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function maxProfit(prices: number[]): number {
2+
if (prices.length <= 1) return 0;
3+
4+
let minPrice = prices[0];
5+
let maxProfit = 0;
6+
7+
for (let i = 1; i < prices.length; i++) {
8+
// 현재 가격이 최소가보다 낮으면 최소가 업데이트
9+
if (prices[i] < minPrice) {
10+
minPrice = prices[i];
11+
}
12+
// 현재 가격으로 팔았을 때의 이익 계산
13+
else {
14+
const currentProfit = prices[i] - minPrice;
15+
// 최대 이익 업데이트
16+
if (currentProfit > maxProfit) {
17+
maxProfit = currentProfit;
18+
}
19+
}
20+
}
21+
22+
return maxProfit;
23+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">week05-1.best-time-to-buy-and-sell-stock</a>
3+
* <li>Description: Return the maximum profit you can achieve from this transaction</li>
4+
* <li>Topics: Array, Dynamic Programming </li>
5+
* <li>Time Complexity: O(N), Runtime 2ms </li>
6+
* <li>Space Complexity: O(1), Memory 61.62MB </li>
7+
*/
8+
class Solution {
9+
public int maxProfit(int[] prices) {
10+
int min = prices[0];
11+
int profit = 0;
12+
for(int i=1; i<prices.length; i++) {
13+
profit = Math.max(profit, prices[i]-min);
14+
min = Math.min(min, prices[i]);
15+
}
16+
return profit;
17+
}
18+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
let minPrices = Infinity;
7+
let profit = 0;
8+
for (price of prices) {
9+
minPrices = Math.min(price, minPrices);
10+
profit = Math.max(profit, price - minPrices);
11+
}
12+
return profit;
13+
};
14+
15+
var maxProfit = function (prices) {
16+
let maxProfit = 0;
17+
let currentProfit = 0;
18+
for (let i = 1; i < prices.length; i++) {
19+
let diff = prices[i] - prices[i - 1];
20+
currentProfit = Math.max(0, currentProfit + diff);
21+
maxProfit = Math.max(maxProfit, currentProfit);
22+
}
23+
return maxProfit;
24+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution(object):
2+
def maxProfit(self, prices):
3+
"""
4+
:type prices: List[int]
5+
:rtype: int
6+
주어진 prices를 한 번만 순회하면서
7+
지금까지의 최솟값을 추적하고,
8+
'현재 가격 - 지금까지의 최솟값'으로 계산되는 이익이
9+
'지금까지의 최대 이익(초기 0)보다 크면 갱신하여
10+
최종 최대 이익 구하기 문제
11+
Time Complexity: O(n)
12+
Space Complexity: O(1)
13+
"""
14+
max_profit = 0 # 이익이 없을 때 0을 반환하게 초기화
15+
min_price = float('inf') # 최소 가격 저장, 무한대로 초기화해서 루프 첫 번째 가격부터 최소 가격에 저장
16+
17+
for price in prices:
18+
# 최대 이익 갱신
19+
max_profit = max(max_profit, (price - min_price))
20+
# 최소 가격 갱신
21+
min_price = min(min_price, price)
22+
# 최대 이익(max_profit) 갱신 이후 최소 가격(min_price) 갱신해야 함
23+
# 최대 이익 자체는 이미 '산' 주식에 대해 계산해야 하므로
24+
# 사는 동시 팔 수 없음
25+
26+
return max_profit
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def maxProfit1(self, prices: List[int]) -> int:
7+
"""
8+
[Complexity]
9+
- TC: O(n)
10+
- SC: O(1)
11+
12+
[Approach]
13+
prices를 순회하면서 다음을 트래킹하면 된다.
14+
(1) 지금까지의 최소 가격인 min_price 트래킹: min(min_price, price)
15+
(2) 지금까지의 최대 수익인 max_profit 트래킹: max(max_profit, price - min_price)
16+
"""
17+
max_profit, min_price = 0, prices[0]
18+
19+
for price in prices:
20+
min_price = min(min_price, price)
21+
max_profit = max(max_profit, price - min_price)
22+
23+
return max_profit
24+
25+
def maxProfit(self, prices: List[int]) -> int:
26+
"""
27+
[Complexity]
28+
- TC: O(n)
29+
- SC: O(1)
30+
31+
[Approach]
32+
two-pointer(buy, sell)로도 접근 가능하다.
33+
두 개의 pointer buy와 sell을 0, 1 인덱스에서 시작한 후, sell을 움직여가며 curr_profit = prices[sell] - prices[buy]를 구한다.
34+
그리고 curr_profit이 0보다 크면 max_profit을 트래킹하고, 그렇지 않으면 buy를 sell 위치로 당긴다.
35+
(curr_profit이 0보다 크지 않다는 것은, buy 시점의 price 이하인 price가 sell 시점에서 발견되었다는 뜻이다!)
36+
"""
37+
buy, sell = 0, 1
38+
max_profit = 0
39+
40+
while sell < len(prices):
41+
curr_profit = prices[sell] - prices[buy]
42+
if curr_profit > 0:
43+
max_profit = max(max_profit, curr_profit)
44+
else:
45+
buy = sell
46+
sell += 1
47+
48+
return max_profit
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
int minPrice = prices[0];
4+
int maxProfit = 0;
5+
6+
for(int p : prices){
7+
if(minPrice < p && maxProfit < p - minPrice){
8+
maxProfit = p - minPrice;
9+
}
10+
if(minPrice > p){
11+
minPrice = p;
12+
}
13+
}
14+
return maxProfit;
15+
}
16+
}
17+

0 commit comments

Comments
 (0)