It's wired. What's the problem with my O(n) algorithm in Java?


  • 0
    Z

    I do not know what is wrong, I think it is right, but the submission is not accepted by a large set. I don't think it has anything to do the size. Please help me.

    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length<2)
                return 0;
            int sum2=0;
            int i=1,H1=0,H2=0,E1=0,E2=0;
            
            for(i=1;i<prices.length;i++){
                if(prices[i]>prices[i-1]){
                    E2=i;
                    sum2+=prices[i]-prices[i-1];
                    if(prices[E2]-prices[H1]>prices[E1]-prices[H1]&&prices[E2]-prices[H1]>sum2){
                        E1=E2;
                    }
                    else if(prices[E1]-prices[H1]>sum2)
                        continue;
                    else{
                        H1=H2;
                        E1=E2;
                    }
                }
                else{
                    sum2=0;
                    H2=i;
                }
            }
            return prices[E1]-prices[H1];
        }
    }
    

Log in to reply
 

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