LeetCode:Best Time to Buy and Sell Stock

来源:互联网 发布:匡恩网络 知乎 编辑:程序博客网 时间:2024/06/03 22:52

题目描述: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.

中文意思:给定一个序列,找出最大差值(只允许后面数减去前面数),没有的话则为0

方法1:两层循环,直接对prices[j] - prices[i] (j > i, i = 0, 1, ..., pricesSize - 2)进行枚举,时间代价为O(n^2)

方法2:动态规划,转移方程为profit[i] = max(profit[i-1], prices[i] - min_price)。也就是说到第i项的时候,最大的利润要么为第i-1项获得的最大利润(意味着第i项不值得交换),​要么为把第i项交换掉,用前面最小的值。

方法2的代码(空间代价可以为常数,自己可以尝试下):

int maxProfit(int* prices, int pricesSize) {    int* profit = (int*)malloc(pricesSize * sizeof(int));    memset(profit, 0, pricesSize * sizeof(int));    int min_price = prices[0];    for (int i = 1;  i < pricesSize; ++i)    {        if (profit[i - 1] > prices[i] - min_price)        {            profit[i] = profit[i - 1];        }        else         {            profit[i] = prices[i] - min_price;        }        if (prices[i] < min_price)        {            min_price = prices[i];        }    }    int max_profit = 0;    for (int i = 0; i < pricesSize; ++i)    {        if (max_profit < profit[i])        {            max_profit = profit[i];        }    }        return max_profit;}


1 0
原创粉丝点击