2021.09.28 - 095.买卖股票的最佳时机

1. 题目

在这里插入图片描述

2. 思路

(1) 动态规划

  • 假设在第i天卖出股票,那么只有在前i-1天中股价最低时买入股票才能获得最高的利润。

  • 变量min记录前i-1天中最低的股价,变量res记录曾经获得的最高利润。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int min = Integer.MAX_VALUE;
        int res = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
    
    
            min = Math.min(min, prices[i]);
            res = Math.max(res, prices[i] - min);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120526915