LeetCode Best Time to Buy and Sell Stock

来源:互联网 发布:sql server2000 sp3 编辑:程序博客网 时间:2024/05/29 15:06

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.


i从小到大时,保存 <i 的最小的数,同时记录最大profit;

i从大到小时,保存 >i 的最大的数,同时记录最大profit。


class Solution {public:int maxProfit(vector<int> &prices) {if (prices.size() == 0)return 0;int min = prices[0], res = 0;for (unsigned i = 1; i < prices.size(); i++) {res = prices[i] - min > res ? prices[i] - min : res;min = prices[i] < min ? prices[i] : min;}return res;}};


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

 

0 0