본문 바로가기
Algorithm/LeetCode

[LeetCode] 1913. Maximum Product Difference Between Two Pairs (java)

by sun_HY 2023. 12. 19.
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.

 

 

#배열  #정렬

 

 

 

(a*b) - (c *d) 의 값이 최대가 되는 경우를 찾는 문제

또 무지성으로 경우의수 다 찾으려고 하다가.. 정신을 차리고 조건을 봤다

값이 가장 크게 하려면 가장 큰 값에서 가장 작은 값을 빼면 되고, 다행히 음수가 없는 조건이라

정렬 후 가장 큰 값 2개를 곱하고 가장 작은 값 두개를 곱해서 빼면 끝

시간이랑 메모리 효율도.. 크게 나쁘진 않은 

 

 

class Solution {
    public int maxProductDifference(int[] nums) {
        int ans = 0;
        int len = nums.length;
        
        Arrays.sort(nums);
        ans = nums[len - 1] * nums[len - 2] - nums[0] * nums[1];
        return ans;
    }
}

 

 
728x90