Best Time to Buy and Sell Stock

来源:互联网 发布:主机屋空间绑域名 编辑:程序博客网 时间:2024/06/07 01:16

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.size()<=1) return 0;int max = prices[0],min = prices[0],r_min = prices[0];for(int i=1;i<prices.size();++i){    //当前值比最大的大,变更最大值if(prices[i]>max){max = prices[i];}//当前能取得的最大利润大,更新区间if((prices[i]-r_min)>(max-min)){                min = r_min;                max = prices[i];}//更新实际最小值            if(prices[i]< r_min){r_min = prices[i];}}        return max - min;    }};


0 0
原创粉丝点击