Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Smallest Range I in Python
Suppose we have an array A of integers, now for each integer A[i] we can choose any x with range [-K to K] then add x to A[i]. Now after this process, we have some array B. We have to find the smallest possible difference between the maximum value of B and the minimum value of B.
So, if the input is like A = [0,10], K = 2, then the output will be 6, as B = [2,8]
To solve this, we will follow these steps −
- MAX := (maximum of A) - K
- MIN := (minimum of A) + K
- difference := MAX - MIN
- if difference <0 is non-zero, then
- return 0
- otherwise return difference
Let us see the following implementation to get better understanding −
Example
class Solution: def smallestRangeI(self, A, K): MAX = max(A)-K MIN = min(A)+K difference = MAX-MIN if difference <0: return 0 else: return difference ob = Solution() print(ob.smallestRangeI([0,10],2))
Input
[0,10],2
Output
6
Advertisements
