[leetcode]: 121. Best Time to Buy and Sell Stock

来源:互联网 发布:python版本选择 编辑:程序博客网 时间:2024/06/04 00:43

1.题目

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.
给一段股票价格序列,只能买卖一次,求最大收益

2.分析

第一种:
找到子序列最大的价格差。
遍历价格序列:
持续更新最高价
如果发现最低价可以更新,则最高价,最低价同时更新,差值也更新。

int maxProfit(vector<int>& prices) {    if(prices.size()==0)        return 0;    int low = prices[0];    int high = prices[0];    int maxP = -1;    for (int i = 1; i < prices.size(); i++) {        if (prices[i] > high)            high = prices[i];        if(prices[i]<low){            maxP = maxP > (high - low) ? maxP : high - low;            low = prices[i];            high = prices[i];        }    }    maxP = maxP > (high - low) ? maxP : high - low;    return maxP;}

第二种:
看solution的解答提到了Kadane’s Algorithm。
提到了这样一种情况,如果给的不是价格序列,而是价格差序列怎么做?这个问题就转化为求连续子序列的最大和。
例如,
股票价格为{1, 7, 4, 11},判断为1买入,11卖出,profile=10
价格差序列{0, 6, -3, 7},判断为6-3+7=10,最大profile=10

int maxProfit(vector<int>& prices) {    if(prices.size()==0)        return 0;    int max_cur = 0;    int max_sofar = 0;    for (int i = 1; i < prices.size(); i++) {        max_cur = max(0, max_cur + prices[i] - prices[i - 1]);        max_sofar = max_sofar > max_cur ? max_sofar : max_cur;    }    return max_sofar;}
阅读全文
0 0