
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Maximum Difference of Adjacent Values After Deleting K Numbers in Python
Suppose we have a list of numbers called nums and they are sorted in ascending order, we have to delete k values from the list such that the maximum difference between any two adjacent values is as minimum as possible, and finally find the difference.
So, if the input is like nums = [15, 20, 30, 400, 1500] k = 2, then the output will be 10, as if we remove [400, 1500] to get the difference of 20 and 30.
To solve this, we will follow these steps −
- abs_diff := a list of differences of every consecutive elements in nums
- Define a function dp() . This will take i, j, cnt
- if cnt is same as 0, then
- m := 0
- for k in range i to j, do
- m := maximum of m and abs_diff[k]
- return m
- return minimum of dp(i + 1, j, cnt - 1) and dp(i, j - 1, cnt - 1)
- From the main method do the following:
- return dp(0, size of abs_diff - 1, k)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): abs_diff = [nums[i] - nums[i - 1] for i in range(1, len(nums))] def dp(i, j, cnt): if cnt == 0: m = 0 for k in range(i, j + 1): m = max(m, abs_diff[k]) return m return min(dp(i + 1, j, cnt - 1), dp(i, j - 1, cnt - 1)) return dp(0, len(abs_diff) - 1, k) ob = Solution() nums = [15, 20, 30, 400, 1500] k = 2 print(ob.solve(nums, k))
Input
[15, 20, 30, 400, 1500], 2
Output
10
Advertisements