Best Time to Buy and Sell Stock

来源:互联网 发布:2017年公务员网络培训 编辑:程序博客网 时间:2024/06/06 01:10

Say you have an array for which the ith element is the price of a given stock on dayi.

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.


Solution:

class Solution {public:    int maxProfit(vector<int>& prices) {        int len = prices.size();        if(!len) return 0;        int index = 0, maxprofit = 0;        for(int i = 0; i < len; ++i)        {            if(prices[i] < prices[index]) index = i;            if(prices[i] - prices[index] > maxprofit)            {                maxprofit = prices[i] - prices[index];            }        }        return maxprofit;    }};


0 0