Best Time to Buy and Sell Stock

Say you have an array for which the ithelement 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.

这个问题挺有意思,刚开始想到了DP,和最大递增子列有点像 C[i] = max{0 < j < i C[j] + A[j] - A[i] } 最后max_profit = max{C[i], 0 <= i < n},这个算法的效率明显是O(n^2),即使将C[j]用数组B组织可以二分查找,平均情况下的复杂度也是O(nlog(n)).

看了别人的实现,有更简单的思路:假设在i处买入,那么 i+1~n的最大股价相对于i能获得最大的利润。只要从后往前,在计算最大利润的时候顺便存储最大价格,那么就是O(n)的复杂度了。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
     int max_profit = 0;
     int max_price = 0;
     for(int i = prices.size() -1; i >= 0; i--){
         if (prices[i] > max_price){
             max_price = prices[i];
         }
         if (max_price - prices[i] > max_profit){
             max_profit = max_price - prices[i];
         }
     }
     return max_profit;
    }
};

原文链接: https://www.cnblogs.com/kwill/archive/2013/02/28/2937703.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/79125

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午6:53
下一篇 2023年2月9日 下午6:53

相关推荐