首页 > 代码库 > LeetCode:Best Time to Buy and Sell Stock

LeetCode:Best Time to Buy and Sell Stock

题目描述:

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.


思路:遍历数组,保存已经遍历过了的元素的最小值low。则在第i天卖出股票所能得到的最大收益为prices[i]-low,求出每天最大收益的最大值即可。


代码:

int maxProfit(vector<int> &prices)
{
    int length = prices.size();
    if(length == 0)
        return 0;
    int max_profit = 0;
    int low = prices[0];
    for(int i = 1;i < length;i++)
    {
        int temp = prices[i] - low;
        if(temp > max_profit)
            max_profit = temp;
        if(prices[i] < low)
            low = prices[i];
    }
    return max_profit;
}


LeetCode:Best Time to Buy and Sell Stock