Get Mystery Box with random crypto!

2579. Count Total Number of Colored Cells Medium: 2579. Cou | LeetCodin

2579. Count Total Number of Colored Cells

Medium: 2579. Count Total Number of Colored Cells
My solution: Java 1 Line | Math | 100% Faster | Explained

Hi! Here is the one of possible solutions for the problem.

Task
Your task is to find the number of cells which you will have after n minutes by drawing touching cells.

Idea
If you pay attention and try drawing and counting cells, you will see that the number of colored cells is somehow connected to arithmetic progression sum.
The difference of each row is 2 (d = 2).

- I found out that the number of cells is the arithmetic progression sum for n plus arithmetic progression sum for n minus an or

Sum(n) + Sum(n) - an => 2 * Sum(n) - an. (a )

You know the first number [a1] of the arithmetic sequence [and it is 1].

If Sum(n) = ((a1 + an) * n ) / 2, then the formula (a ) above will be

2 * Sum(n) - an = 2 * ((a1 + an) * n ) / 2 - an = (a1 + an) * n - an. (b )

Now, let's find an. According to the formula an = a1 + (n - 1) * d and this will be
an = 1 + (n - 1) * 2 = 1 + 2n - 2 = 2n - 1 => an = 2n - 1.

Finally, we put an into the formula (b )
(a1 + an) * n - an = (a1 + 2 * n - 1) * n - (2 * n - 1) = 2 * n * n - 2 * n + 1 = 2 * n * (n - 1) + 1.

So, the solution is 2 * n * (n - 1) + 1.

Good luck!

@leetcodin