zoukankan      html  css  js  c++  java
  • 【LeetCode】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.

    code : 朴素的算法,对每一个i ,计算 最大 的 prices[j] (j>i) 来维护最大的差值,但是这样的复杂度是O(n^2),会TLE 

    考虑下面的O(n)算法:

     

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            int maxsum = 0;
            if(prices.size() <= 1)
                return 0;
                
            int maxPrice = prices.back();
            for(int i = prices.size()-1; i >= 0; i--)
            {
                maxPrice = max(maxPrice,prices[i]);
                maxsum = max(maxsum,maxPrice-prices[i]);
            }
            return maxsum ;
            
        }
    };


  • 相关阅读:
    VERSIONINFO Resource
    WCF 学习文摘
    hook 学习
    COM 学习
    ActiveX开发
    Word 开发资料集合
    Loops with PL/SQL
    TWain 在 Qt4 中的调用方法
    从 TWAIN 设备中扫描图像
    Qt enum使用总结
  • 原文地址:https://www.cnblogs.com/pangblog/p/3359984.html
Copyright © 2011-2022 走看看