Skip to content

Commit aca8697

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 9cf683f + a41c907 commit aca8697

File tree

153 files changed

+5789
-1
lines changed

Some content is hidden

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

153 files changed

+5789
-1
lines changed

3sum/yoonthecoder.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var threeSum = function (nums) {
2+
nums.sort((a, b) => a - b);
3+
const results = [];
4+
for (let i = 0; i < nums.length - 2; i++) {
5+
if (i > 0 && nums[i] === nums[i - 1]) continue;
6+
let left = i + 1;
7+
let right = nums.length - 1;
8+
while (left < right) {
9+
const currSum = nums[i] + nums[left] + nums[right];
10+
11+
if (currSum == 0) {
12+
results.push([nums[i], nums[left], nums[right]]);
13+
left++;
14+
right--;
15+
// to avoid duplicates
16+
while (left < right && nums[left] === nums[left - 1]) left++;
17+
while (left < right && nums[right] === nums[right + 1]) right--;
18+
} else if (currSum < 0) {
19+
left++;
20+
} else right--;
21+
}
22+
}
23+
return results;
24+
};
25+
26+
// Time complexity: O(n^2);
27+
// Space complexity: O(n)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Solution: 1) 2중 포문을 돌면서 max값을 구한다.
3+
Time: O(n^2)
4+
Space: O(1)
5+
6+
Time Limit Exceeded
7+
8+
"""
9+
10+
11+
class Solution:
12+
def maxProfit(self, prices: List[int]) -> int:
13+
result = 0
14+
for l in range(len(prices) - 1):
15+
for r in range(l + 1, len(prices)):
16+
result = max(result, prices[r] - prices[l])
17+
18+
return result
19+
20+
21+
"""
22+
Solution:
23+
1) prices를 순회하면서 max_profit 을 찾는다.
24+
2) profit 은 current price - min_profit로 구한다.
25+
Time: O(n)
26+
Space: O(1)
27+
"""
28+
29+
30+
class Solution:
31+
def maxProfit(self, prices: List[int]) -> int:
32+
n = len(prices)
33+
max_profit = 0
34+
min_price = prices[0]
35+
36+
for i in range(1, len(prices)):
37+
profit = prices[i] - min_price
38+
max_profit = max(max_profit, profit)
39+
min_price = min(prices[i], min_price)
40+
return max_profit
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package leetcode_study
2+
3+
/*
4+
* 두 거래일 사이 최고의 수익을 구하는 문제
5+
* 시간 복잡도: O(n^2)
6+
* -> 모든 경우의 수를 순회하며 거래일 사이 최고 가격을 구하는 로직: O(n^2)
7+
* 공간 복잡도: O(1)
8+
* 아래 로직은 시간 초과 발생 O(n^2)의 복잡도를 줄여야함.
9+
* */
10+
fun maxProfit(prices: IntArray): Int {
11+
var result = Int.MIN_VALUE
12+
13+
for (i in prices.indices) {
14+
for (j in i + 1 until prices.size) {
15+
if (prices[i] < prices[j]) {
16+
if (result < prices[j] - prices[i]) {
17+
result = prices[j] - prices[i]
18+
}
19+
}
20+
}
21+
}
22+
if (result == Int.MIN_VALUE) return 0
23+
return result
24+
}
25+
26+
/*
27+
* 가장 작은 값을 저장하는 변수와 가장 큰 수익을 갖는 변수를 두고 문제 해결
28+
* 시간 복잡도: O(n)
29+
* 공간 복잡도: O(1)
30+
* */
31+
fun maxProfit2(prices: IntArray): Int {
32+
var minValue = Int.MAX_VALUE
33+
var maxValue = 0
34+
35+
for (price in prices) {
36+
if (price < minValue) {
37+
minValue = price
38+
} else if (price - minValue > maxValue) {
39+
maxValue = price - minValue
40+
}
41+
}
42+
return maxValue
43+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
/**
4+
1. understanding
5+
- price[i]: i th day's stock price
6+
- to maximize profit, choose a single day to buy, and future day to sell.
7+
- return maximum profit
8+
- [7, 1, 5, 3, 6, 4] -> [0, 0, 4, 4, 5, 5]
9+
- [7, 6, 4, 3, 1] -> [0, 0, 0, 0, 0]
10+
2. strategy
11+
- profit = (sell price) - (buy price)
12+
3. complexity
13+
- time: O(N)
14+
- space: O(1)
15+
*/
16+
int minPrice = prices[0];
17+
for (int i = 0; i <prices.length; i++) {
18+
int tmp = prices[i];
19+
if (i == 0) {
20+
prices[i] = 0;
21+
} else {
22+
prices[i] = Math.max(prices[i-1], prices[i] - minPrice);
23+
}
24+
minPrice = Math.min(minPrice, tmp);
25+
}
26+
27+
return prices[prices.length - 1];
28+
}
29+
}
30+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// 시간복잡도: O(n)
2+
// 공간복잡도: O(1)
3+
4+
// 최소값을 계속 갱신하면서 최대 이익을 계산
5+
6+
/**
7+
* @param {number[]} prices
8+
* @return {number}
9+
*/
10+
var maxProfit = function (prices) {
11+
let minPrice = Infinity;
12+
let maxProfit = 0;
13+
14+
for (let price of prices) {
15+
if (price < minPrice) {
16+
minPrice = price;
17+
} else {
18+
maxProfit = Math.max(maxProfit, price - minPrice);
19+
}
20+
}
21+
22+
return maxProfit;
23+
};
24+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# 시간 복잡도 : O(n)
2+
# 공간 복잡도 : O(1)
3+
class Solution:
4+
def maxProfit(self, prices: List[int]) -> int:
5+
min_price = float('inf')
6+
max_profit = 0
7+
8+
for price in prices:
9+
min_price = min(min_price, price)
10+
max_profit = max(max_profit, price - min_price)
11+
12+
return max_profit
13+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
 #해석
2+
#prices list를 순회하면서 최솟값 min_val을 업데이트 한다
3+
#현재 prices[n]과 min_val의 차를 업데이트 해준다.
4+
5+
6+
#Big O
7+
#N: prices 의 크기
8+
9+
#Time Complexity: O(N)
10+
#- for loop : prices의 원소 갯수만큼 순회하므로 O(N)
11+
12+
13+
#Space Complexity: O(1)
14+
#- min_val, answer : 변수는 상수이므로 O(1)
15+
class Solution(object):
16+
def maxProfit(self, prices):
17+
18+
#Initialize variables
19+
min_val = prices[0]
20+
answer = 0
21+
22+
for n in range(len(prices)):
23+
min_val= min(min_val,prices[n]) #Update min value of the prices list
24+
answer = max(prices[n]-min_val,answer) #Update max value of prices[n] - min value
25+
26+
return answer
27+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
6+
// TC : O(n)
7+
// SC : O(1)
8+
9+
var maxProfit = function (prices) {
10+
if (prices.length === 1) {
11+
return 0;
12+
}
13+
14+
// Two variables (profitMax and priceMin) are used to store the maximum profit and minimum price seen, which require O(1) space.
15+
let profitMax = 0;
16+
let priceMin = prices[0];
17+
18+
for (const price of prices) {
19+
const profit = price - priceMin;
20+
profitMax = Math.max(profit, profitMax);
21+
priceMin = Math.min(price, priceMin);
22+
}
23+
24+
return profitMax;
25+
};
26+
27+
// Why Constants Are Ignored in Big-O
28+
// In Big-O notation, O(2) is simplified to O(1) because constants are irrelevant in asymptotic analysis.
29+
// Big-O focuses on how resource usage scales with input size, not fixed values.
30+
31+
// Using 2 variables: O(1)
32+
// Using 10 variables: O(1)
33+
// Using 100 variables: O(1)
34+
35+
// What Space Complexity Looks Like for Larger Growth
36+
// O(n): Memory grows linearly with the input size (e.g., storing an array of n elements).
37+
// O(n^2): Memory grows quadratically (e.g., a 2D matrix with n*n elements).
38+
// 𝑂(log 𝑛): Memory grows logarithmically (e.g., recursive calls in binary search).
39+
// O(1): Fixed memory usage, regardless of input size (e.g., using a fixed number of variables).
40+
41+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Constraints:
3+
1. 1 <= prices.length <= 10^5
4+
2. 0 <= prices[i] <= 10^4
5+
6+
Time Complexity: O(n)
7+
8+
Space Complexity: O(1)
9+
10+
풀이 방법:
11+
- 배열을 한 번 순회하면서:
12+
1. 현재까지의 최소 가격(min_price)을 계속 갱신
13+
2. 현재 가격에서 최소 가격을 뺀 값(현재 가능한 이익)과 기존 최대 이익을 비교하여 더 큰 값을 저장
14+
- 이 방식으로 각 시점에서 가능한 최대 이익을 계산함
15+
16+
To Do:
17+
- 다른 접근 방법 찾아보기 (Two Pointers, Dynamic Programming)
18+
"""
19+
20+
class Solution:
21+
def maxProfit(self, prices: List[int]) -> int:
22+
min_price = prices[0]
23+
max_profit = 0
24+
25+
for i in range(1, len(prices)):
26+
min_price = min(min_price, prices[i])
27+
max_profit = max(max_profit, prices[i] - min_price)
28+
29+
return max_profit
30+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* 최대 수익을 구하는 알고리즘
3+
* 알고리즘 복잡도
4+
* - 시간 복잡도: O(n)
5+
* - 공간 복잡도: O(1)
6+
* @param prices
7+
*/
8+
function maxProfit(prices: number[]): number {
9+
let min = prices[0]
10+
let total = 0
11+
12+
for(let i = 1 ; i < prices.length ; i++) {
13+
min = Math.min(min, prices[i])
14+
// console.log(dp[i],'===', dp[i-1], '===', prices[i])
15+
total = Math.max(total, prices[i] - min)
16+
}
17+
18+
return total
19+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 최대 이익을 계산하는 함수
3+
* @param {number[]} prices
4+
* @returns {number}
5+
*
6+
* 시간 복잡도 : O(n) (n: 주식 가격 배열의 길이)
7+
* 공간 복잡도 : 0(1) (추가 자료구조 X)
8+
*/
9+
function maxProfit(prices: number[]): number {
10+
let minPrice = 100001; // 지금까지의 최소 가격
11+
let maxProfit = 0; // 최대 이익
12+
13+
for (let price of prices) {
14+
// 최소 가격 갱신
15+
if (price < minPrice) {
16+
minPrice = price;
17+
}
18+
19+
// 현재 가격에서 최소 가격을 뺀 이익이 최대 이익보다 크다면 갱신
20+
const potentialProfit = price - minPrice;
21+
if (potentialProfit > maxProfit) {
22+
maxProfit = potentialProfit;
23+
}
24+
}
25+
26+
return maxProfit;
27+
}
28+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# 시간복잡도 O(n)
2+
# 공간복잡도 O(1)
3+
class Solution:
4+
def maxProfit(self, prices: list[int]) -> int:
5+
min_p = prices[0] # 최소 가격 설정 : 배열의 첫 번째 가격
6+
cur = 0
7+
max_p = 0
8+
for n in prices:
9+
if n < min_p: # 현재 가격이 최소 가격보다 작다면 최소가격 갱신
10+
min_p = n
11+
cur = n - min_p # 현재 이익 계산
12+
if max_p < cur: # 현재 이익과 최대로 얻을 수 있는 이익 비교
13+
max_p = cur # 최대 이익 갱신신
14+
15+
return max_p
16+
17+
18+
19+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* 시간 복잡도: prices.length만큼 순회하므로 O(n)
3+
* 공간 복잡도: 상수 크기의 변수만 사용하므로 O(1)
4+
*/
5+
/**
6+
* @param {number[]} prices
7+
* @return {number}
8+
*/
9+
var maxProfit = function (prices) {
10+
let maxProfit = 0;
11+
let min = prices[0];
12+
13+
for (let i = 0; i < prices.length; i++) {
14+
maxProfit = Math.max(maxProfit, prices[i] - min);
15+
min = Math.min(min, prices[i]);
16+
}
17+
return maxProfit;
18+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
3+
* Runtime: 6ms, Memory: 62.30MB
4+
*
5+
* Time Complexity: O(N)
6+
* Space Complexity: O(1)
7+
*/
8+
9+
function maxProfit(prices: number[]): number {
10+
let buyingPrice = prices[0];
11+
let profit = 0;
12+
13+
for (const price of prices) {
14+
buyingPrice = Math.min(price, buyingPrice);
15+
profit = Math.max(profit, price - buyingPrice);
16+
}
17+
18+
return profit;
19+
}
20+
21+
maxProfit([7, 1, 5, 3, 6, 4]);

0 commit comments

Comments
 (0)