Leetcode:72 Best Time to Buy and Sell Stock

来源:互联网 发布:中易广告联盟v9源码 编辑:程序博客网 时间:2024/06/08 06:32

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) {        int res = 0;        if(prices.empty())            return res;        int min = prices[0];        for(int i = 0; i < prices.size(); i++)        {            if(prices[i] < min)                min = prices[i];            if(prices[i] - min > res)                res = prices[i] - min;        }        return res;    }};


0 0
原创粉丝点击