題目
原題頁面:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
題目型別:Array, Greedy
難度評價:Medium
類似題目:(M) Best Time to Buy and Sell Stock, (H) Best Time to Buy and Sell Stock III, (H) Best Time to Buy and Sell Stock IV
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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析
一開始還以為是找出序列中的最大值和最小值然後求差,這種錯誤的想法充分暴露了本人炒股屬於把錢往裡一丟就再也不管了的型別。其實這題體現的就是一個“低買高買”的貪婪思想,需要找到每一個遞增的子序列,從而使利潤最大化。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-best-time-to-buy-and-sell-stock-ii/
