Algorithm to solve find max no at a time

前端 未结 5 1153
半阙折子戏
半阙折子戏 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:37

    Consider each dinosaur birth as an open parenthesis and death as a close one. Then sort the parenthesis by date - this will give you chronological order of every event of birth and death. After that pass over the parenthesis sequence and compute the balance (increment on '(' and decrement on ')' ). Track the maximal balance and it will be the answer.

    Update:

    Sample source in C++.
    Input: number of dinosaurs n, then 2n dates of birth and death.
    Output: number of maximal quantity of dinos living at the same time

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        int n;
        cin >> n;
        vector > dinos(2*n); // 
        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;
    }
    

    P.S. I assumed that if two dinos born and died at the same time then they didn't live together. If you want the opposite, just change the values as born=0, died=1.

提交回复
热议问题