Share my greedy strategy


  • 0
    C
    //I will buy stock when the prices of stock in the local minimum value point, 
    //and sell my stock when the prices in the local maximum value point.
    //eg: prices : 1,2,3,2,1,2,3
    //my transaction process: day1 - buy, day3 - sell, day5 - buy, day6 - sell
    public int maxProfit(int[] prices) {
        int maxProfit = 0, currentMin = Integer.MAX_VALUE;
        boolean hasStock = false;
        for (int i = 0; i < prices.length; i++) {
        	if( (i == prices.length - 1 || prices[i] > prices[i + 1]) && hasStock){
    			maxProfit += prices[i] - currentMin;
    			hasStock = false;
    		}
    		if( i < prices.length - 1 && prices[i] < prices[i + 1] && !hasStock){
    			currentMin = prices[i];
    			hasStock = true;
    		}
    	}
        return maxProfit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.