Time complexity of Max counters
As per the instructions are given in MaxCounters-Codility,
You are given
N
counters, initially set to 0, and you have two possible operations on them:
increase(X)
− counterX
is increased by 1,
max counter
− all counters are set to the maximum value of any counter.
A non-empty array
A
ofM
integers is given. This array represents consecutive operations:
if
A[K] = X
, such that 1 ≤X
≤N
, then operationK
isincrease(X)
, ifA[K] = N + 1
then operationK
ismax counter
.
I have written this code
public int[] maxCount(int[]A,int N) {
int[] I = new int[N];
for (int i = 0; i < A.length; i++) {
try {
I[A[i] - 1]++;
} catch (Exception e) {
Arrays.sort(I);
Arrays.fill(I, I[I.length - 1]);
}
}
return I;
}
It gives correct answers for all test cases. Any Idea to do this with time complexity O(N). Its currently on O(N*M).
- 153
- 1
- 8