best-time-to-buy-and-sell-stock

来源:互联网 发布:尤克里里谱制作软件 编辑:程序博客网 时间:2024/06/18 01:25

题目:

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.

程序:

class Solution {public:    int maxProfit(vector<int> &prices) {        int MaxProfit = 0,Min = prices[0];        for(int i=1;i<prices.size();i++)        {            if(prices[i]>Min)                MaxProfit = max(MaxProfit,prices[i]-Min);            else                Min = prices[i];        }        return MaxProfit;    }};