Skip to content

Commit f2581b3

Browse files
author
programmerhjh
committed
日常水题(腾讯秋招50道)
1 parent 2a0ae73 commit f2581b3

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package myleetcode;
2+
3+
/**
4+
* 买卖股票的最佳时机
5+
* @author acer
6+
*
7+
*/
8+
public class BestTimeToBuyAndSellStock {
9+
10+
public int maxProfit(int[] prices) {
11+
int minprice = Integer.MAX_VALUE;
12+
int maxprofit = 0;
13+
for (int i = 0; i < prices.length; i++) {
14+
if (prices[i] < minprice)
15+
minprice = prices[i];
16+
else if (prices[i] - minprice > maxprofit)
17+
maxprofit = prices[i] - minprice;
18+
}
19+
return maxprofit;
20+
}
21+
22+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package myleetcode;
2+
3+
/**
4+
* 买卖股票的最佳时机 II
5+
* @author acer
6+
*
7+
*/
8+
public class BestTimeToBuyAndSellStockII {
9+
10+
public int maxProfit(int[] prices) {
11+
if (prices.length == 0) {
12+
return 0;
13+
}
14+
int i = 0;
15+
int valley = prices[0];
16+
int peak = prices[0];
17+
int maxprofit = 0;
18+
while (i < prices.length - 1) {
19+
while (i < prices.length - 1 && prices[i] >= prices[i + 1])
20+
i++;
21+
valley = prices[i];
22+
while (i < prices.length - 1 && prices[i] <= prices[i + 1])
23+
i++;
24+
peak = prices[i];
25+
maxprofit += peak - valley;
26+
}
27+
return maxprofit;
28+
}
29+
}

0 commit comments

Comments
 (0)