0w1

HR Vertical Sticks ( Expectation )

https://www.hackerrank.com/challenges/vertical-sticks
I really consider this one quite tough. It took me literally an hour to understand how someone else's idea worked.
algorithm - How to approach Vertical Sticks challenge? - Stack Overflow
First we know that we have to calculate the contribution of each individual stick, in order to pass in time. According to what Henry has suggested, for each stick, minding only the expected distance before it that contributes, we should know how many sticks are there that might have affect on. The ones that will make difference are those with equal or greater height. Let the number of such sticks be K. Then we can ignore all other shorter sticks, and consider a new problem: "K + 1 sticks are assigned to different spots in [ 1, N ], what is the expected distance between one and another?", the answer will be the average length of gap, which is ( N + 1 ) / ( K + 2 ). Sum them all will do.

void solve(){
    int N; cin >> N;
    vi Y( N );
    for( int i = 0; i < N; ++i )
        cin >> Y[ i ];
    double ans = 0;
    vi higher_cnt( N );
    for( int i = 0; i < N; ++i )
        for( int j = 0; j < N; ++j )
            if( Y[ i ] <= Y[ j ] )
                ++higher_cnt[ i ];
    for( int i = 0; i < N; ++i )
        ans += 1.0 * ( N + 1 ) / ( higher_cnt[ i ] + 1 );
    cout << fixed << setprecision( 2 ) << ans << "\n";
}