Why my answer is wrong?
The logic i used is straight forward and could be easily understood by my code.
- It makes no sense to do j = j - 2 after the while loop if the pattern discovered was of only length 2 then it will keep looping inside it forever for example in the case as simple as
1
3
3 1 3
Your code will give TLE - since the row of same numbers can be a part of increasing as well and decreasing sequence, your logic would require you to move back whenever there is pattern change after row of same numbers for example
4 3 2 2 2 2 3 4 5, In this 4 3 2 2 2 is also valid 2 2 2 3 4 5 is also valid iterating back would bring time complexity to n^2.
Correct Approach: You can make 2 array, one inc, that will have at ith position length of the increasing sequence till i, similary a dec array that will have length of decreasing sequence till ith (ith till n).
For inc array compute the sequence length from left to right
For dec array compute the sequence length from right to left.
Now for every i you have both increasing length till that point and decreasing length to get answer.
Eg
1 6 8 9 3 4 6 5
inc array
1 2 3 4 1 2 3 1
dec array
1 1 1 2 1 1 1 2
Ans 4 + 2 -1
refer to this code if any doubt:
sir,here i am just comparing the element in the jth element with that of j+1th,and ingrement the number of times it satisfies the constraint
that approach is wrong as when same number appears multiple times in success they can satisfy the constraint both ways.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.