Smallest Range I

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimumscoreofnumsafter applying the mentioned operation at most once for each index in it.
LeetCode Problem - 908
class Solution {
public int smallestRangeI(int[] nums, int k) {
// Sort the array to easily access the smallest and largest elements
Arrays.sort(nums);
// Get the smallest and largest elements after sorting
int firstIdx = nums[0];
int lastIdx = nums[nums.length-1];
// Initialize flag to store the minimum possible difference
int flag = Integer.MAX_VALUE;
// Iterate k+1 times to try to reduce the difference between the smallest and largest elements
for(int i=0; i<k+1; i++){
// Calculate the current difference between the largest and smallest elements
int diff = lastIdx - firstIdx;
// If the difference becomes negative, return 0 (as difference cannot be negative)
if(diff < 0) {
return 0;
}
// Update the minimum difference found so far
if(diff < flag){
flag = diff;
}
// Move towards reducing the difference further by incrementing the smallest
// element and decrementing the largest element
firstIdx++;
lastIdx--;
}
// Return the smallest difference found
return flag;
}
}




