Array balancing

What is the best way to solve this problem? The balancing point of the array of N-elements A is an index i in such a way that all elements of lower indices have values ​​<= A [i], and all elements of higher indices have values ​​higher or equal to A [i].

For example, given:

A [0] = 4 A [1] = 2 A [2] = 7 A [3] = 11 A [4] = 9

one of the correct solutions: 2. All elements below A [2] are less than A [2], all elements after A [2] are larger than A [2]. One solution that I thought was O (nsquare) solution. Is there a better solution?

+5
source share
5 answers

, A[0] . ; A[i] A[0], .

i , A[i] < A[0], , A[0] , , , A[i]. , , , . .

, O (n)!

:

int i_pole = 0;
int i_max  = 0;
bool have_pole = true;
for (int i = 1; i < N; i++)
{
    if (A[i] < A[i_pole])
    {
        have_pole = false;
    }
    if (A[i] > A[i_max])
    {
        i_max = i;
        if (!have_pole)
        {
            i_pole = i;
        }
        have_pole = true;
    }
}
+5

, , O (n log n) , .

EDIT: , . - [2, 5, 3, 1, 4].

+3

, , , MIN MAX. M MAX 0..M. M MIN M..N-1.

M MIN MAX. INPUT [M] == MIN [M] INPUT [M] == MAX [M], M .

MIN N , MAX. N . O (N) . .

+1

, i- node , A[i] i. , ( ). - A[bad] < maxSoFar MP. , A[good] < A[bad] . ( maxSoFar ), . - MP, MP . - O (n), - n n .

Update

, , "" "" :).

0

You can combine bmcnett and Oli answers to find all poles as quickly as possible.

std::vector<int> i_poles;
i_poles.push_back(0);
int i_max = 0;
for (int i = 1; i < N; i++)
{
    while (!i_poles.empty() && A[i] < A[i_poles.back()])
    {
        i_poles.pop_back();
    }
    if (A[i] >= A[i_max])
    {
        i_poles.push_back(i);
    }
}

You can use an array pre-allocated for size N if you want to avoid redistribution.

0
source

All Articles