My java dp


  • 0
    C
    public class Solution {
    public int maxProfit(int[] prices) {
        	if(prices.length == 0)
    		return 0;
    	int buy =prices[0];
    	int profit = 0;
    
    	for(int i=0;i<prices.length;i++)
    	{
    		profit = max(profit,prices[i] - buy);
    		//buy should go after profit 不然的话,没有买就卖了是不存在这种情况的
    		buy = min(buy,prices[i]);
    	}
    	return profit;
    }
    
    int max(int a,int b)
    {
    	return a>=b?a:b;
    }
    int min(int a,int b)
    {
    	return a<b?a:b;
    }
    

    }


Log in to reply
 

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