728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.
문제는 여기서 볼 수 있습니다.
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
Code:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell, maxProfit = 0, 1, 0
while sell < len(prices): # 둘째날~마지막날 파는 경우 탐색
profit = prices[sell] - prices[buy]
if prices[buy] < prices[sell]:
maxProfit = max(profit,maxProfit)
else:
buy = sell # 더 작은 가격인 sell날로 buy날을 옮김
sell += 1 # 각 파는 날마다 이익이 나는지 확인하므로 if문 후 날짜 업데이트
return maxProfit
if문에서는 산 날의 가격보다 판 날의 가격이 더 큰지, 즉 이익이 나는지의 여부를 따진다. 이익이 난다면 최대이익인지를 확인한다.
만약 if문에서 이득이 나지 않는다는 결과가 나온다면, 즉 else문이 실행된다면 sell날의 가격이 buy날의 가격보다 작은 것이다. 살 때의 가격은 적을수록 이득이므로 buy 날짜를 sell 날짜로 옮긴다.
if문의 결과와 무관하게 sell 날짜는 계속 하나씩 늘어난다. 즉, 파는 날이 둘째날, 셋째날, ..., 마지막 날일 경우의 각 최댓값을 매번 구해서 전체 최댓값보다 큰 지를 비교하는 과정인 것이다.
728x90
'알고리즘' 카테고리의 다른 글
[Leetcode/Python] Valid Palindrome (0) | 2022.08.21 |
---|---|
[Leetcode/Python] Reverse String (0) | 2022.08.21 |
[Leetcode/Python] Count Primes (0) | 2022.08.18 |
[Leetcode/Python] Validate Binary Search Tree (0) | 2022.08.16 |
[LeetCode/Python] Reverse Linked List (0) | 2022.08.15 |