Find index of the nearest larger number of given index number

Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices.

For example, given [4, 1, 3, 5, 6] and index 0, you should return 3.

If two distances to larger numbers are equal, then return any one of them. If the array at i doesn't have a nearest larger integer, then return null.

Example:

Input:  arr ={4,1,3,5,6}, index = 0
Output: 3

Approach

C++

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

int findNearestLarger(vector<int&arrint index)
{
    int minVal = arr[index]n = arr.size();
    int j = index;
    while (n > (++index) || (--j) >= 0)
    {
        if (index < n && arr[index] > minVal)
        {
            return index;
        }
        if (j >= 0 && arr[j] > minVal)
        {
            return j;
        }
    }
    return -1;
}

int main()
{
    vector<intarr = {41356};
    int index = 0;

    cout << findNearestLarger(arrindex);

    return 0;
}


No comments:

Post a Comment