A border outpost has n sentry towers standing in a row, each with a current height. Certain towers are marked as command towers -- each command tower must be strictly taller than every immediate neighbor tower next to it in the row, so that its watch commander always has the clearest sightline. Heights may only be raised (never lowered), and raising any single tower by one unit costs exactly 1 unit of construction material.
Given the tower heights and the list of command tower positions, determine the minimum total units of material needed to raise towers so that every command tower ends up strictly taller than each of its immediate neighbors. If no amount of raising can achieve this (which happens when two command towers are directly next to each other, since neither can ever be simultaneously strictly taller than the other), report that it is impossible.
n, the number of sentry towers.n space-separated integers, the current height of each tower, indexed 0 to n-1 left to right.m, the number of command towers.m space-separated integers in strictly increasing order, the 0-indexed positions of the command towers (this line is empty when m is 0).A single integer: the minimum total units of height that must be added across all towers, or -1 if it is impossible.
Example 1
Input
5 3 1 4 1 5 2 1 3
Expected
9
Explanation
Towers are [3,1,4,1,5]; towers at positions 1 and 3 are command towers, and they are not adjacent to each other. Tower 1 (height 1) has neighbors with heights 3 and 4, so it must be raised to 5, costing 4. Tower 3 (height 1) has neighbors with heights 4 and 5, so it must be raised to 6, costing 5. Neither raise affects the other's neighbors, so the total cost is 4 + 5 = 9.
Example 2
Input
4 10 10 10 10 2 0 1
Expected
-1
Explanation
Command towers 0 and 1 are directly adjacent, so tower 0 would need to be strictly taller than tower 1 while tower 1 simultaneously needs to be strictly taller than tower 0 -- a contradiction that no amount of raising can resolve, so the answer is -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 →