Fill up the freqarr vector from last to first . After m - 1 th position frequency of all type of tasks will be 0. Then at m - 2 th position only frequency of arr [ m - 1 ] type task will be increased by 1. Again , in m - 3 th position only frequency of type arr [ m - 2 ] task will be increased by 1 and so on .
vector < int > newvec ( m + 1 , 0 ) ; freqarr [ m - 1 ] = newvec ; for ( int i = m - 2 ; i >= 0 ; i -- ) { vector < int > nv ; nv = freqarr [ i + 1 ] ; nv [ arr [ i + 1 ] ] += 1 ; freqarr [ i ] = nv ; }