代码随想录算法训练营第四十一天|122. 买卖股票的最佳时机 II
122. 买卖股票的最佳时机 II
public static int maxProfit(int[] prices) { // 买 如果后面的价格有比当前的价格大.反之不买 // 卖 如果后面的价格有比当前的价格小,反之不卖 int currentProfitMoney = 0; boolean flag = false; for (int i = 0; i < prices.length; i++) { if (i == prices.length - 1) { if (flag) { currentProfitMoney += prices[prices.length - 1]; } break; } if (!flag) { if (prices[i] < prices[i + 1]) { currentProfitMoney -= prices[i]; flag = true; } } if (flag) { if (prices[i] > prices[i + 1]) { currentProfitMoney += prices[i]; flag = false; } } } return currentProfitMoney; }