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.
假如你有一个数组,数组中的第 i 个元素代表了给定的股票在第 i 天的股价
如果你只被允许完成一次交易(例如:买进并卖出一次股票),设计一种算法来获得最大收益
注意你不能在你买之前卖一只股票
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
股票的买进卖出貌似是leetcode动态规划中非常经典的问题,这个应该是是最简单的版本。
从目前的理解来看,动态规划的核心是找到最优子结构,构造状态转移方程,说的直白一些应该是一个复杂问题的最优解可以分解成多个简单子问题的最优解,我们通过将简单子问题解决并记住子问题的解,最终汇总,得到复杂问题的最优解。
所以下面的解决方法是遍历数组,迭代更新最优利润,并返回。
Solutions:
Python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
max_pro = -1
low_pri = prices[0]
for i in range(1,len(prices)):
low_pri = min(prices[i],low_pri)
max_pro = max(prices[i]-low_pri,max_pro)
return max_pro
关于动态规划看了一些博客,有一些启发:
算法-动态规划 Dynamic Programming--从菜鸟到老鸟:https://blog.csdn.net/u013309870/article/details/75193592
进一步理解动态规划:https://www.jianshu.com/p/69669c7bd69e