- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- Program to swap string characters pairwise in Python
- Python program to get all pairwise combinations from a list
- Make the button size small with Bootstrap
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Pairwise Addition in Tuples in Python
- Program to find k sublists with largest sums and return sums in ascending order in Python
- Make the button size extra small with Bootstrap
- Removing letters to make adjacent pairs different using JavaScript
- Program to restore the array from adjacent pairs in Python
- Program to make Indian Flag in Python
- How to make a list of partial sums using forEach JavaScript
- Program to find valid matrix given row and column sums in Python
- Multiply Adjacent elements in Python
- Program to find range sum of sorted subarray sums using Python
- Program to find shortest string after removing different adjacent bits in Python

Advertisements