The head gardener planted a long path of flower plots, and every plot holds exactly one species of flower, encoded as a species ID. To score how visually varied each section of the path is, the gardener looks at every contiguous stretch of plots (a single plot counts too, and so does the entire path), counts how many distinct species appear in that stretch, and squares the count. Add up these squared diversity scores across every possible contiguous stretch and report the grand total.
n, the number of plots along the path.n space-separated integers, the species ID planted in each plot, in path order.Print a single integer: the sum, over every contiguous stretch of plots, of the square of the number of distinct species in that stretch.
Example 1
Input
3 1 2 1
Expected
15
Explanation
The path has plots [1, 2, 1]. The six stretches and their squared diversities are: [1]->1, [1,2]->4, [1,2,1]->4, [2]->1, [2,1]->4, [1]->1. Summing gives 1+4+4+1+4+1 = 15.
Example 2
Input
1 4
Expected
1
Explanation
With a single plot, there is exactly one stretch (the whole path), containing one distinct species, so the total is 1^2 = 1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →