leetcode 买卖股票的最佳时机 II

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值