https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
🤣 문제 설명
- 주식의 일 가격이 나열되어 있는 정수 배열 prices 가 주어진다.
- 하루에 주식을 매수, 매도 할 수 있을 때, 기간동안 벌어들일 수 있는 가장 큰 이익을 구해 반환하라.
- 단 당일에 산 주식을 당일에 매도할 수 있으며 이익을 얻을 수 없을시 0을 반환한다.
- 1 <= prices.length <= 3 * 104
- 0 <= prices[i] <= 104
🥲 문제 해결
- 첫 번째날 가격을 current 변수에 저장하고 반복문을 돌아 prices 에 접근한다.
- price 가격이 현재 가격보다 클 시 매도하여 이익에 더하면 되고, 현재 가격보다 작을 시에는 매수하면 된다. 당일에 매도할 수 있기 때문이다. 이는 반복문을 돌면서 매번 current 를 prices[i] 로 갱신하는 코드로 대체된다.
🙂 시간복잡도
O(prices.length) 이므로, O(30000) 이다.
🙃 공간복잡도
O(1)이다.
😉 정답
class Solution {
public int maxProfit(int[] prices) {
int current = prices[0];
int profit = 0;
for(int price : prices) {
int money = price - current;
if(current < price) {
profit += money;
}
current = price;
}
return profit;
}
}
😗 개선사항
- 검색해보니 대부분 비슷하게 코드를 작성한 것 같다.
'개인 공부 > 코딩테스트' 카테고리의 다른 글
[LeetCode] 125번 (Valid Palindrome) (0) | 2023.08.28 |
---|---|
[LeetCode] 121번 (Best Time to Buy and Sell Stock) (0) | 2023.08.25 |
[LeetCode] 169번 (Majority Element) (0) | 2023.08.25 |
[LeetCode] 80번 (Remove Duplicates Sorted Array 2) (0) | 2023.08.25 |
[LeetCode] 26번 (Remove Duplicates Sorted Array 1) (0) | 2023.08.24 |