💡
Seb's Whiteboard
  • 👨‍💻Welcome, I'm Sebastien St Vil
  • Extras
    • Gradient Descent
    • How I learned Java
    • Machine Learning by Andrew Ng
  • Projects
    • 📉Backtest Equity Trading with SMA Strategy
    • Wellington GA Lab
    • Stock analysis
    • 📈Time Series Regression-based Trading Strategy
  • Arrays & Strings
    • Best Time to Buy and Sell Stock II
    • Online Stock Span
    • Implement strStr()
    • 2Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum II
    • Set Matrix Zeroes
    • Group Anagrams
    • Longest Substring Without Repeating Characters
    • Remove Duplicates from Sorted Array
    • Move Zeroes
    • Valid Sudoku
    • Rotate Image
    • First Unique Character in a String
    • Design a Circular Queue
    • Longest Common Prefix
  • Binary Tree
  • Second Minimum Node In a Binary Tree (671)
  • Design
  • LRU Cache
  • Min Stack (155)
  • Sorting & Searching
    • Merge Sorted Array (88)
    • First Bad Version
  • Math
    • Power of Three (326)
    • Power of Two (231)
    • Count Prime (204)
    • Roman to Integer (13)
    • Fizz Buzz (412)
    • Count-and-Say
  • Dynamic Programming
    • Pascal's Triangle (118)
  • Linked List
    • Copy List with Random Pointer
    • Remove Nth Node From End of List
    • Remove Duplicated from Sorted List II
  • Tips
    • Finding dups
  • Sliding Window
    • Subarray Product Less Than K
Powered by GitBook
On this page

Was this helpful?

  1. Arrays & Strings

Best Time to Buy and Sell Stock II

PreviousTime Series Regression-based Trading StrategyNextOnline Stock Span

Last updated 3 years ago

Was this helpful?

You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Approach:

The general idea is to buy stock at valleys (lowest price) and then sell stock at its next peak (highest price). In the below drawing, there are two valleys and two peaks. Since (1) we have to buy stock before selling it and (2) we can not have back-to-back buy or sell trades, thus there are two options of trading stocks.

Option 1: Buy stock at valley[1] then sell at peak[5] makes profit A (peak[5] - valley[1]). Then buy stock at valley [3] and sell at peak[6] makes profit B (peak[6] - valley[3]). So the total profit of this trade option is A + B.

Option 2: Skip the intermediate trades, i.e,, we buy stock at valley[1] then sell at peak[6]. In this case, the total profit will be C (peak[6]-valley[1]).

Based on the graph shown below, A + B > C --> 4 + 3 > 6 (if not, peak[i] and valley[j] won't exist). So in order to maximize the profit, we can buy stock at valleys and then sell stock at peaks.

I've drawn the below illustration to help conceptualize this problem:

from collections import deque
class Solution:
    def maxProfit(self, prices: List[int])-> int:
        stack = deque()
        profit = 0
        
        for price in prices:
            maxprice = 0
            while stack and price > stack[-1]:
                maxprice = max(maxprice, price - stack.pop())
            profit += maxprice
            stack.append(price)
        
        return profit