Skip to content

Commit 13dbcd3

Browse files
minimum moves to equal array elements
1 parent aa8b7cf commit 13dbcd3

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package easy;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
import java.util.Queue;
6+
7+
public class MinimumMovestoEqualArrayElements {
8+
9+
public static int minMoves(int[] nums) {
10+
Queue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>(){
11+
@Override
12+
public int compare(Integer o1, Integer o2) {
13+
if(o1 > o2) return 1;
14+
else if(o1 < o2) return -1;
15+
else return 0;
16+
}
17+
});//in ascending order
18+
19+
int max = Integer.MIN_VALUE;
20+
for(int i = 0; i < nums.length; i++){
21+
max = Math.max(max, nums[i]);
22+
heap.offer(nums[i]);
23+
}
24+
25+
int moves = 0;
26+
while(!heap.isEmpty()){
27+
//always increments two elements
28+
int one = heap.poll();
29+
int two = heap.poll();
30+
one++;
31+
two++;
32+
moves++;
33+
max = Math.max(max, Math.max(one, two));
34+
heap.offer(one);
35+
heap.offer(two);
36+
if(heap.peek() == max) break;
37+
}
38+
return moves;
39+
}
40+
41+
public static void main(String...args){
42+
int[] nums = new int[]{1,2,3};
43+
System.out.println(minMoves(nums));
44+
}
45+
46+
}

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# fishercoderLeetcode
22
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
33
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
4+
|453|[Minimum Moves to Equal Array Elementss](https://leetcode.com/contest/12/problems/minimum-moves-to-equal-array-elements/)|[Solution](../../blob/master/EASY/src/easy/MinimumMovestoEqualArrayElements.java)| O(n)|O(n) | Easy| BFS
45
|441|[Arranging Coins](https://leetcode.com/problems/arrange-coins/)|[Solution](../../blob/master/EASY/src/easy/ArrangingCoins.java)| O(n)|O(1) | Easy|
56
|419|[Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/)|[Solution](../../blob/master/MEDIUM/src/medium/BattleshipsinaBoard.java) | O(n^2) |O(1) | Medium| DFS
67
|417|[Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)|[Solution](../../blob/master/MEDIUM/src/medium/PacificAtlanticWaterFlow.java) | O(m*n*Max(m,n)) |O(m*n) | Medium| DFS

0 commit comments

Comments
 (0)