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 ≤ X ≤ N, then operation K is increase(X),if A[K] = N + 1 then operation K is max counter.
I spent about 10 minutes just to understand the question itself.(and this happens occasionally. Is it just me?) So on this questions you need to get int[]
of the counters.
int N
and int[] A
are given. N represents the number of counters and each counters increases by the operations that is executed by each element of A.
max counter
is the key.
Easy way is to put for loop to change all the counters to the maximum value of all the counters when A[K] = N + 1 but it causes timeout error of course. So I created prevMax
to reserve the max value everytime A[K] his N + 1 and when all the operation executed(end of the first for loop), counters that's less than prevMax
value is now that prevMax
value.
public static int[] solution(int N, int[] A) {
int[] answer = new int[N];
int max = 0;
int prevMax = 0;
for (int i : A) {
if (i <= N) {
// This line won't be effective until A[K] first his N + 1
answer[i - 1] = Math.max(prevMax, answer[i - 1]);
answer[i - 1]++;
max = Math.max(max, answer[i - 1]);
continue;
}
prevMax = max;
}
for (int i = 0; i < N; i++) {
if (answer[i] < prevMax) {
answer[i] = prevMax;
}
}
return answer;
}