当前位置:网站首页>[leetcode refers to the maximum profit of offer 63. Stock (medium)]

[leetcode refers to the maximum profit of offer 63. Stock (medium)]

2022-04-23 21:21:00 Minaldo7

subject :

Suppose you store the price of a stock in an array in chronological order , What's the maximum profit you can get from buying and selling this stock at one time ?

Example 1:

Input : [7,1,5,3,6,4]
Output : 5
explain : In the 2 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 6) Sell when , Maximum profit = 6-1 = 5 .
Note that profit cannot be 7-1 = 6, Because the selling price needs to be higher than the buying price .
Example 2:

Input : [7,6,4,3,1]
Output : 0
explain : under these circumstances , No deal is done , So the biggest profit is 0.

Limit :

0 <= The length of the array <= 10^5

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

class Solution {
    
    public int maxProfit(int[] prices) {
    
        if(prices == null || prices.length <= 1) {
    
            return 0;
        }
        int minInit = prices[0];
        int maxGet = 0;
        for(int i=1;i<prices.length;i++){
    
            maxGet = Math.max(maxGet, prices[i]-minInit);
            minInit = Math.min(minInit,prices[i]);
        }
        return maxGet;
    }
}

Execution results :

 Insert picture description here

Another solution :

class Solution {
    
    public int maxProfit(int[] prices) {
    
       if(prices == null || prices.length <= 1) {
    
            return 0;
        }
        int res = 0, min = prices[0];
        for(int i = 1; i < prices.length; i++) {
    
            if(prices[i] <= min) {
              
                //  Change the minimum buying price 
                min = prices[i];
            }else {
                             
                //  Change maximum profit 
                res = Math.max(res, prices[i] - min);
            }
        }
        return res;
    }
}

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479508.html