Problem(Error)

Logic is right but during submit wrong answer get display. How to fix this problem. In custom input also answer right as per sample input and sample output.
Also how to tackle with constraints.

Check your answer for multiple test cases. Your logic might be wrong for other test cases.
For constraints, if N=10^5, you can run upto O(N) or maybe O(N*log N)
For N=10^3, you can run upto O(N^2) and so on