image.png

    • 要想要获得最大利润,必须保证局部最优,从局部考虑问题

      • 保证买入的是n天及之前的最小值(指获得利益最大所能够花费的最小代价)
      • 保证卖出的是n天及之前的最大值(指获得利益最大)

        • 需要变量min记录n天及之前能获得最大的利益的买入最小值(min不一定是最小值)
        • 需要遍历max记录n天及之前能获得最大的利益 ```java

        //暴力法 public int maxProfit(int prices[]) { int maxprofit = 0; for (int i = 0; i < prices.length - 1; i++) {

        1. for (int j = i + 1; j < prices.length; j++) {
        2. int profit = prices[j] - prices[i];
        3. if (profit > maxprofit) {
        4. maxprofit = profit;
        5. }
        6. }

        } return maxprofit; }

        public int maxProfit(int[] prices) { int len = prices.length; if (len <= 1) return 0; int max = 0, min = prices[0]; for (int i = 1; i < len; i++) {

            max = Math.max(max, prices[i] - min);
            min = Math.min(min, prices[i]);
        

        } return max; } ```

    买卖股票股票的最佳时机