q3.cpp
· 504 B · C++
Ham
int minMoves(vector<int>arr, int n, int k) {
// Sort the array
sort(arr.begin(), arr.end());
int i = 0, j = n - 1;
int moves = 0;
// Two pointers approach
while (i <= j) {
// If the lightest and heaviest together are within the limit, move both
if (arr[i] + arr[j] <= k) {
i++; // move the lighter object
}
// Move the heavier object (j--)
j--;
// Count one move
moves++;
}
return moves;
}
1 | int minMoves(vector<int>arr, int n, int k) { |
2 | // Sort the array |
3 | sort(arr.begin(), arr.end()); |
4 | |
5 | int i = 0, j = n - 1; |
6 | int moves = 0; |
7 | |
8 | // Two pointers approach |
9 | while (i <= j) { |
10 | // If the lightest and heaviest together are within the limit, move both |
11 | if (arr[i] + arr[j] <= k) { |
12 | i++; // move the lighter object |
13 | } |
14 | // Move the heavier object (j--) |
15 | j--; |
16 | // Count one move |
17 | moves++; |
18 | } |
19 | |
20 | return moves; |
21 | } |