Qty Adjust based on Last date

Dear All Experts,

I have an table where data is coming as below and i want the output as per the last picture.

Suppose Item A have stock 5 Qty and under Item A there are 5 Invoices, so it will check last Invoice Qty and adjust the Invoice Qty based on stock Qty and its should not be more then stock Qty.

Please provide the sql query for the same.

Without additional explanation, I don't see anything in the base table that would support the values in the desired output.