zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock

    Objective:

    Find out the lowest point to buy-in and find out the a following hightest point to sell-out. And the maximal profit is equivalent to the max difference between the highest point and lowest point.

    Before solving this problem, suggest referring to the "maximum subarray" first. Then you will get an idea how to set the pointer and how to store the "buy" and "sell" variables.

    class Solution {
        
    public:
        int maxProfit(vector<int> &prices) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if (prices.empty()) return 0;
            int cur = 0; // the pointer
            int buy = 0; // date to buy
            int sell = 0; // day to sell
            int maxProf = 0; // the maximum profit
            
            for(int i=1;i<prices.size();i++)
            {
                if(prices[i]<prices[cur])
                    cur = i;
                else if(prices[i]>prices[cur] && prices[i]-prices[cur]>maxProf)
                {
                    buy = cur;
                    sell = i;
                    maxProf = prices[i]-prices[cur];
                }
                
            }
            
            return maxProf;
        }
    };
  • 相关阅读:
    单表查询
    解读python中SocketServer源码
    C++实训(2.3)
    C++实训(2.2)
    C++实训(2.1)
    C++实训(1.3)
    C++实训(1.1)
    顺序表的实现,在vs2019上运行成功
    p243_5(3)
    自考新教材-p176_5(2)
  • 原文地址:https://www.cnblogs.com/winscoder/p/3373272.html
Copyright © 2011-2022 走看看