Hi, can someone help me solve this problem:
Input consist of integer n and array a of n integers. Output number of pairs (a[i],a[j]), i<j who are adjacent or for all k (i<k<j) this equation is true: a[k]<=min(a[i],a[j]).
1<=n<=10^6
0<=a[i]<=2^31
example:
8
4 1 2 3 6 5 1 2
Output: 11








Since any adjacent element is considered as valid pair, ans is at least
n-1. So initializeans = n-1Let the array be
a[].For such index
bwherea[b+1] < a[b], if you use indexbas left border, calculate how many index you can use as right border. From indexb+1iterate to the right til the elements are non decreasing, i.e. stop at indexiwhena[i]<a[i-1]. From indexb+2tilli-1you can use any index as right border for the left borderb. So, setans = ans + (i-b-2);andb = i-1. Initially setb = -1, then if b != -1 only then you add i-b-2 to answer.Also, for any contiguous segment
[x,y]of length at least 3, where all elements are similar, you can use any index fromxtoy-2as left border for right bordery. So, setans = ans + y - 1 - xComplexity: O(n)
If I understand you correctly, approach is wrong. If you see this test example: 5 4 2 3 2 5 Your answer will be 2 for i=1, you don't look pair (1,5), only (1,2),(1,3). I can't give you problem link beacuse I have problem written on paper, and problem is written on Serbian language.
You are right. I didn't tested for this input. My bad.
Can you give the problem link ?