[JAVA] Find 3 max and 2 min / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public int maximumProduct(int[] nums) {
            int first = Integer.MIN_VALUE;
            int second = Integer.MIN_VALUE;
            int third = Integer.MIN_VALUE;
            
            int sfirst = Integer.MAX_VALUE;
            int sSecond = Integer.MAX_VALUE;
            
            for(int num : nums){
                if(first < num){
                    third = second;
                    second = first;
                    first = num;
                }
                else if(second < num){
                    third = second;
                    second = num;
                }
                else if(third < num){
                    third = num;
                }
                
                if(sfirst > num){
                    sSecond = sfirst;
                    sfirst = num;
                }
                else if(sSecond > num){
                    sSecond = num;
                }
            }
            
            return Math.max(first * second * third, first * sfirst * sSecond);
        }
    }
    

Log in to reply
 

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