File tree Expand file tree Collapse file tree 1 file changed +13
-1
lines changed Expand file tree Collapse file tree 1 file changed +13
-1
lines changed Original file line number Diff line number Diff line change @@ -19,16 +19,21 @@ using namespace std;
19
19
class Solution {
20
20
public:
21
21
int getMinDiff (int arr[], int n, int k) {
22
+ // sort the array first
22
23
sort (arr, arr+n);
23
24
25
+ // store the difference between first and last value.
24
26
int ans = arr[n-1 ] - arr[0 ];
25
27
26
28
for (int i = 0 ; i < n-1 ; i++) {
27
29
if (arr[i+1 ] < k) {
28
30
continue ;
29
31
}
32
+ // currMin will have minimum value after update
30
33
int currMin = min (arr[i+1 ]-k, arr[0 ]+k);
34
+ // currMax will have maximum value after update
31
35
int currMax = max (arr[i]+k, arr[n-1 ]-k);
36
+ // minimum value between previous answers and current difference will be saved in ans variable.
32
37
ans = min (ans, currMax-currMin);
33
38
}
34
39
@@ -38,15 +43,22 @@ class Solution {
38
43
39
44
int main (){
40
45
int n,k;
46
+
47
+ // Accept length of the array
41
48
cin>>n;
49
+ // K is the number by which the values will be increased/decreased
42
50
cin>>k;
43
- int arr[n];
44
51
52
+ int arr[n];
53
+ // loop to accept array values
45
54
for (int i=0 ;i<n;i++){
46
55
cin>>arr[i];
47
56
}
57
+ // creating object of Solution class and saving the returned value in min_diff variable.
48
58
Solution obj;
49
59
int min_diff = obj.getMinDiff (arr,n,k);
60
+
61
+ // print the final answer
50
62
cout<<" The difference between the largest and smallest is: " << min_diff<< " \n " ;
51
63
52
64
return 0 ;
You can’t perform that action at this time.
0 commit comments