
문제해석
각 i번째 날의 주가가 들어있는 배열 prices가 주어졌을 때
가장 큰 수익이 날 수 있는 값을 반환하기
주식은 무조건 산 이후 날만 판매가 가능함
정답 예
public int maxProfit(int[] prices) {
int length = prices.length;
if (length == 1) {
return 0;
}
int min = prices[0];
int maxProfit = 0;
for (int i = 1; i < length; i++) {
int price = prices[i];
// 작은 값 저장
if (min > price) {
min = price;
}
int profit = price - min;
// 현재가로 팔았을 경우 가격 비교
if (maxProfit < profit) {
maxProfit = profit;
}
}
return maxProfit;
}
참고 알고리즘
카데인 알고리즘
'Algorithm' 카테고리의 다른 글
| [leetcode 75] 704. Binary Search (0) | 2023.02.22 |
|---|---|
| [leetcode 75] 589. N-ary Tree Preorder Traversal (0) | 2023.02.21 |
| [leetcode 75] 142. Linked List Cycle II (1) | 2023.02.18 |
| [leetcode 75] 206. Reverse Linked List (0) | 2023.02.18 |
| [leetcode 75] 21. Merge Two Sorted Lists (0) | 2023.02.18 |