코-딩/Leetcode

[leetcode] 714. Best Time to Buy and Sell Stock with Transaction Fee (python)

2022. 9. 27. 20:04
728x90

문제: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

난이도: Medium

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).

 

풀이
class Solution:  #dp
    def maxProfit(self, prices: List[int], fee: int) -> int:
      
        sell_stock = [0 for _ in range(len(prices))]      # i번째 날에 팔았을 때
        not_sell_stock = [0 for _ in range(len(prices))]  # i번째 날에 사거나 넘어갔을 때(fee 지불)
        
        # 주식은 buy부터 시작
        sell_stock[0] = 0
        not_sell_stock[0] = -prices[0] - fee
        
        for i in range(1, len(prices)):
            sell_stock[i] = max(sell_stock[i - 1], not_sell_stock[i - 1] + prices[i])
            not_sell_stock[i] = max(sell_stock[i - 1] - prices[i] - fee, not_sell_stock[i - 1])
        
        return sell_stock[-1]

 

  • sell_stock[i] : i번째 날 stock을 팔거나 가지고 있지 않을 때 최대 이익
  • not_sell_stock[i] : i번째 날 stock을 사거나 계속 가지고 있을 때 최대 이익. 이 때 거래 수수료를 고려해야 한다.
  • 주식은 처음에 사야지 매도할 수 있기 때문에 사는 것부터 시작한다.
  • 보자마자 dp로 풀었는데 다양한 알고리즘으로도 풀 수 있다.
  • 자고로 주식은 저점에서 사고 고점에서 파는게 진리이며 여기선 이것을 보장해준다.(현실에서도 부탁드려요,,)
    또한, 추가 매수가 불가하기 때문에(사면 무조건 팔아야 한다.) greedy 알고리즘으로도 충분히 풀 수 있다.

 

 

728x90
저작자표시 동일조건 (새창열림)
'코-딩/Leetcode' 카테고리의 다른 글
  • [leetcode] 720. Longest Word in Dictionary (python)
  • [leetcode] 74. Search a 2D Matrix (python)
  • [leetcode] 605. Can Place Flowers
  • [leetcode]242. Valid Anagram (python)
힞뚜루마뚜루
힞뚜루마뚜루
250x250
힞뚜루마뚜루
히++;
힞뚜루마뚜루
전체
오늘
어제
  • 히++; (107)
    • 코-딩 (50)
      • BOJ (8)
      • 프로그래머스 (19)
      • Leetcode (23)
    • IT (21)
      • Spring | Java (9)
      • CS (2)
      • Angular (2)
      • Design Pattern (4)
      • etc (4)
    • 후-기 (12)
      • 취업 후기 (7)
      • 일상 후기 (5)
    • 일기 (24)

블로그 메뉴

  • 홈
  • Guestbook
  • Tag Cloud
  • 글 작성

공지사항

인기 글

최근 댓글

최근 글

250x250
hELLO · Designed By 정상우.
힞뚜루마뚜루
[leetcode] 714. Best Time to Buy and Sell Stock with Transaction Fee (python)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.