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 ;
            
        }
    };


  • 相关阅读:
    基于JavaMail开发邮件发送器工具类
    微服务架构
    图像识别
    Manacher
    左偏树
    虚树
    动态树(Link-Cut Tree)
    Splay
    扩展中国剩余定理(EXCRT)
    K-D树
  • 原文地址:https://www.cnblogs.com/pangblog/p/3359984.html
Copyright © 2011-2022 走看看