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;
        }
    };
  • 相关阅读:
    地图篇-02.地理编码
    地图篇-01.获取用户位置
    新手教程之使用Xib自定义UITableViewCell
    封装
    NSDate简单介绍
    OC知识点归纳
    Xcode的控制台调试命令
    [开发笔记]UIApplication介绍
    技术分享-开发利器block底层实现
    技术分享-开发利器block
  • 原文地址:https://www.cnblogs.com/vercont/p/10210292.html
Copyright © 2011-2022 走看看