Best Time to Buy and Sell Stock

[2]:
import IPython; IPython.display.HTML('''<script>code_show=true; function code_toggle() { if (code_show){ $('div.nbinput').show(); } else { $('div.nbinput').hide(); } code_show = !code_show} $( document ).ready(code_toggle);</script><form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
[2]:

188. IV

Hard

Say you have an array for which the i-th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
[3]:
# DP 解答的一維陣列版本 https://www.youtube.com/watch?v=oDhu5uGq_ic
# 有比 DB 更快的算法 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/54118/C%2B%2B-Solution-with-O(n-%2B-klgn)-time-using-Max-Heap-and-Stack

prices = [2, 4, 1]
k = 2

def maxProfit(k, prices):
    if not prices:
        return 0

    n = len(prices)
    t = [0]*n

    for i in range(k):
        maxDiff = -prices[0]
        for j in range(1, n):
            tj_prev = t[j]
            t[j] = max(t[j-1], prices[j] + maxDiff)
            maxDiff = max(maxDiff, tj_prev - prices[j])

    return t[-1]

maxProfit(k, prices)
[3]:
2

121. I

Easy

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example:

Input: [7,1,5,3,6,4]
Output: 5
[4]:
from math import inf

prices = [7, 1, 5, 3, 6, 4]

def maxProfit(prices):
    curMin = inf
    curMaxProfit = 0
    for price in prices:
        curMin = min(curMin, price)
        curMaxProfit = max(curMaxProfit, price - curMin)

    return curMaxProfit

def maxProfit_(prices):
    '''Can use solution of 53 because profit is sum of daily profits from consecutive days'''

    import numpy as np
    return max(0, maxSubArray(np.diff(prices))) if len(prices)>1 else 0

maxProfit(prices)
[4]:
5

123. III

Hard

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

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

Example:

Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
[1]:
# 分拆兩半丟 121 再加起來的解答

prices = [7, 1, 5, 3, 6, 4]

def maxProfit(prices):
    n = len(prices)

    # pass 1
    runningMax1 = [0]*n
    currentMin = [0]*n
    if n > 0:
        currentMin[0] = prices[0]
        for i, p in zip(range(1, n), prices[1:]):
            runningMax1[i] = max(p-currentMin[i-1], runningMax1[i-1])
            currentMin[i] = min(currentMin[i-1], p)

    # pass 2
    prices = [-p for p in prices[::-1]]
    runningMax2 = [0]*n
    currentMin = [0]*n
    if n > 0:
        currentMin[0] = prices[0]
        for i, p in zip(range(1, n), prices[1:]):
            runningMax2[i] = max(p-currentMin[i-1], runningMax2[i-1])
            currentMin[i] = min(currentMin[i-1], p)

    runningMax1 = [0] + runningMax1
    runningMax2 = runningMax2[::-1] + [0]

    return max(m1+m2 for m1, m2 in zip(runningMax1, runningMax2))

maxProfit(prices)
[1]:
7

309. With Cooldown

Medium

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
[12]:
prices = [8, 6, 4, 3, 3, 2, 3, 5, 8, 3, 8, 2, 6]

def maxProfit(prices):
    n = len(prices)
    if n < 2:
        return 0
    else:
        h = [0]*n
        u = [0]*n

        h[:2] = [-prices[0], max(-prices[0], -prices[1])]
        u[1] = max(h[0] + prices[1], u[0])

        for i, p in zip(range(2, n), prices[2:]):
            h[i], u[i] = max(u[i-2] - p, h[i-1]), max(h[i-1] + p, u[i-1])

        return u[n-1]

maxProfit(prices)
[12]:
10

122. II

Easy

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. 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 at the same time (i.e., you must sell the stock before you buy again).

Example:

Input: [7,1,5,3,6,4]
Output: 7
[7]:
prices = [7, 1, 5, 3, 6, 4]

def maxProfit2(prices):
    import numpy as np
    diff = np.diff(prices)
    return diff[np.where(diff > 0)].sum()

maxProfit2(prices)
[7]:
7

714. With Transaction Fee

Medium

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
[4]:
prices = [8, 6, 4, 3, 3, 2, 3, 5, 8, 3, 8, 2, 6]
fee = 3

def maxProfit(prices, fee):
    n = len(prices)
    if n < 2:
        return 0
    else:
        h = [0]*n
        u = [0]*n
        h[0] = -prices[0]

        for i, p in zip(range(1, n), prices[1:]):
            h[i], u[i] = max(u[i-1] - p, h[i-1]), max(h[i-1] + p - fee, u[i-1])

        return u[n-1]

maxProfit(prices, fee)
[4]:
6