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.

题目的意思是所有天加起来只能最多买一次买一次

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int ret=0;
        if(prices.size()==0)return 0;
        int min=prices[0];
        for(int i=1;i<prices.size();i++){
            if(prices[i]>=min){
                if(prices[i]-min>ret){
                    ret=prices[i]-min;
                }
            }
            else{
                min=prices[i];
            }
        }
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/superzrx/p/3355316.html