Best Time to Buy and Sell Stockを解く[morning leetcode #2]
Best Time to Buy and Sell Stockを解く
morning leetcodeとは
基礎力向上のため、毎朝30分LeetCodeを解く。
目標: 3ヶ月でBlind 75完走
(朝起きれたら)
学習記録: GitHub - morning-leetcode
問題
121. Best Time to Buy and Sell Stock
株価の配列 prices が与えられる。prices[i] は i 日目の株価。
利益を最大化するために、ある1日を選んで株を買い、それより後の別の日に売る。
最大利益を返せ。利益が出ない場合は 0 を返す。
例:
-
prices = [7,1,5,3,6,4]→5(1日目に買い、4日目に売る: 6 - 1 = 5) -
prices = [7,6,4,3,1]→0(利益が出ない)
最初の考え
素直に行くと、i日目に買って、i+1日目, i+2日目...と愚直に利益を出して最大値を更新していく感じ?
2重ループで全組み合わせを試す。
当然TLEになった。
def maxProfit(prices: list[int]) -> int:
profit = 0
for i in range(len(prices)):
for j in range(len(prices)):
if i == j:
continue
if i > j:
continue
current_profit = prices[j] - prices[i]
if profit < current_profit:
profit = current_profit
return profit
AIに分析・フィードバックをもらう
AIの回答:
「ある日に売ると決めたとき、利益を最大化するにはその日までの最安値で買えばいい」
「配列を左から走査しながら、今まで見た中での最安値を1つの変数で記録し続ける」
「各日についてprices[i] - min_buy_priceが、その日に売った場合の最大利益」
走査しながら変数で最安値を追跡すれば、
ハマったポイント
min_buy_price の初期値を 0 にしてしまった。
株価はどれも0より大きいので、一度も更新されない。
prices[0] か float("inf") にする必要がある。
min() を毎回呼べばよくない?
min(prices[:i]) みたいにすると、毎回スライスして最小値を探すから結局
走査しながら変数1つで更新していくのがポイント。
改善後のコード
def maxProfit(prices: list[int]) -> int:
min_buy_price = prices[0]
max_profit = 0
for i in range(len(prices)):
current_stock_price = prices[i]
if current_stock_price < min_buy_price:
min_buy_price = current_stock_price
current_profit = current_stock_price - min_buy_price
if current_profit > max_profit:
max_profit = current_profit
return max_profit
1パス解法。走査しながら「今までの最安値」を変数で追跡。
Sliding Windowでも書いてみた
def maxProfit(prices: list[int]) -> int:
profit = 0
left_buy_index = 0
right_sell_index = 1
while right_sell_index < len(prices):
if prices[left_buy_index] > prices[right_sell_index]:
left_buy_index = right_sell_index
current_profit = prices[right_sell_index] - prices[left_buy_index]
if current_profit > profit:
profit = current_profit
right_sell_index += 1
return profit
One Passと本質的には同じ。
ただ「左端(買い)と右端(売り)の区間」というフレームワークで捉えている。
right を伸ばして新しい候補を調べ、left を動かしてより良い起点に切り替える。
学んだこと
- 過去を毎回探し直さない、走査しながら記録する
「今の要素に対して、過去の最適な値を参照したい」なら、変数やハッシュマップで追跡する。
Two Sumではハッシュマップ、この問題では変数1つ。
道具は違うけど、やってることは同じ。
- 共通パターン: 2重ループの内側を、過去の記録で置き換える
「内側のループって、毎回同じことを探し直してない?」と気づけるかどうか。
Discussion