{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Best Time to Buy and Sell Stock"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
"
],
"text/plain": [
""
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import IPython; IPython.display.HTML('''''')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 188. IV\n",
"Hard\n",
"\n",
"Say you have an array for which the i-th element is the price of a given stock on day i.\n",
"\n",
"Design an algorithm to find the maximum profit. You may complete at most k transactions.\n",
"\n",
"Note:\n",
"You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n",
"\n",
" Example:\n",
"\n",
" Input: [2,4,1], k = 2\n",
" Output: 2\n",
" Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# DP 解答的一維陣列版本 https://www.youtube.com/watch?v=oDhu5uGq_ic \n",
"# 有比 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\n",
"\n",
"prices = [2, 4, 1]\n",
"k = 2\n",
"\n",
"def maxProfit(k, prices):\n",
" if not prices:\n",
" return 0\n",
"\n",
" n = len(prices)\n",
" t = [0]*n\n",
"\n",
" for i in range(k):\n",
" maxDiff = -prices[0]\n",
" for j in range(1, n):\n",
" tj_prev = t[j]\n",
" t[j] = max(t[j-1], prices[j] + maxDiff)\n",
" maxDiff = max(maxDiff, tj_prev - prices[j])\n",
"\n",
" return t[-1]\n",
"\n",
"maxProfit(k, prices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 121. I\n",
"Easy\n",
"\n",
"Say you have an array for which the ith element is the price of a given stock on day i.\n",
"\n",
"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.\n",
"\n",
"Note that you cannot sell a stock before you buy one.\n",
"\n",
" Example:\n",
" \n",
" Input: [7,1,5,3,6,4]\n",
" Output: 5\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from math import inf\n",
"\n",
"prices = [7, 1, 5, 3, 6, 4]\n",
"\n",
"def maxProfit(prices):\n",
" curMin = inf\n",
" curMaxProfit = 0\n",
" for price in prices:\n",
" curMin = min(curMin, price)\n",
" curMaxProfit = max(curMaxProfit, price - curMin)\n",
"\n",
" return curMaxProfit\n",
" \n",
"def maxProfit_(prices):\n",
" '''Can use solution of 53 because profit is sum of daily profits from consecutive days'''\n",
" \n",
" import numpy as np\n",
" return max(0, maxSubArray(np.diff(prices))) if len(prices)>1 else 0\n",
"\n",
"maxProfit(prices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 123. III\n",
"Hard\n",
"\n",
"Say you have an array for which the ith element is the price of a given stock on day i.\n",
"\n",
"Design an algorithm to find the maximum profit. You may complete at most two transactions.\n",
"\n",
"Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).\n",
"\n",
" \n",
"\n",
" Example:\n",
"\n",
" Input: prices = [3,3,5,0,0,3,1,4]\n",
" Output: 6\n",
" Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n",
" Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 分拆兩半丟 121 再加起來的解答\n",
"\n",
"prices = [7, 1, 5, 3, 6, 4]\n",
"\n",
"def maxProfit(prices):\n",
" n = len(prices)\n",
" \n",
" # pass 1\n",
" runningMax1 = [0]*n\n",
" currentMin = [0]*n\n",
" if n > 0:\n",
" currentMin[0] = prices[0]\n",
" for i, p in zip(range(1, n), prices[1:]):\n",
" runningMax1[i] = max(p-currentMin[i-1], runningMax1[i-1])\n",
" currentMin[i] = min(currentMin[i-1], p)\n",
"\n",
" # pass 2\n",
" prices = [-p for p in prices[::-1]]\n",
" runningMax2 = [0]*n\n",
" currentMin = [0]*n\n",
" if n > 0:\n",
" currentMin[0] = prices[0]\n",
" for i, p in zip(range(1, n), prices[1:]):\n",
" runningMax2[i] = max(p-currentMin[i-1], runningMax2[i-1])\n",
" currentMin[i] = min(currentMin[i-1], p)\n",
"\n",
" runningMax1 = [0] + runningMax1\n",
" runningMax2 = runningMax2[::-1] + [0]\n",
" \n",
" return max(m1+m2 for m1, m2 in zip(runningMax1, runningMax2))\n",
"\n",
"maxProfit(prices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 309. With Cooldown\n",
"Medium\n",
"\n",
"Say you have an array for which the ith element is the price of a given stock on day i.\n",
"\n",
"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:\n",
"\n",
"* You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n",
"* After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\n",
"\n",
"```\n",
"Example:\n",
"\n",
"Input: [1,2,3,0,2]\n",
"Output: 3 \n",
"Explanation: transactions = [buy, sell, cooldown, buy, sell]\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prices = [8, 6, 4, 3, 3, 2, 3, 5, 8, 3, 8, 2, 6]\n",
"\n",
"def maxProfit(prices):\n",
" n = len(prices)\n",
" if n < 2:\n",
" return 0\n",
" else:\n",
" h = [0]*n\n",
" u = [0]*n\n",
" \n",
" h[:2] = [-prices[0], max(-prices[0], -prices[1])]\n",
" u[1] = max(h[0] + prices[1], u[0])\n",
" \n",
" for i, p in zip(range(2, n), prices[2:]):\n",
" h[i], u[i] = max(u[i-2] - p, h[i-1]), max(h[i-1] + p, u[i-1])\n",
" \n",
" return u[n-1]\n",
"\n",
"maxProfit(prices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 122. II\n",
"Easy\n",
"\n",
"Say you have an array prices for which the ith element is the price of a given stock on day i.\n",
"\n",
"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).\n",
"\n",
"Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).\n",
"\n",
"\n",
" Example:\n",
" \n",
" Input: [7,1,5,3,6,4]\n",
" Output: 7\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prices = [7, 1, 5, 3, 6, 4]\n",
"\n",
"def maxProfit2(prices):\n",
" import numpy as np\n",
" diff = np.diff(prices)\n",
" return diff[np.where(diff > 0)].sum()\n",
"\n",
"maxProfit2(prices)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 714. With Transaction Fee\n",
"Medium\n",
"\n",
"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.\n",
"\n",
"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.)\n",
"\n",
"Return the maximum profit you can make.\n",
"\n",
" Example:\n",
" \n",
" Input: prices = [1, 3, 2, 8, 4, 9], fee = 2\n",
" Output: 8\n",
" Explanation: The maximum profit can be achieved by:\n",
" Buying at prices[0] = 1\n",
" Selling at prices[3] = 8\n",
" Buying at prices[4] = 4\n",
" Selling at prices[5] = 9\n",
" The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prices = [8, 6, 4, 3, 3, 2, 3, 5, 8, 3, 8, 2, 6]\n",
"fee = 3\n",
"\n",
"def maxProfit(prices, fee):\n",
" n = len(prices)\n",
" if n < 2:\n",
" return 0\n",
" else:\n",
" h = [0]*n\n",
" u = [0]*n\n",
" h[0] = -prices[0]\n",
"\n",
" for i, p in zip(range(1, n), prices[1:]):\n",
" h[i], u[i] = max(u[i-1] - p, h[i-1]), max(h[i-1] + p - fee, u[i-1])\n",
"\n",
" return u[n-1]\n",
"\n",
"maxProfit(prices, fee)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}