关关的刷题日记 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)。 同时请,关注我们的公众号,获取最新关于专知以及人工智能的资讯、技术、算法等内容。扫一扫下方关注我们的微信公众号。

图片

展开全文
相关主题
Top
微信扫码咨询专知VIP会员