LeetCode Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝做什么推广好 编辑:程序博客网 时间:2024/04/28 11:21

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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(prices.empty())            return 0;        int curr=prices[0],diff=0;        for(int i=1;i<prices.size();++i){            if(prices[i]<curr){                curr=prices[i];            }else{                diff=max(diff,prices[i]-curr);            }        }        return diff;    }};


原创粉丝点击