前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q121 Best Time to Buy and Sell Stock

Q121 Best Time to Buy and Sell Stock

作者头像
echobingo
发布2018-04-25 16:53:34
5170
发布2018-04-25 16:53:34
举报

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.
解题思路:

这题第一反应和最大子段和问题 Q53 Maximum Subarray 差不多,因此可以用动态规划求解。

用一个列表记录当前累积的最大利润。如果当前值比下一个值小,则用下一个值减去当前值作为最大利润,然后当前值下标不变,下一个值往后滑动一位继续比较。如果当前值比后面的某个值大,则最大利润置为0,当前值下标变为后面那个值的下标。一次遍历,返回利润列表中的最大值。时间复杂度为 O(n)。

Python实现:
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        li = [0]  # 当前累积的最大利润
        i = 0; j = 1
        while j < len(prices):
            if prices[i] >= prices[j]:
                li.append(0)
                i = j
            else:
                li.append(prices[j] - prices[i])
            j += 1
        return max(li)

a = [7,2,5,3,6,4,1,5,6,4,0]
b = Solution()
print(b.maxProfit(a)) # 5 # 1元的时候买入,6元的时候卖出
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档