티스토리 뷰
Medium
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
- n == position.length
- 2 <= n <= 105
- 1 <= position[i] <= 109
- All integers in position are distinct.
- 2 <= m <= position.length
문제해석
지구 C-137 우주에서 Rick은 새로 발명한 바구니에 두 개의 공을 넣으면 특별한 형태의
자기력이 발생한다는 것을 발견했습니다. Rick은 n개의 빈 바구니를 가지고 있으며,
i번째 바구니는 position[i] 위치에 있습니다. Morty는 m개의 공을 가지고 있으며,
공들 사이의 최소 자기력이 최대가 되도록 공을 바구니에 분배해야 합니다.
Rick은 두 개의 다른 공이 x와 y 위치에 있을 때 자기력은 |x - y|라고 말했습니다.
정수 배열 position과 정수 m이 주어질 때, 요구되는 자기력을 반환하세요.
해결방법
- 처음 주어진 순서는 중요하지 않다.
- 1 ~ 주어진 배열의 max 값 중에 정답이 있다
- 일일히 하나씩 다 확인하기에는 시초발생
- 이진탐색으로 정답이 되는지 판단하자!!
풀이
더보기
import java.util.*;
class Solution {
public int maxDistance(int[] position, int m) {
Arrays.sort(position);
int max = 0;
for(int i=0; i<position.length; i++){
max = Math.max(max, position[i]);
}
int s = 1;
int e = max;
while(s <= e){
int mid = (s+e) / 2;
if(check(position, mid, m))
s = mid + 1;
else
e = mid - 1;
}
return e;
}
static boolean check(int[] arr, int force, int m){
int cnt = 1;
int tmp = arr[0];
for(int i=1; i<arr.length; i++){
if(arr[i] - tmp >= force){
cnt++;
tmp = arr[i];
}
if(cnt >= m) return true;
}
return false;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 2563 Count the Number of Fair Pairs - 이진탐색, 투포인터 (0) | 2024.11.13 |
---|---|
[LeetCode] 2070 Most Beautiful Item for Each Query - 이진탐색 (1) | 2024.11.12 |
[LeetCode] 2601 Prime Subtraction Operation (0) | 2024.11.11 |
[LeetCode] 1598 Crawler Log Folder (0) | 2024.07.10 |
LeetCode 1482 Minimum Number of Days to Make Bouquets (0) | 2024.06.19 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준 14890 경사로
- BFS
- 백준 경사로
- dp
- 스프링부트3
- 오블완
- 조합
- 바텀업
- 위상정렬
- 탑다운dp
- 백준
- 누적합
- #스프링부트 자바버전 오류
- 스프링부트3 자바 17 오류
- 투포인터
- 이진탐색
- 1482
- 백준 경사로 자바
- leetcode 1552
- sql
- 유니온파인드
- 스프링부트3 자바 버전
- 백준 14890
- 구현
- 탑다운
- 슬라이딩윈도우
- 스프링부트3 java 버전오류
- 티스토리챌린지
- dfs
- 백준 14890 자바
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함