-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBestTimeToBuyAndSellStock.java
More file actions
63 lines (59 loc) · 2.25 KB
/
Copy pathBestTimeToBuyAndSellStock.java
File metadata and controls
63 lines (59 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* <p>给定一个数组 <code>prices</code> ,它的第 <code>i</code> 个元素 <code>prices[i]</code> 表示一支给定股票第 <code>i</code> 天的价格。</p>
*
* <p>你只能选择 <strong>某一天</strong> 买入这只股票,并选择在 <strong>未来的某一个不同的日子</strong> 卖出该股票。设计一个算法来计算你所能获取的最大利润。</p>
*
* <p>返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 <code>0</code> 。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>[7,1,5,3,6,4]
* <strong>输出:</strong>5
* <strong>解释:</strong>在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
* 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>prices = [7,6,4,3,1]
* <strong>输出:</strong>0
* <strong>解释:</strong>在这种情况下, 没有交易完成, 所以最大利润为 0。
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>1 <= prices.length <= 10<sup>5</sup></code></li>
* <li><code>0 <= prices[i] <= 10<sup>4</sup></code></li>
* </ul>
* <div><div>Related Topics</div><div><li>数组</li><li>动态规划</li></div></div><br><div><li>👍 2002</li><li>👎 0</li></div>
*/
package leetcode6;
public class BestTimeToBuyAndSellStock {
public static void main(String[] args) {
Solution solution = new BestTimeToBuyAndSellStock().new Solution();
}
/**
* 详细题解参考 {@link BestTimeToBuyAndSellStockIv}
*/
class Solution {
public int maxProfit(int[] prices) {
if (prices.length <= 1) {
return 0;
}
int[][] dp = new int[2][prices.length];
dp[1][0] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[1][i] = Math.max(dp[1][i - 1], -prices[i]);
dp[0][i] = Math.max(dp[0][i - 1], dp[1][i - 1] + prices[i]);
}
return dp[0][prices.length - 1];
}
}
}