Algorithm to solve find max no at a time

前端 未结 5 1113
半阙折子戏
半阙折子戏 2021-01-19 05:13

Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. Th

5条回答
  •  执念已碎
    2021-01-19 05:22

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
    
    unsigned int n;
    cin >> n;
    vector > dinos(2*n); // 
    
    unsigned int i;
    for( i = 0; i < n; ++i )
    {
    cin >> dinos[ 2 * i ].first >> dinos[ 2 * i + 1 ].first;
    dinos[ 2 * i ].second = 1; // born
    dinos[ 2 * i + 1 ].second = 0; // died
    }
    
    sort( dinos.begin(), dinos.end()); // sorts by date first
    int ans = 0, balance = 0;
    
    for( i = 0; i < dinos.size(); ++i ) {
    if( dinos[ i ].second ) // someone's born
    {
    ++balance;
    ans = max( ans, balance ); // check for max
    } else
    --balance;
    }
    cout << ans << endl;
    return 0;
    }
    

提交回复
热议问题