【算法刷题】LeetCode 121.股票买卖

版权声明:本文为博主原创文章,如需转载,请注明出处: https://blog.csdn.net/MASILEJFOAISEGJIAE/article/details/89810009

题目描述

给定一个数组,存储了一只股票每一天的价格,假定只能进行一次买卖,求最高收益。

Example 1:

Input: [7,1,5,3,6,4]
Output: 5 (收益= 6-1 = 5)

Example 2:

Input: [7,6,4,3,1]
Output: 0 (因为无论怎么买都会赔钱,所以收益为0)

解题思路

大家都能想到,用两重循环的暴力解法,时间复杂度为 O ( n 2 ) O(n^2)

还有一种复杂度为 O ( n ) O(n) 的解法,只需要一次循环
用Windows自带的画图工具画了个股票价格示意图:

一次循环,从左到右,记录当前已知的最低处的位置minIdx,以及当前波峰最大的高度差maxProfit,若发现新的最低处,则更新minIdx,计算新的高度差,若新的高度差比maxProfit大,则更新maxProfit。例如,图中h2>h1,则最大的高度差从原先的h1更新为h2。

#include<vector>
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int minIdx = 0;
        int maxProfit = 0;
        
        //先要找到第一个最低处
        for(int i = 1; i < n; i++)
        {
            if(prices[i]<prices[minIdx])
            {
                minIdx = i; //如果还有更低处,更新minIdx
            }
            else    //不是最低处
            {
                int profit = prices[i] - prices[minIdx];
                maxProfit = profit > maxProfit ? profit : maxProfit;
            }
        }
        return maxProfit;
    }
};

LeetCode链接:LeetCode 121. Best Time to Buy and Sell Stock

猜你喜欢

转载自blog.csdn.net/MASILEJFOAISEGJIAE/article/details/89810009