JAVA easy concise AC O(n) solution


  • 0
    W
        public int maximumProduct(int[] nums) {
            int max1 = Integer.MIN_VALUE + 2;
            int max2 = Integer.MIN_VALUE + 1;
            int max3 = Integer.MIN_VALUE + 0;
            
            int min1 = Integer.MAX_VALUE - 2;
            int min2 = Integer.MAX_VALUE - 1;
            int min3 = Integer.MAX_VALUE - 0;
            
            for (int i : nums) {
                if (i > max1) {
                    max3 = max2;
                    max2 = max1;
                    max1 = i;
                } else if (i > max2) {
                    max3 = max2;
                    max2 = i;
                } else if (i > max3) {
                    max3 = i;
                }
                
                if (i < min1) {
                    min3 = min2;
                    min2 = min1;
                    min1 = i;
                } else if (i < min2) {
                    min3 = min2;
                    min2 = i;
                } else if (i < min3) {
                    min3 = i;
                }
            }
            return Math.max(max1 * max2 * max3, min1 * min2 * max1);
        }
    

  • 1
    B

    @wz366 why put +2, +1 and -2, -1 at the behind of each max and min? what are they be used for?


  • 0
    W

    @sanquanfeng To make sure max1 > max2 and max2 > max3


Log in to reply
 

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