π Problem Details
πWhat Were My Initial Thoughts?
- sort the input array
- two pointers to efficiently iterate over the input array
- minDiff variable to track and update minimum difference
π€What Did I Struggle With?
~
π‘ Explanation of Solution
~ same as initial thoughts
β Complexity Analysis
Time Complexity: O(n log n) due to initial sorting of the input array
Space Complexity: O(1), no auxilary space used for this problem
π» Implementation of Solution
class Solution {
public:
Β Β int minimumDifference(vector<int>& nums, int k) {
Β Β Β Β if(k == 1) return 0;
Β Β Β Β sort(nums.begin(), nums.end());
Β Β Β Β int minDiff = INT_MAX;
Β Β Β Β int left = 0 , right = k-1;
Β Β Β Β while(right < nums.size()) {
Β Β Β Β Β Β int diff = nums[right] - nums[left];
Β Β Β Β Β Β minDiff = min(minDiff, diff);
Β Β Β Β Β Β left++;
Β Β Β Β Β Β right++;
Β Β Β Β }
Β Β Β Β return minDiff;
Β Β }
};