var arr = '1 2 3 2 3 4 5 1 4 6'.match(/\d+/g);
var max = 4;
function pit(arr, max)
{
var puddle = 0, min;
for (var i = 0; i < arr.length; i++) {
if(max <= +arr[i]) break;
if(min == void 0 && arr[i + 1] < arr[i]) min = arr[i];
if(min != void 0 && arr[i] > min) min = void 0;
if(min != void 0) puddle += min - arr[i];
}
return puddle
}
var num = pit(arr, max) ;
alert(num);