LeetCode | Best Time to Buy and Sell Stock(股票购买和抛售问题)

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.

题目解析:

给一堆数据,找到两个数之差的最大值,大数要在小数之后。


方案一:

很直观的方法:每一个元素为起点,让后面的数于该数相减,保存最大值;这样循环n次即可。时间复杂度为O(n^2)。大数据超时。

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

方案二:

如果我们不仅位置最大值也维持一个最小的数呢?当我们从前向后遍历的时候,用min记录下i之前的最小的数据,那么以i为大数的差值为a[i]-min,然后判断是否要更新res。这样时间复杂度就降低了很多。

有两个思考点:

1、我们一般找数据是像后找,也难怪,这个题目大数必须要在小数的后面,这样就限制了我们的思维。但如果变换一下的话,以大数为结尾,找前面的小数,能行的通。

2、既然找的话,也免不了一个一个去比较。我们要找最小数,就像维持最大值res一样,维持一个最小数变量min。

总的来说,要有逆向思维,碰到这种找最值的问题,可以用变量来简化查找。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        if(n == 0 || n == 1)
            return 0;
        int res = 0;
        int min = prices[0];
        for(int i = 1;i < n;i++){
            if(prices[i] < min)
                min = prices[i];
            else{
                if(prices[i]-min > res)
                    res = prices[i]-min;
            }
        }
        return res;
    }
};


方案三:

如果再变换一下思路,我们从后向前便利呢?也同样维持一个max,当求以i为小数的时候,就用i+1...n中的最大值max-a[i]即可。

如果一个问题,不好思考的时候,尽量反向去考虑。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.size() == 0)
            return 0;
            
        int maxPrice = prices[prices.size()-1];
        int ans = 0;
        for(int i = prices.size() - 1; i >= 0; i--)
        {
            maxPrice = max(maxPrice, prices[i]);
            ans = max(ans, maxPrice - prices[i]);
        }
        
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值