LeetCode 刷题【122. 买卖股票的最佳时机 II】
122. 买卖股票的最佳时机 II
自己做
解:一次遍历
class Solution {public int maxProfit(int[] prices) {int max = 0; //结果int profit = 0; //当前利润int min_price = prices[0]; //历史低点for(int i = 1; i < prices.length; i++){if(prices[i] < min_price) //更新最低点min_price = prices[i];if(prices[i] - min_price > profit){ //当前利润在上涨,记录当前利润profit = prices[i] - min_price;if(i == prices.length - 1) //一直涨到最后,抛max += profit;}else{ //当前利润出现下降,抛出max += profit;profit = 0; //重置利润min_price = prices[i]; //重置最低点}}return max;}
}