LeetCode - 121. Best Time to Buy and Sell Stock -思路详解

来源:互联网 发布:python 提取d盘文件名 编辑:程序博客网 时间:2024/06/04 00:40

原题

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.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

题目翻译

给定一组股票交易的价格序列,第i个表示第i天的价格。只允许一次交易。

题目分析

该题目采用动态规划思想解题。求得最大的增长即可。
即求,任意i到j的差值最大。


思路1

直接求第i天和第j天的差值。两层循环,时间复杂度O(n^2)。测试结果大数据集超时。

代码1

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

思路2

计算每一次增长,然后更新增长最大值。时间复杂度为O(n)
测试结果时间:4ms

代码2

int maxProfit(int* prices, int pricesSize) {    int maxProfit = 0;    int min = prices[0];    for(int i = 0;i < pricesSize; i++){        if(prices[i] > min){            maxProfit = (prices[i] - min)>maxProfit?prices[i] - min:maxProfit;        }else{            min = prices[i];        }    }    return maxProfit;}

思路3

采取动态规划思路。借鉴别人思路。本质和思路2相似。
初始情况,收益为0。买入价格为第一天。
每新来一个价格后,判断他是否大于前一天的价格。
1,如果大于前一天的价格。则计算收益,即当前价格减去买入价格。是否大于当前的收益。如果大于当前的收益,则更新。如果小于,则不处理。然后遍历下一天的价格。

2,如果小于买入价格,则将买入价格更新为该价格。接着遍历。

代码3

class Solution {public:    int maxProfit(vector<int>& prices) {        int len = prices.size();        if(len == 0){            return 0;        }        int max = 0;        int pri = prices[0];        for(int i = 0; i < len; i++){            if(prices[i] > pri){                //判断当前收益是否大于max                if(prices[i] - pri > max){                    max = prices[i] - pri;                 }            }else{                //记录最低买入                pri = prices[i];   //当前价格小于之前的买入价格,则更新买入价格。            }        }        return max;    }};
0 0
原创粉丝点击