题目
LeetCode 122. Best Time to Buy and Sell Stock II
思路
- 要求尽可能多的完成交易
- 要求不能同时多笔交易
- 所以判断每笔交易能不能赚钱(即 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) { if(prices == null || prices.length <= 1) { return 0; } int totalProfit = 0; int profit = 0; for (int i = 0; i < prices.length - 1; i++) { profit = prices[i + 1] - prices[i]; if (profit > 0) { totalProfit += profit; } } return totalProfit; } }
|