File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments