201 / 201 个通过测试用例
状态:通过
执行用时:2 ms
内存消耗:37.4 MB
提交时间:6 月,3 周之前
class Solution {
public int maxProfit(int[] prices) {
//第一种情况升序 直接返回 最后一个坐标和0坐标的差
int asc = 1;
for(int i = 0; i < prices.length - 1; i++){
if(prices[i] < prices[i+1]){
asc++;
if(asc == prices.length) return prices[prices.length -1] - prices[0];
}
}
//第二种情况降序 直接返回0
int des = 1;
for(int i = 0; i < prices.length - 1; i++){
if(prices[i] > prices[i+1]){
des++;
if(des == prices.length) return 0;
}
}
//第三种情况
int buy = 0;//买入
boolean isBuy = false;
//int sell = 0;//卖出
int profit = 0;//利润
for(int i = 0; i < prices.length - 1; i++){
if(!isBuy && prices[i] < prices[i+1]){
buy = prices[i];//买入
isBuy = true;
if(i == prices.length - 2) profit += prices[i+1] -prices[i];
continue;
}
if(isBuy && prices[i] >= prices[i+1]){
profit += prices[i] - buy;//卖出并计算利润
buy = 0;
isBuy = false;
}else if (isBuy && prices[i] < prices[i+1]){
profit += prices[i] - buy;//卖出并计算利润
buy = prices[i];//同时买入
isBuy = true;
}
if(isBuy && i == prices.length - 2)profit += prices[i+1] - prices[i];
}
return profit;
}
}