Problem Link [:https://codeforces.com/contest/1249/problem/C2] I read the problem's editorial as well,but wasn't able to wrap my head around the logic. I can understand that we need to represent the number in base 3 and we need to replace any 2 present in the Base 3 representation,also I understand why we need the maximum position of 2, but why should we replace the maximum position of 2 with 0, why not 1 ?

The following part is taken from the editorial:

Let pos0 be the leftmost position of 0 to the right from pos2. We can add 3^pos0 and replace all digits from the position pos0−1 to the position 0 with 0.

Can somebody please help me understand the logic behind it. Thanks in advance.

2 -> 0 (requires adding 1)

2 -> 1 (requires adding 2)

We have to minimise the number. So adding 1 is optimal.

I wrote a comment about this: https://codeforces.com/blog/entry/70779#comment-553025