Skip to content

Commit e1ffa74

Browse files
committed
✨ leetcode 第121题
1 parent 1c7403b commit e1ffa74

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.fuyd.other;
2+
3+
/**
4+
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
5+
*
6+
* 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
7+
*
8+
* 注意你不能在买入股票前卖出股票。
9+
*
10+
* 示例 1:
11+
*
12+
* 输入: [7,1,5,3,6,4]
13+
* 输出: 5
14+
* 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
15+
* 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
16+
* 示例 2:
17+
*
18+
* 输入: [7,6,4,3,1]
19+
* 输出: 0
20+
* 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
21+
*
22+
* 来源:力扣(LeetCode)
23+
* 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
24+
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
25+
*
26+
* @author fuyongde
27+
* @date 2020/2/18
28+
*/
29+
public class Solution121 {
30+
31+
/**
32+
* 暴力穷举
33+
* 时间复杂度:O(n²)
34+
* 空间复杂度:O(1)
35+
*/
36+
public int maxProfit(int[] prices) {
37+
int max = 0;
38+
for (int i = 0; i < prices.length; i++) {
39+
for (int j = i + 1; j < prices.length; j++) {
40+
if (prices[j] - prices[i] > 0) {
41+
max = Math.max(max, prices[j] - prices[i]);
42+
}
43+
}
44+
}
45+
return max;
46+
}
47+
48+
/**
49+
* 一次遍历,动态规划的思想
50+
* 先找到一个最小谷底的然后继续找最大的峰值,这期间如果找到比之前找到的谷底更小的值,那么就更换谷底的值,
51+
* 然后再找最高的峰值,然后比较差值是否比之前的大,如果大就替换不然就找类似的进行判断
52+
*
53+
* 时间复杂度:O(n²)
54+
* 空间复杂度:O(1)
55+
*/
56+
public int maxProfit2(int[] prices) {
57+
int max = 0, minprice = Integer.MAX_VALUE;
58+
for (int i = 0; i < prices.length; i++) {
59+
if (prices[i] < minprice) {
60+
minprice = prices[i];
61+
} else if (prices[i] - minprice > max) {
62+
max = prices[i] - minprice;
63+
}
64+
}
65+
return max;
66+
}
67+
}

0 commit comments

Comments
 (0)