#include <cstddef>
#include <iostream>

template <std::size_t N>
int calc_volume(int const (&heights)[N])
{
    int const max_height = 9;
    
    int volume          = 0;
    int max_left_height = 0;
    int prev_height     = max_height;
    
    int tmp_volume[max_height + 1] = {};    
    
    for (int i = 0; i != N; ++i)
    {
        int const cur_height = heights[i];
        
        if (cur_height > max_height)
            return -1;

        for (int j = prev_height; j < cur_height; ++j)
        {
            volume += tmp_volume[j];
            tmp_volume[j] = 0;
        }

        for (int j = cur_height; j < max_left_height; ++j)
            ++tmp_volume[j];
            
        if (cur_height > max_left_height)
            max_left_height = cur_height;
    
        prev_height = cur_height;
    }
    
    return volume;
}

int main()
{
   int const heights1[] = { 2, 5, 1, 2, 3, 4, 7, 7, 6 }; // 10
   int const heights2[] = { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 }; // 17
   int const heights3[] = { 2, 5, 1, 3, 8, 2, 1, 7, 7, 6 }; // 17
   int const heights4[] = { 4, 3, 1, 5, 8, 0, 4, 0 ,0 , 5, 5, 7, 5, 8, 3, 3 }; // 42
   int const heights5[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // 0
   int const heights6[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; // 0
   int const heights7[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9 }; // 45
   int const heights8[] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1 }; // 1
   int const heights9[] = { 7, 1, 7, 2, 5 }; // 9
   
   int const vol = calc_volume(heights1);
   
   std::cout << "volume: " << vol;
   
   return 0;
}
