力扣-10.13-122

在这里插入图片描述
在这里插入图片描述
方法一:(自己写的)

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if(prices.length==0 || prices.length==1) {
    
    
        	return 0;
        }
        int p=0,q=1,profit=0;
        while(q<prices.length) {
    
    
        	if(prices[p]>prices[q]) {
    
    
        		p=q;
        		q++;
        	}else {
    
    
        		while(q<prices.length-1 && prices[q+1]>prices[q]) {
    
    
        			q++;
        		}
        		profit+=prices[q]-prices[p];
        		p=q+1;
        		q=p+1;
        	}
        }
		return profit;
    }
}

方法二:
对于 [a, b, c, d],如果有 a <= b <= c <= d ,那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ,因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] > 0,那么就把 prices[i] - prices[i-1] 添加到收益中。

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int profit=0;
        for(int i=1;i<prices.length;i++) {
    
    
        	if(prices[i]>prices[i-1]) {
    
    
        		profit+=prices[i]-prices[i-1];
        	}
        }
        return profit;
    }
}

猜你喜欢

转载自blog.csdn.net/Desperate_gh/article/details/109046393