当前位置:网站首页>The best time to climb a ladder & sell shares (notes of the runner)

The best time to climb a ladder & sell shares (notes of the runner)

2022-06-22 04:26:00 Just a garbage runner

Climbing a ladder

70. climb stairs - Power button (LeetCode)

image-20220620120848706

At first I was going to use recursion to solve the problem , Because this is actually a Fibonacci sequence .

The code is as follows

class Solution {
    
public:
    int climbStairs(int n) 
    {
    
        if(n == 1)
            return 1;
        if(n == 2)
        {
    
            return 2;
        }
        return climbStairs(n-1)+climbStairs(n-2);
    }
};

But I can't

image-20220620121505816

Scrolling array

So we can use the current rolling array to solve the problem

The code is as follows :

class Solution {
    
public:
    int climbStairs(int n) 
    {
    
        int p = 0, q = 0, r = 1;
        for (int i = 1; i <= n; ++i) 
        {
    
            p = q; 
            q = r; 
            r = p + q;
        }
        return r;
    }
};

The best time to buy and sell stocks

The best time to buy and sell stocks - Power button (LeetCode)

image-20220620155933307

The title means to give you an array , You can only subtract the previous array value from the latter value , Return the maximum value .

Violence law

The direct use time complexity is O(n2) The method code of is as follows . But timeout .

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

image-20220620155911961

Just go through

We will first minprices Assign a value to 105 because prices[i] The maximum value of 104

image-20220620170852493

class Solution {
    
public:
    int maxProfit(vector<int>& prices) 
    {
    
        int minprices = 1e5;// The maximum value is 1*10^5^
        int ret = 0;
        for(int i =0;i<prices.size();i++)
        {
    
            minprices = min(minprices,prices[i]);// Record the minimum value of each node 
            ret = max(ret,prices[i]-minprices);// Used to record the maximum value of each node minus the previous lowest value .
        }
        return ret;
    }
};

We only need to traverse this node once, because every time we walk through a node, we will judge whether it is smaller than the previous value , If you are young, write it down .

In this way, we can directly subtract the previous minimum value from the current position when subtracting, and we earn the most in this case .

Then compare with the maximum value we can earn recorded before, and we can get the maximum value we want through a traverse .

原网站

版权声明
本文为[Just a garbage runner]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220424306021.html