You are given an array prices where prices[i] is the price of a given stock on the ith day,
and an integer fee representing a transaction fee.
Find the maximum profit you can achieve.
You may complete as many transactions as you like,
but you need to pay the transaction fee for each transaction.
Note:
- You may not engage in multiple transactions simultaneously
(i.e., you must sell the stock before you buy again).
- The transaction fee is only charged once for each stock purchase and sale.
i번째 날의 주식 가격을 담은 prices 배열이 있습니다.
또한 주식을 판매할때마다 fee 만큼의 비용을 지불해야 합니다.
1주를 매수, 매도 함으로 얻을수 있는 최대의 이익을 구하세요
단 아래 규칙을 따라야 합니다.
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation:
i = 0 일때 구매 -> i = 3 일때 판매 ( 8 - 1 - 2 원 이익 )
i - 4 일때 구매 -> i = 5 일때 판매 ( 9 - 4 - 2 원 이익 )
2원은 매도 수수료 ( fee )
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
buy = -prices[0]
sell = 0
for i in range(1, len(prices)):
buy_changed = max(buy, sell - prices[i])
sell_changed = max(sell, buy + prices[i] - fee)
buy = buy_changed
sell = sell_changed
return sell