/**
* 自己的代码
* Runtime: 1 ms, faster than 65.74%
* Memory Usage: 38.7 MB, less than 51.52%
*/
class Solution {
public int maxProfit(int[] prices) {
int res = 0, buy = Integer.MAX_VALUE; // buy也可以换成Integer buy = null;,用null表示还没有买,运行效果一模一样
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i] < prices[i + 1]) {
if (buy == Integer.MAX_VALUE) {
buy = prices[i];
}
} else if (buy != Integer.MAX_VALUE) {
res += prices[i] - buy;
buy = Integer.MAX_VALUE;
}
}
return buy == Integer.MAX_VALUE ? res : res + prices[prices.length - 1] - buy;
}
}
/**
* 和上一段几乎一样,只是上一段每次比较确定在prices[i]的操作,这一段确定在prices[i-1]的
* Runtime: 1 ms, faster than 65.74%
* Memory Usage: 39 MB, less than 31.73%
*/
class Solution {
public int maxProfit(int[] prices) {
int res = 0, buy = Integer.MAX_VALUE;
for (int i = 1; i < prices.length; i++) {
if (prices[i - 1] < prices[i] && buy == Integer.MAX_VALUE) {
buy = prices[i - 1];
} else if (prices[i - 1] > prices[i] && buy != Integer.MAX_VALUE) {
res += prices[i - 1] - buy;
buy = Integer.MAX_VALUE;
}
}
return buy == Integer.MAX_VALUE ? res : res + prices[prices.length - 1] - buy;
}
}