121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 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

In this case, no transaction is done, i.e. max profit = 0.

解:
找到已经遍历过的数值中的最小值,然后找到后面和这个值的差的最大值。然后找到差值的最大值。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        minprice =float('Inf')
        maxprofit = 0
        for i in range(len(prices)):
            minprice = min(minprice, prices[i])
            maxprofit = max(maxprofit, prices[i] - minprice)
        return maxprofit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最佳的时间买卖股票III问题也可以使用动态规划算法来解决。动态规划算法通过将问题拆分为子问题,并利用子问题的解来构建更大规模问题的解。 对于最佳的时间买卖股票III问题,我们可以使用动态规划来构建一个二维数组dp,其中dp[i][j]表示在第i天结束时,最多进行j次交易所能获得的最大利润。 我们可以使用两个状态数组buysell来表示第j次交易的买入和卖出价格。初始化buysell数组为负无穷大。 接下来,我们遍历股票价格列表,对于每一天的价格,我们更新buysell数组的值。具体更新方式如下: 1. 对于第j次交易的买入价格,我们可以选择继续保持之前的买入价格(buy[j])或者在第i天买入(prices[i] - dp[i-1][j-1])。 2. 对于第j次交易的卖出价格,我们可以选择继续保持之前的卖出价格(sell[j])或者在第i天卖出(prices[i] + buy[j])。 在更新完buysell数组后,我们更新dp[i][j]为当前的最大利润(即sell[j])。 最后,我们返回dp[-1][-1]作为最大利润。 下面是使用动态规划算法解决最佳的时间买卖股票III问题的代码示例(假设prices是股票价格的列表): ```python def maxProfit(prices): n = len(prices) k = 2 # 最多进行两次交易 dp = [[0] * (k+1) for _ in range(n)] buy = [-float('inf')] * (k+1) sell = [0] * (k+1) for i in range(n): for j in range(1, k+1): buy[j] = max(buy[j], dp[i-1][j-1] - prices[i]) sell[j] = max(sell[j], prices[i] + buy[j]) dp[i][j] = max(dp[i-1][j], sell[j]) return dp[-1][-1] ``` 这个算法的时间复杂度是O(nk),其中n是股票价格列表的长度,k是最多进行的交易次数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值