# leetcode 买卖股票的最佳时机 II

201 / 201 个通过测试用例

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]){
if(i == prices.length - 2) profit += prices[i+1] -prices[i];
continue;
}
if(isBuy  &&  prices[i] >= prices[i+1]){
profit += prices[i] - buy;//卖出并计算利润
}else if (isBuy &&  prices[i] < prices[i+1]){
profit += prices[i] - buy;//卖出并计算利润
}
if(isBuy && i == prices.length - 2)profit += prices[i+1] - prices[i];
}

return  profit;
}
}

05-09 418
06-04 118
07-02 938
05-15 247
06-10 565
04-19 7294
11-24 5502
07-01 183
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客