LeetCode:Best Time to Buy and Sell Stock

来源:互联网 发布:matlab table转为矩阵 编辑:程序博客网 时间:2024/06/04 23:26

题目描述:

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;}


0 0
原创粉丝点击