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

48 篇文章 0 订阅
43 篇文章 0 订阅

原题

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值