Skip to content

Commit 278485c

Browse files
committed
1. Best Time to Buy And Sell Stock
1 parent c7afa4d commit 278485c

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* 아이디어
3+
* 수익을 얻기 위해서는 index보다 뒤에 오는 값 중에 현재 값보다 큰 값이 있어야 한다
4+
* 차이가 가장 큰 두 값을 찾으면 되는데, 그 값의 순서가 작은값 다음 큰 값 순이어야 한다
5+
* 가격의 차이를 어떻게 구할 수 있을까?
6+
* for문을 두번 돌면서 값의 차이를 저장해둔다.(순서가 일치해야함)
7+
* 값의 차이 중 가장 큰 값을 리턴한다.
8+
* 리턴할 값이 없으면 0을 리턴한다.
9+
* ====> 이 방법으로 풀었더니 타임초과가 나왔다.
10+
* 어떻게 시간복잡도를 줄일 수 있을까?
11+
* for문을 두번돌면 O(n^2)이 드니 for문을 한번만 돌게 하면 좋을 것 같다.
12+
* for문을 돌면서 가장 작은 구매가, 최대 이익 두가지 변수를 업데이트 하자
13+
* ===> 연습삼아 투포인터로도 풀어보자
14+
*/
15+
16+
function maxProfit1(prices: number[]): number {
17+
let profit = 0;
18+
19+
for (let i = 0; i <= prices.length - 2; i++) {
20+
const x = prices[i];
21+
for (let j = i + 1; j <= prices.length - 1; j++) {
22+
const y = prices[j];
23+
const diff = y - x;
24+
if (x < y && profit < diff) {
25+
profit = diff;
26+
}
27+
}
28+
}
29+
30+
return profit;
31+
}
32+
// TC: O(n^2)
33+
// SC: O(1)
34+
35+
function maxProfit2(prices: number[]): number {
36+
let buyPrice = prices[0];
37+
let profit = 0;
38+
39+
for (let i = 0; i <= prices.length - 1; i++) {
40+
const todayPrice = prices[i];
41+
const diff = todayPrice - buyPrice;
42+
43+
if (todayPrice <= buyPrice) {
44+
buyPrice = todayPrice;
45+
} else {
46+
if (profit < diff) {
47+
profit = todayPrice - buyPrice;
48+
}
49+
}
50+
}
51+
52+
return profit;
53+
}
54+
// TC: O(n)
55+
// SC: O(1)
56+
57+
function maxProfit3(prices: number[]): number {
58+
let left = 0;
59+
let right = 1;
60+
let maxProfit = 0;
61+
62+
while (right <= prices.length - 1) {
63+
if (prices[left] > prices[right]) {
64+
left = right;
65+
} else {
66+
const profit = prices[right] - prices[left];
67+
maxProfit = Math.max(profit, maxProfit);
68+
}
69+
70+
right++;
71+
}
72+
73+
return maxProfit;
74+
}
75+
// TC: O(n)
76+
// SC: O(1)

0 commit comments

Comments
 (0)