![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements