There is no reason to use lists instead of arrays, new int[size] will give you an array full of 0s without any overhead.
If you want to optimize, youYou can useget away with creating only one array (leftMax the same way) and then while computing the values of rightMax -, instead of saving them into an array, complete the full calculation of how much to add to ans. Like this:
public int TrapDynamicProgramming(int[] height)
{
if (height == null || height.Length == 0)
{
return 0;
}
int ans = 0;
int size = height.Length;
int[] leftMax = new int[size];
leftMax[0] = height[0];
for (int i = 1; i < size; i++)
{
leftMax[i] = Math.Max(height[i], leftMax[i - 1]);
}
int rightMax = height[size - 1];
for (int i = size - 2; i >= 0; i--)
{
rightMax = Math.Max(height[i], rightMax);
ans += Math.Min(leftMax[i], rightMax) - height[i];
}
return ans;
}