Leetcode_Dynamic_Programming --121. Best Time to Buy and Sell Stock [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.

假如你有一个数组,数组中的第 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值