There are n roses in a shop. Each rose is assigned an ID. These roses are arranged in order
. Each rose has a smell factor denoted as (). 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 to (). You can remove at most one rose from this segment of roses. Thus, the final length of roses is or .
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 with indices from to is . The subarray is strictly increasing if .
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