0%

LeetCode 122. 买卖股票的最佳时机 ii

题目

LeetCode 122. Best Time to Buy and Sell Stock II

思路

  1. 要求尽可能多的完成交易
  2. 要求不能同时多笔交易
  3. 所以判断每笔交易能不能赚钱(即 arr[i + 1] - arr[i] > 0), 满足条件则发生交易即可

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int maxProfit(int[] prices) {
//validate param
if(prices == null || prices.length <= 1) {
return 0;
}

int totalProfit = 0;
int profit = 0;
//calculate profit between every day, if profit > 0, means you can complete one transaction.
for (int i = 0; i < prices.length - 1; i++) {
profit = prices[i + 1] - prices[i];
if (profit > 0) {
totalProfit += profit;
}
}
return totalProfit;
}
}