Skip to content

Commit 3c01ada

Browse files
Update Minimize_the_height.cpp
1 parent a192d2b commit 3c01ada

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

Arrays/Minimize_the_height.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,21 @@ using namespace std;
1919
class Solution {
2020
public:
2121
int getMinDiff(int arr[], int n, int k) {
22+
//sort the array first
2223
sort(arr, arr+n);
2324

25+
//store the difference between first and last value.
2426
int ans = arr[n-1] - arr[0];
2527

2628
for(int i = 0; i < n-1; i++) {
2729
if(arr[i+1] < k) {
2830
continue;
2931
}
32+
//currMin will have minimum value after update
3033
int currMin = min(arr[i+1]-k, arr[0]+k);
34+
//currMax will have maximum value after update
3135
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.
3237
ans = min(ans, currMax-currMin);
3338
}
3439

@@ -38,15 +43,22 @@ class Solution {
3843

3944
int main(){
4045
int n,k;
46+
47+
//Accept length of the array
4148
cin>>n;
49+
//K is the number by which the values will be increased/decreased
4250
cin>>k;
43-
int arr[n];
4451

52+
int arr[n];
53+
//loop to accept array values
4554
for(int i=0;i<n;i++){
4655
cin>>arr[i];
4756
}
57+
//creating object of Solution class and saving the returned value in min_diff variable.
4858
Solution obj;
4959
int min_diff = obj.getMinDiff(arr,n,k);
60+
61+
//print the final answer
5062
cout<<"The difference between the largest and smallest is: " << min_diff<< "\n";
5163

5264
return 0;

0 commit comments

Comments
 (0)