Roses in a shop

There are n roses in a shop. Each rose is assigned an ID. These roses are arranged in order 

1, 2, 3, ..., n. Each rose has a smell factor denoted as smell[i] (1≤i≤n). You want to buy roses from this shop under the condition that you can buy roses in a segment. In other words, you can purchase roses from l to r (1≤l≤r≤n). You can remove at most one rose from this segment of roses. Thus, the final length of roses is n−1 or n.

Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the smell factors of these roses.

Note: A contiguous subarray a with indices from l to r is a[l, ..., r]=a[l], a[l+1], ..., a[r]. The subarray a[l, ..., r] is strictly increasing if a[l]<a[l+1]< ... <a[r].

Example:

Input:  n = 5, a = [1,2,5,3,4]
Output: 4

Approach

C++

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

int rosesInShop(int n, int a[])
{
    int p[n], s[n];
    p[0] = 1;

    for (int i = 1; i < n; i++)
    {
        p[i] = 1;
        if (a[i] > a[i - 1])
            p[i] = p[i - 1] + 1;
    }
    s[n - 1] = 1;
    for (int i = n - 2; i >= 0; i--)
    {
        s[i] = 1;
        if (a[i + 1] > a[i])
            s[i] = s[i + 1] + 1;
    }
    int maxElement = *max_element(p, p + n);

    for (int i = 1; i < n - 1; i++)
    {
        if (a[i - 1] < a[i + 1])
        {
            maxElement = max(maxElement, p[i - 1] + s[i + 1]);
        }
    }

    return maxElement;
}
int main()
{

    int n = 5;

    int a[n] = {1, 2, 5, 3, 4};

    cout << rosesInShop(n, a);

    return 0;
}


No comments:

Post a Comment