Maximizing the Profit

  • + 0 comments

    still missing some test cases can anyone catch why ??

    static long calc(long a, long b, long c) {
        if(a == Integer.MIN_VALUE || b == Integer.MIN_VALUE || c == Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        return a * b * c;
    }
    
    static long maximumProfit(int[] a) {
        TreeSet<Long> lset = new TreeSet<Long>();
        TreeSet<Long> rset = new TreeSet<Long>();
        for(int i : a)
            rset.add((long)i);
    
        long max = Long.MIN_VALUE;
    
        for(int i = 0;i < a.length;i++) {
            rset.remove((long)a[i]);
            long res = Long.MIN_VALUE;
    
            if(lset.size() > 0 && rset.size() > 0) {
                long a1 = (lset.first() < (long)a[i]) ? lset.first() : Integer.MIN_VALUE;
                long a2 = (lset.lower((long)a[i]) == null) ? Integer.MIN_VALUE : lset.lower((long)a[i]);
                long c1 = (rset.higher((long)a[i]) == null) ? Integer.MIN_VALUE : rset.higher((long)a[i]);
                long c2 = (rset.last() > (long)a[i]) ? rset.last() : Integer.MIN_VALUE;
    
                res = Math.max(res, calc(a1, (long)a[i], c1));
                res = Math.max(res, calc(a2, (long)a[i], c1));
                res = Math.max(res, calc(a1, (long)a[i], c2));
                res = Math.max(res, calc(a2, (long)a[i], c2));
                //System.out.println("a[i] = " + a[i] + " res = " + res);
                if(res > max)
                    max = res;
            }
    
            lset.add((long)a[i]);
        }
    
        return max == Long.MIN_VALUE ? -1 : max;
    }