• 【leetcode】Best Time to Buy and Sell (easy)


    题目:

    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.

    说白了,就是找一组数字里最大差值,并且大数要在小数的后面。 因为只能做一次买卖操作。

    思路:从后向前记录最大的数和该最大数前面的最小数,不断更新最大差值。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if(prices.empty())
            {
                return 0;
            }
            int maxNum = prices.back();
            int minNum = prices.back();
            int maxprofit = 0;
            vector<int>::iterator it;
            for(it = prices.end() - 2; it >= prices.begin(); it--)
            {
                if(*it < minNum)
                {
                    minNum = *it;
                }
                else if(*it > maxNum)
                {
                    maxprofit = ((maxNum - minNum) > maxprofit) ? (maxNum - minNum) : maxprofit;
                    maxNum = *it;
                    minNum = *it;
                }
            }
            maxprofit = ((maxNum - minNum) > maxprofit) ? (maxNum - minNum) : maxprofit;
            return maxprofit;
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> vec;
        int n = s.maxProfit(vec);
    
        return 0;
    }
  • 相关阅读:
    Kali上安装VMwareplayerfull 16
    安全漏洞概述
    BlueZ Linux上的bluetoth
    以太帧、ip数据包、tcp数据报长度究竟怎么算?
    office misc
    检测车道线——5.霍夫变换 Hough Transform
    Kafka 总体调优
    MySQL 联合索引 和 单列索引 的区别
    odps数据库(一)
    AIRPWRA\AIRPWRB\AIRPWRC
  • 原文地址:https://www.cnblogs.com/dplearning/p/4110913.html
Copyright © 2020-2023  润新知