买卖股票的最佳时机 (Best Time to Buy and Sell Stock)

 

思路:

// @Title: 买卖股票的最佳时机 (Best Time to Buy and Sell Stock)
// @Author: qisiii
// @Date: 2024-09-22 17:42:54
// @Runtime: 2 ms
// @Memory: 60.3 MB
// @comment: 
// @flag: 
class Solution {
    public int maxProfit(int[] prices) {
        int min=prices[0],result=0;
        for(int i=1;i<prices.length;i++){
            if(prices[i]>=min){
                result=Math.max(result,prices[i]-min);
            }else{
                min=prices[i];
            }
        }
        return result;
    }
}

+++ title = “买卖股票的最佳时机 (Best Time to Buy and Sell Stock)” draft = false +++

思路:

// @Title: 买卖股票的最佳时机 (Best Time to Buy and Sell Stock)
// @Author: qisiii
// @Date: 2024-09-22 17:40:53
// @Runtime: 3 ms
// @Memory: 60.4 MB
// @comment: 
// @flag: 
class Solution {
    public int maxProfit(int[] prices) {
        int min=prices[0],result=0;
        for(int i=1;i<prices.length;i++){
            min=Math.min(min,prices[i]);
            if(prices[i]>=min){
                result=Math.max(result,prices[i]-min);
            }else{
                min=prices[i];
                result=0;
            }
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18