728x90
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.
Example 1:
Input: nums = [5,6,2,7,4]
Output: 34
Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
Example 2:
Input: nums = [4,2,5,9,7,4,8]
Output: 64
Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
Constraints:
- 4 <= nums.length <= 104
- 1 <= nums[i] <= 104
나의 풀이
|
1
2
3
4
5
6
7
8
9
|
/**
* @param {number[]} nums
* @return {number}
*/
var maxProductDifference = function(nums) {
nums.sort((a,b)=> b-a)
return (nums[0] *nums[1]) - (nums[nums.length-1] *nums[nums.length-2])
};
|
cs |
문제를 풀며 느낀 점
- nums.sort(조건)을 통해서 nums배열을 내림차순 정렬하였고 앞부터 2개의 값을 곱한 값 - 뒤에서 2개의 값을 곱한 값을 한 값을 return 하였습니다.
728x90
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
| [프로그래머스] 최빈값 구하기 (0) | 2023.02.22 |
|---|---|
| [프로그래머스] 외계어 사전 (0) | 2023.02.19 |
| [프로그래머스] 문자열 계산하기 (0) | 2023.02.16 |
| [프로그래머스] 컨트롤 제트 (1) | 2023.02.16 |
| [프로그래머스] 잘라서 배열로 저장하기 (0) | 2023.02.16 |