Clear java O(1) space O(n) time code


  • 0
    L

    Clear code:

    public class Solution {
        public int maximumProduct(int[] nums) {
            if (nums.length == 3) {
                return nums[0] * nums[1] * nums[2];
            }
            // get biggest 4 positives and smallest 3 smallest negatives
            int[] positives = new int[4];
            int[] negatives = new int[3];
            for (int num : nums) {
                // replace smallest positive and sort
                positives[0] = num;
                Arrays.sort(positives);
                // replace biggest negative and sort
                negatives[2] = num;
                Arrays.sort(negatives);
            }
            return Math.max(positives[1] * positives[2] * positives[3],
                negatives[0] * negatives[1] * positives[3]);
        }
    }
    

Log in to reply
 

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