알고리즘/해결

LeetCode1464. Maximum Product of Two Elements in an Array

언클린 2020. 6. 5. 15:37
728x90

1. 문제(원본)

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

 

Example 1:

Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.

Example 2:

Input: nums = [1,5,4,5] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7] Output: 12

 

Constraints:

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3

2. 문제

임의의 배열에 (nums[i]-1)*(nums[j]-1) 의 최댓값을 반환하라

3. 나의 답

class Solution {
    func maxProduct(_ nums: [Int]) -> Int {
        let sortedArray = nums.sorted { $0 > $1 }
        return (sortedArray[0] - 1) * (sortedArray[1] - 1)
    }
}

4. 다른 유저의 답

#1

class Solution {

    func maxProduct(_ nums: [Int]) -> Int {

        let (min1, min2, max2, max1) = nums.reduce(into: (Int(Int.max), Int(Int.max), Int(Int.min), Int(Int.min)), {

            let a = $1 - 1

            if a < 0 {

                if a < $0.0 {

                    $0.1 = $0.0

                    $0.0 = a

                } else if a < $0.1 {

                    $0.1 = a

                }

            } else {

                if a > $0.3 {

                    $0.2 = $0.3

                    $0.3 = a

                } else if a > $0.2 {

                    $0.2 = a

                }

            }

        })

        return max((min1 < 0 && min2 < 0 ? min1 * min2 : 0), (max1 > 0 && max2 > 0 ? max1 * max2 : 0))

    }

}

5. 마무리

코드가 짧다고 무조건 좋은 코드는 아니라는 것을 알게 되었다. 다른 유저의 답변은 복잡하고 길었지만 처리 속도는 현처히 차이가 났다.

개발자로서는 짧은 코드가 해석도 쉽고 개발하기 쉬울지 몰라도 그것을 사용하는 유저들의 입장에서는 빠른 처리 속도 쪽을 선호할 것이다.

이번 문제에서 의외로 금방 끝나 무난하다라고 생각했지만 풀고나서는 많은 학습이 되었던 것 같다.

728x90