data test;
input x @@;
cards;
. . 1 2 . 3 . . 5
;run;
/* step 1: add a sequence number ID and change the missing value to zero */
data test_1;
id = _n_;
set test;
if x = . then y = 0;
else y=x;
run;
/* Step 2: reverse the order of the data by ID */
proc sort data=test_1 out=test_revers;
by descending id;
run;
/* Step 3: create a lag variable */
data test_2;
set test_revers;
y_lag = lag(y);
run;
/* step 4: fill the missing value */
data test_3;
set test_2;
retain z;
if _n_ = 1 and y~=. then z = y;
else if y = 0 and y - y_lag < 0 then z = y_lag;
else if y = 0 and y_lag = 0 then z = z;
else z = y;
drop y y_lag;
run;
/* change the order back */
proc sort data=test_3 out = test_4;
by ID;
run;
data test_result (rename = (x=z));
set test_4 (keep=z);
run;