SQL get difference of row data in another row I want to calculate how many days a product has been out of stock

I have an audit.inventory table where data gets inserted after change in the inventory table.

Inventory Table is as below:

  inventoryid    productid     stock
  1              1             8
  2              2             5


And audit.inventory is same as inventory with an extra stamp field for when the change occured

audit.inventory is as below:

  inventoryid    productid     stock    stamp
  1              1             8        2018-06-26 14:59:33
  1              1             6        2018-06-26 14:59:33
  1              1             5        2018-06-26 14:47:09
  1              1             0        2018-06-21 18:30:50
  1              1             0        2018-06-04 16:57:02
  1              1             3        2018-06-04 14:58:57
  1              1             2        2018-06-02 12:54:18
  1              1             0        2018-05-27 11:44:22    


So if I run this query for productid = 1

select extract(day from stamp) as day_of_month, max(stock) from 
audit.inventory where productid = 1
and extract(month from stamp) = 6 group by extract(day from stamp);


Gives me:

day_of_month    stock
2               2
4               3
21              0
26              5


How can I calculate the stock on days in between, for example 1(day_of_month) will have stock 0, 3(day_of_month) will have 2 as the stock and 4-20(day_of_month) will have stock 3 and then 22-25 will have stock 0.
So the total number of days the product stock has been 0 will be 6 ie. 1,21,22,23,24,25
fiddle

WITH cte (day_of_month, stock) -- add pseudo-records
AS 
( SELECT day_of_month, stock FROM test
  UNION ALL
  SELECT 1,0
  UNION ALL 
  SELECT 31,1 -- June have 30 days
),
cte2 (leadday, day_of_month, stock) -- calculate lead 
AS
( SELECT LEAD(day_of_month) OVER (ORDER BY day_of_month, stock), day_of_month, stock
  FROM cte
)
SELECT SUM(leadday - day_of_month) -- obtain data we need
FROM cte2
WHERE stock = 0;


To make sure the result is correct both when there exist the record for the first day of month and when the last record have stock = 0 uncomment appropriate values for test table data.