6ms Java solution


  • 0
    F
    public class Solution {
        public int maxProfit(int[] prices) { 
            if(prices == null || prices.length == 0) return 0;
            if(prices.length == 1) return 0;
            if(prices.length ==2) return prices[1]-prices[0] >0 ? prices[1]-prices[0]: 0;
            ArrayList arrayList1 = new ArrayList();
            ArrayList arrayList2 = new ArrayList();
            int profit = 0;
            for(int i = 1; i<prices.length-1 ; i++){
                if (prices[i]-prices[i-1]<=0 && prices[i+1]-prices[i] >0){
                    arrayList1.add(prices[i]);
                }
                if (prices[i]-prices[i-1]>0 && prices[i+1]-prices[i] <=0){
                    arrayList2.add(prices[i]);
                }
            }
            if (prices[prices.length-2]-prices[prices.length-1]<0){
                arrayList2.add(prices[prices.length-1]);
            }
            if(prices[0]-prices[1]<0) {
                arrayList1.add(prices[0]);
            }
            for( int i = 0; i < arrayList1.size(); i++){
                int xx = (int) arrayList2.get(i);
                int yy = (int) arrayList1.get(i);
                profit += xx-yy;
            }
            return profit;
        }
    }

Log in to reply
 

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