【LeetCode】关关刷题日记24-Leetcode 121. Best Time to Buy and Sell Stock

时间:2022-05-07
本文章向大家介绍【LeetCode】关关刷题日记24-Leetcode 121. Best Time to Buy and Sell Stock,主要内容包括关小刷刷题 24——Leetcode 121. Best Time to Buy and Sell Stock、题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关小刷刷题 24——Leetcode 121. 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.

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.

题目的意思是给定一个数组,各元素值代表当天的股价,要求最多进行一次交易:买一次股票,卖一次股票,求可以获得的最大收益。

思路

思路:题目的意思是求max(nums[j]-nums[i]),要求j>i。从头至尾遍历一次数组,不断对当前的最小值和当前的最大利润做更新。时间复杂度O(n).

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

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。