problem So i know the solution is dp with 2 choices for index j in array for value i,closest left to j and closest right to j,but my query is if i don't choose optimally and instead choose m1= max value of (p+dp[i-1][p]) for p>j and m2=max value of (p-dp[i-1][p]) for p<j and then update dp[i][j]-max(m1,m2) will that also work?









No, your approach won’t always work because it doesn’t correctly account for how j affects the transition cost from p to j. In standard optimized DP, we precompute values like dp[i-1][p] ± p and then adjust with ∓ j during the update to maintain correctness. Your version mixes p and dp[i-1][p] without that final adjustment by j, which leads to incorrect results.
I am storing p+dp[i-1][p] and p-dp[i-1][p] separately and when i come at some index j for current i,i will search for p+dp[i-1][p] max value for any p>j and also search for min value of p-dp[i-1][p] value for all p<j and then transition is trivial.Also we can see max and min value respectively using seg tree