Friday, July 15, 2022

628. Maximum Product of Three Numbers

 一刷 07/2022

Version #1 Sorting

Time O(NlogN)

Space O(N) or O(NlogN) depending on the sorting algorithm

Runtime: 18 ms, faster than 23.65% of Java online submissions for Maximum Product of Three Numbers.
Memory Usage: 54.1 MB, less than 62.91% of Java online submissions for Maximum Product of Three Numbers.

class Solution {

    public int maximumProduct(int[] nums) {

        // if all negative / all positive / only 1 negative -> 3 largest

        Arrays.sort(nums);

        int lastIndex = nums.length - 1;

        if (nums[lastIndex] <= 0 || nums[1] >= 0) {

            return nums[lastIndex] * nums[lastIndex - 1] * nums[lastIndex - 2];

        }

        // - - - + + +

        return nums[lastIndex] * Math.max(nums[0] * nums[1], nums[lastIndex - 1] * nums[lastIndex - 2]);

    }

}

No comments:

Post a Comment