leetcode Best Time to Buy and Sell Stock

来源:互联网 发布:防骗大数据 编辑:程序博客网 时间:2024/05/22 13:08

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) {        if (prices.empty()) return 0;        int min = prices[0],profit = 0;                int len = prices.size();                for (int i =1 ;i!= len;++i)        {            if (min > prices[i])                min = prices[i];            else                profit = max(profit,prices[i] - min);        }                    return profit;    }};


0 0