I have been trying to understand the logic behind this problem for a lot of days but couldn’t get any near the answer. I would appreciate some help.

From INOI 2018 Discussion ,

“For second one, The observation was that, we can take one path and calculate the total sum without a second path using dp[i][j][k] = min/max(dp[i-1][j][k], dp[i-1][j-1][k-1])+prefix_sum[i][j]. We calculate this two times, once for min and once for max and then we can use the prefix sum intuition to subtract min-dp from max-dp. It’s not clear enough here, but you might get an essence.”

can you like explain it in a better way please.