Towers

You are given n cubes in a certain order, and your task is to build towers using them. Whenever two cubes are one on top of the other, the upper cube must be smaller than the lower cube.

You must process the cubes in the given order. You can always either place the cube on top of an existing tower or begin a new tower. What is the minimum possible number of towers?

Example:

Input: n = 5, arr = {3, 8, 2, 1, 5}
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int towers(int nvector<int&arr)
{

    vector<intdp;
    for (int i = 0i < ni++)
    {
        int x = arr[i];

        auto it = upper_bound(dp.begin(),
                              dp.end(), x);
        if (it == dp.end())
            dp.push_back(x);
        else
            *it = x;
    }
    return dp.size();
}

int main()
{
    int n = 5;

    vector<intarr = {38215};
    cout << towers(narr<< "\n";

    return 0;
}


No comments:

Post a Comment