#leetcode#Best Time to Buy and Sell Stock

来源:互联网 发布:美国协同办公软件 编辑:程序博客网 时间:2024/05/08 17:38

https://leetcode.com/problems/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.


首先想到的是扫两边, 先找到最大值, 然后找到最大值前面的最小值, 相减得到最大的profit,但是这样的话[4, 1, 2]就会返回0, 应该是1买进, 2卖出, 这样profit为1.

问题想的太简单了。

所以正确的brute force是对每一个元素,计算于其身后的所有可能的profit, 时间复杂度为O(n^2)。


DP思路还是借鉴了Code Ganker大神, 维护两个变量, local = 0, global = 0。 

local = Math.max(local + prices[i + 1] - prices[i], 0)   ......  局部变量如果走到某一节点处变为负数, 则最大利益交易有可能已经出现, 或者还在后面。

global = Math.max(global, local)

http://blog.csdn.net/linhuanmars/article/details/23162793


0 0