# Program to make pairwise adjacent sums small in Python

Suppose we have a list of non-negative numbers say nums and a non-negative value k. Now suppose we can perform an operation where we select a single positive umber in nums and decrease it by 1. We have to find the minimum number of operations required such that every pair of adjacent values in the list sums <= k. If the answer is very large, then return the result mod 10^9 + 7.

So, if the input is like nums = [4, 6, 2, 5], k = 6, then the output will be 5, as we can decrement the list to [3, 3, 1, 4] which is a total of 5 decrements. Here the sum of every adjacent pair is <= 6.

To solve this, we will follow these steps −

• m = 10^9 + 7
• ans := 0
• for i in range 0 to size of nums - 1, do
• sm := nums[i] + nums[i + 1]
• diff := maximum of sm - k and 0
• nums[i + 1] := nums[i + 1] - diff
• if nums[i + 1] < 0, then
• nums[i + 1] := 0
• ans := ans + diff
• return ans mod m

Let us see the following implementation to get better understanding −

## Example

Live Demo

m = 10 ** 9 + 7
class Solution:
def solve(self, nums, k):
ans = 0
for i in range(0, len(nums) - 1):
sm = nums[i] + nums[i + 1]
diff = max(sm - k, 0)
nums[i + 1] -= diff
if nums[i + 1] < 0:
nums[i + 1] = 0
ans += diff
return ans % m
ob = Solution()
nums = [4, 6, 2, 5]
k = 6 print(ob.solve(nums, k))

## Input

[4, 6, 2, 5], 6

## Output

5