Skip to content

Commit 66543d5

Browse files
author
王俊超
committed
commit
1 parent 7279a82 commit 66543d5

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-09 08:46
4+
**/
5+
public class Solution {
6+
public int maxProfit(int[] prices) {
7+
8+
if (prices == null || prices.length < 2) {
9+
return 0;
10+
}
11+
12+
int buy = 0;
13+
int sell = 1;
14+
15+
int sum = 0;
16+
while (sell < prices.length) {
17+
// 从buy的位置开始找降序子序列中最小的值
18+
while (buy + 1 < prices.length && prices[buy] >= prices[buy + 1]) {
19+
buy++;
20+
}
21+
// 从buy的位置开始找升序子序列中最大的值
22+
sell = buy + 1;
23+
while (sell + 1 < prices.length && prices[sell] <= prices[sell + 1]) {
24+
sell++;
25+
}
26+
27+
if (sell < prices.length) {
28+
sum += prices[sell] - prices[buy];
29+
}
30+
31+
buy = sell + 1;
32+
33+
}
34+
35+
return sum;
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-09 09:13
4+
**/
5+
public class Test {
6+
public static void main(String[] args) {
7+
Solution solution = new Solution();
8+
9+
int[] prices = {7, 1, 5, 3, 6, 4};
10+
System.out.println(solution.maxProfit(prices) == 7);
11+
12+
int[] prices2 = {1, 2, 3, 4, 5};
13+
System.out.println(solution.maxProfit(prices2) == 4);
14+
15+
int[] prices3 = {7, 6, 4, 3, 1};
16+
System.out.println(solution.maxProfit(prices3) == 0);
17+
}
18+
}

0 commit comments

Comments
 (0)