LEETCODE: Best Time to Buy and Sell Stock

来源:互联网 发布:监控视频显示无网络 编辑:程序博客网 时间:2024/06/08 14:24

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) {        vector<int> maxs(prices.size());        vector<int> mins(prices.size());                // Get min from left to right at what time we may buy.        for(int ii = 0; ii < prices.size(); ii ++) {            if(ii == 0) {                mins[ii] = prices[ii];            }            else {                mins[ii] = min(mins[ii - 1], prices[ii]);            }        }                // Get max from right to left at what time we may sell.        for(int ii = prices.size() - 1; ii >= 0; ii --) {            if(ii == prices.size() - 1) {                maxs[ii] = prices[ii];            }            else {                maxs[ii] = max(maxs[ii + 1], prices[ii]);            }        }                int maxgap = 0;        for(int ii = 0; ii < maxs.size(); ii ++) {            if(maxgap < maxs[ii] - mins[ii]) {                maxgap = maxs[ii] - mins[ii];            }        }                return maxgap;    }};



0 0
原创粉丝点击