zoukankan      html  css  js  c++  java
  • best-time-to-buy-and-sell-stock leetcode C++

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

    C++

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if(prices.size() < 2) return 0;
            int maxPro = 0;
            int curMin = prices[0];
            for(int i =1; i < prices.size();i++){
                if (prices[i] < curMin) 
                    curMin = prices[i];
                else
                    maxPro = max(prices[i] - curMin,maxPro);
            }
            return maxPro;
        }
        
        int maxProfit4(vector<int> &prices) {
            if(prices.size() < 2) return 0;
            int maxPro = 0;
            int curMin = prices[0];
            for(int i =1; i < prices.size();i++){
                int cur = prices[i];
                if (cur < curMin) 
                    curMin = cur;
                else{
                    int curPro = cur - curMin;
                    if (curPro > maxPro)
                        maxPro = curPro;
                }
            }
            return maxPro;
        }
        
        int maxProfit2(vector<int> &prices) {
            if(prices.size() < 2) return 0;
            int maxPro = 0;
            int curMin = prices[0];
            for(int i =1; i < prices.size();i++){
                if (prices[i] < curMin) 
                    curMin = prices[i];
                else
                    if (prices[i] - curMin > maxPro)
                        maxPro = prices[i] - curMin;
            }
            return maxPro;
        }
    };
  • 相关阅读:
    蠢货之对闭包表的扩展
    蠢货之TaskCompletionSource 带事件的同步调用
    SQLSERVER新建存储过程模板
    缓存更新
    写给”源码爱好者“
    区块链-一个不神秘却总能骗人的东西
    graceful-upgrades-in-go
    谁也逃不过C++
    Go的问题
    面试
  • 原文地址:https://www.cnblogs.com/vercont/p/10210292.html
Copyright © 2011-2022 走看看