-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxRandomInt.java
38 lines (27 loc) · 1005 Bytes
/
MaxRandomInt.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
/**
Given an array of integers arr, randomly return an index of the maximum value seen by far.
Example:
Input: [11, 30, 2, 30, 30, 30, 6, 2, 62, 62]
Having iterated up to the at element index 5 (where the last 30 is), randomly give an index among [1, 3, 4, 5] which are indices of 30 - the max value by far. Each index should have a ¼ chance to get picked.
**/
// O(1) space
public void maxRandomIndex(int[] nums) {
Random random = new Random();
int max = Integer.MIN_VALUE;
int maxIndex = -1;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
maxIndex = i;
count = 1;
} else if (nums[i] == max) {
count++;
// probability of 1/count . throw a dice and see if it match to choose this index so if in future asked max index its a fair chance to get any of the visited max value index/
if (random.nextInt(count) == 0) {
maxIndex = i;
}
}
System.out.print(maxIndex + " ");
}
}