- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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

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

- Related Articles
- Program to swap string characters pairwise in Python
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Python program to get all pairwise combinations from a list
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Pairwise Addition in Tuples in Python
- Program to restore the array from adjacent pairs in Python
- Program to find valid matrix given row and column sums in Python
- Program to find range sum of sorted subarray sums using Python
- Program to make Indian Flag in Python
- Program to find shortest string after removing different adjacent bits in Python
- Program to find minimum adjacent swaps for K consecutive ones in Python
- Removing letters to make adjacent pairs different using JavaScript
- Program to find index whose left and right elements sums are equal in Python
- Program to find any two numbers in a list that sums up to k in Python
- Program to find minimum possible difference of indices of adjacent elements in Python

Advertisements