forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimumMovestoEqualArrayElementsII.java
63 lines (47 loc) · 1.22 KB
/
MinimumMovestoEqualArrayElementsII.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
// TC : O(nlogn)
// SC : O(1)
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
int medianEl = nums[len/2];
int count = 0;
for(int el: nums){
count += Math.abs(el-medianEl);
}
return count;
}
// TC : O(nlogn)
// SC : O(n)
public int minMoves2(int[] nums) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(); // MIN heap
int len = nums.length;
for(int i=0;i<nums.length;i++){
if(pq.size()<=len/2){
pq.offer(nums[i]);
} else if(nums[i] > pq.peek()){
pq.poll();
pq.offer(nums[i]);
}
}
int medianEl = pq.peek();
int count = 0;
for(int el: nums){
count += Math.abs(el-medianEl);
}
return count;
}
// 3rd Solution:
// TC: O(NLogN)
// SC: O(1)
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int i = 0, j = nums.length-1, moves = 0;
while(i < j) {
moves += (nums[j] - nums[i]);
i++;
j--;
}
return moves;
}
}