Skip to main content
Code Review

Return to Revisions

5 of 5
edited tags; edited tags
200_success
  • 145.5k
  • 22
  • 190
  • 479

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) − counter X is increased by 1,
  • max counter − all counters are set to the maximum value of any counter.

A non-empty array A of M integers is given. This array represents consecutive operations:

if A[K] = X, such that 1 ≤ XN, then operation K is increase(X), if A[K] = N + 1 then operation K is max 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).

RAN_0915
  • 153
  • 1
  • 8
lang-java

AltStyle によって変換されたページ (->オリジナル) /