Notice
Recent Posts
Recent Comments
Link
오늘도 개발
25. Array Partition I 본문
문제
배열 nums의 요소를 두 개씩 묶고,
각 쌍에서 최소 요소를 하나씩 골라 모두 더했을 때,
나올 수 있는 가장 큰 수를 반환하시오.
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
내가 해결한 방식
[1, 4, 3, 2]인 경우 [1, 2, 3, 4]로 정렬해서 순서대로 두 개씩 묶었을 때 최대값이 나올 수 있다.
def arrayPartition(nums):
nums.sort()
result = 0
for i in range(0, len(nums), 2):
result += nums[i]
return result'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 27. Minimum Size Subarray Sum (0) | 2022.10.15 |
|---|---|
| 26. Two Sum II - Input array is sorted (1) | 2022.10.15 |
| 24. Reverse String (1) | 2022.10.14 |
| 23. Longest Common Prefix (0) | 2022.10.14 |
| 22. Find the Index of the First Occurrence in a String (0) | 2022.10.12 |