From c6ae3884f6449f9f68e1e956a12ef0b23be8a3f1 Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Fri, 10 Sep 2021 14:32:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0121.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?.mdJava=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index daeb05a9..b08e4193 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -214,6 +214,26 @@ class Solution { } } ``` +```java +// 解法1 +class Solution { + public int maxProfit(int[] prices) { + if (prices == null || prices.length == 0) return 0; + int length = prices.length; + // dp[i][0]代表第i天持有股票的最大收益 + // dp[i][1]代表第i天不持有股票的最大收益 + int[][] dp = new int[length][2]; + int result = 0; + dp[0][0] = -prices[0]; + dp[0][1] = 0; + for (int i = 1; i < length; i++) { + dp[i][0] = Math.max(dp[i - 1][0], -prices[i]); + dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]); + } + return dp[length - 1][1]; + } +} +``` ``` java class Solution { // 动态规划解法