Skip to content

Commit c188307

Browse files
committed
5주차 문제 풀이
1 parent d155be4 commit c188307

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+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
/*
6+
주어진 배열 prices에서 prices[i]는 i번째 날의 주가를 의미한다.
7+
8+
한 번의 거래(1회 매수 + 1회 매도)만 할 수 있으며,
9+
미래의 어떤 날에 매도해야 한다. (즉, 매수일 < 매도일)
10+
11+
목표:
12+
- 매수 후 매도하여 만들 수 있는 최대 이익을 계산한다.
13+
- 이익을 낼 수 없다면 0을 반환한다.
14+
15+
입력 형식 :
16+
- prices: 정수 배열
17+
- 1 <= prices.length <= 100,000
18+
- 0 <= prices[i] <= 10,000
19+
20+
출력 형식 :
21+
- 만들 수 있는 최대 이익 (정수)
22+
23+
예시 :
24+
25+
Example 1
26+
입력 : prices = [7,1,5,3,6,4]
27+
출력 : 5
28+
설명 :
29+
- 2번째 날(가격 1)에 매수
30+
- 5번째 날(가격 6)에 매도
31+
- 이익 = 6 - 1 = 5
32+
33+
※ 매수일보다 앞선 날짜에 매도하는 것은 불가능함.
34+
35+
Example 2
36+
입력 : prices = [7,6,4,3,1]
37+
출력 : 0
38+
설명 :
39+
- 어떤 날을 매수해도 이후 가격이 상승하지 않음
40+
- 이익을 낼 수 없으므로 0 반환
41+
*/
42+
var maxProfit = function(prices) {
43+
44+
let min_value = prices[0];
45+
let min_value_index = 0;
46+
let max_value = 0;
47+
48+
for (let i = 0; i < prices.length; i ++) {
49+
if(prices[i] < min_value)
50+
{
51+
min_value = prices[i];
52+
min_value_index = i;
53+
}
54+
}
55+
56+
if(min_value_index == (prices.length - 1))
57+
{
58+
return 0;
59+
}
60+
61+
for (min_value_index; min_value_index < prices.length; min_value_index++)
62+
{
63+
64+
if (max_value < prices[min_value_index]) {
65+
max_value = prices[min_value_index];
66+
}
67+
}
68+
69+
return max_value - min_value;
70+
};
71+
72+
console.log(maxProfit([7,1,5,3,6,4]))
73+
console.log(maxProfit([7,6,4,3,1]))
74+
75+
76+

0 commit comments

Comments
 (0)