How do i opetimize it?

N=1e4 so N*N dp array size will be 1e8 i have done that MLE came.

also by using map<pair,int,int>> only two test cases pass.

See my code-

@yaduvanshii092 when these type of situations arrive try to save the answer for some portion instead of complete array like save for order of 1e6 or 1e7 space
Coding Blocks IDE
like here your approach is correct save limit space it will work fine
if issue still exists let me know and if clear rate my experience

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.