Skip to content

Commit 15072ba

Browse files
authored
Merge pull request #1603 from SadafKausar2025/mk
Added leetcode -3107 minimum operation to make median equal to k
2 parents a1922ff + e42a7bd commit 15072ba

File tree

6 files changed

+203
-13
lines changed

6 files changed

+203
-13
lines changed

dsa-problems/leetcode-problems/3100-3199.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export const problems = [
5656
"problemName": "3107. Minimum Operations to Make Median of Array Equal to K",
5757
"difficulty": "Medium",
5858
"leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-median-of-array-equal-to-k",
59-
"solutionLink": "#"
59+
"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Minimum-operation-to-make-median-of-array-equal-to-k"
6060
},
6161
{
6262
"problemName": "3108. Minimum Cost Walk in Weighted Graph",

dsa-solutions/lc-solutions/3100-3199/3100-Water-Bottles-II.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
id: water-bottles-II
33
title: Water-Bottles-II
44
level: hard
5-
sidebar_label: Water-Bottles-II
5+
sidebar_label: 3100-Water-Bottles-II
66
tags:
77
- Dynamic Programming
88
- Bit Manipulation

dsa-solutions/lc-solutions/3100-3199/3101-count-alternating-subarrays.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
id: Count-Alternating-subarrays
33
title: Count-Alternating-subarrays
44
level: hard
5-
sidebar_label: Count-Alternating-subarrays
5+
sidebar_label: 3101-Count-Alternating-subarrays
66
tags:
77
- Dynamic Programming
88
- Bit Manipulation
@@ -83,13 +83,11 @@ The provided code effectively implements the sliding window approach with the me
8383

8484
4. int left = 0;: Initializes left and right pointers, both starting at index 0.
8585

86-
87-
- int right = 0;
86+
- int right = 0;
8887

8988
5. while (right < n): A loop that continues as long as right hasn't reached the end of the array.
9089

91-
92-
- while (right < n - 1 && nums[right] != nums[right + 1]): This inner loop extends the current subarray as long as adjacent elements differ.
90+
- while (right < n - 1 && nums[right] != nums[right + 1]): This inner loop extends the current subarray as long as adjacent elements differ.
9391

9492
6. It checks if right is within bounds and if the elements at right and right + 1 are different.
9593

dsa-solutions/lc-solutions/3100-3199/3102-Minimize Manhattan Distance.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
id: Minimize-Manhattan-Distances
33
title: Minimize Manhattan Distances
44
level: hard
5-
sidebar_label: Minimize Manhattan Distances
5+
sidebar_label: 3102-Minimize Manhattan Distances
66
tags:
77
- Dynamic Programming
88
- Bit Manipulation
@@ -74,15 +74,14 @@ Constraints:
7474

7575
`maxi=max(maxsum-minsum,maxdiff-mindiff);`
7676

77-
7877
- Now, find the values of minsum, maxsum, mindiff, maxdiff
7978

80-
- `minsum=st1.begin(), maxsum=--st1.end()`
79+
- `minsum=st1.begin(), maxsum=--st1.end()`
8180

82-
- `mindiff=st2.begin(), maxdiff=--st2.end()`
81+
- `mindiff=st2.begin(), maxdiff=--st2.end()`
8382

84-
`Note:- st.end() denotes an iterator pointing to the position
85-
just after the last element that's why we have taken --st.end()`
83+
`Note:- st.end() denotes an iterator pointing to the position
84+
just after the last element that's why we have taken --st.end()`
8685

8786
8. After finding the maximum value upon removal of the current sum and difference, store the minimum computed so far in variable mini which holds the minimum of all Manhattan Distance found so far.
8887

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
---
2+
id: Minimum-operation-to-make-median-of-array-equal-to-k
3+
title: Minimum-operation-to-make-median-of-array-equal-to-k
4+
sidebar_label: 3107-Minimum-operation-to-make-median-of-array-equal-to-k
5+
tags:
6+
- Java
7+
- Greedy
8+
- String
9+
description: "This document provides a solution of Minimum-operation-to-make-median-of-array-equal-to-k"
10+
---
11+
12+
## Problem statement:
13+
14+
You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1.
15+
16+
Return the minimum number of operations needed to make the median of nums equal to k.
17+
18+
The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
19+
20+
**Example 1:**
21+
22+
Input: nums = [2,5,6,8,5], k = 4
23+
Output: 2
24+
25+
Explanation:
26+
We can subtract one from nums[1] and nums[4] to obtain [2, 4, 6, 8, 4]. The median of the resulting array is equal to k.
27+
28+
**Example 2:**
29+
30+
Input: nums = [2,5,6,8,5], k = 7
31+
Output: 3
32+
33+
Explanation:
34+
We can add one to nums[1] twice and add one to nums[2] once to obtain [2, 7, 7, 8, 5].
35+
36+
**Example 3:**
37+
38+
Input: nums = [1,2,3,4,5,6], k = 4
39+
Output: 0
40+
41+
Explanation:
42+
The median of the array is already equal to k.
43+
44+
Constraints:
45+
46+
`1 <= nums.length <= 2 * 105`
47+
`1 <= nums[i] <= 109`
48+
`1 <= k <= 109`
49+
50+
## Solutions:
51+
52+
### Intuition
53+
54+
-> Plot the intial points and the expected points of the given array on a graph.
55+
-> To find the expected median 'k' the expected graph should coincide with the inital graph.
56+
-> Find minimum number of steps to coincide them.
57+
58+
### Approach
59+
60+
consider: nums = [2,5,6,8,5], k = 4
61+
62+
![alt text](image-2.png)
63+
64+
1. till the n/2th element-> all elements to the left of expected graph should be merged with the expected graph and those on the right wouldn't affect the median so no need to add in answer.
65+
66+
2. for n/2th element it should be same for both graphs, so take difference and add.
67+
68+
3. for elements after n/2-> the element to the left of expected graph wouldn't affect the median however those on the right will, so shift them so that they coincide and add the cost of shifting as well.
69+
70+
### Observation:
71+
72+
To make both the graphs coincide:
73+
74+
1. For elements less than the median (i < n / 2): calculate the difference between the current element nums[i] and the target value k. If this difference is positive (i.e., nums[i] is greater than k), add this difference to ans. Otherwise, add 0(already conincided).
75+
76+
2. For the median element itself (i == n / 2): calculate the absolute difference between the current element nums[i] and k and add it to ans. This ensures that regardless of whether k is greater or smaller than the median, its distance is considered.
77+
78+
3. For elements greater than the median (i > n / 2): calculate the difference between k and the current element nums[i]. If this difference is positive (i.e., nums[i] is less than k), add this difference to ans. Otherwise, add 0(already coincided).
79+
80+
## code:
81+
82+
<Tabs>
83+
<TabItem value="cpp" label="C++" default>
84+
<SolutionAuthor name="@Ajay-Dhangar"/>
85+
```cpp
86+
#include <vector>
87+
#include <algorithm>
88+
using namespace std;
89+
90+
class Solution {
91+
public:
92+
long long minOperationsToMakeMedianK(vector<int>& nums, int k) {
93+
int n = nums.size();
94+
sort(nums.begin(), nums.end());
95+
long long ans = 0;
96+
for (int i = 0; i < n; i++) {
97+
if (i < n / 2)
98+
ans += max(0, nums[i] - k); // 1st case
99+
else if (i == n / 2)
100+
ans += abs(nums[i] - k); // 2nd case
101+
else
102+
ans += max(0, k - nums[i]); // 3rd case
103+
}
104+
return ans;
105+
}
106+
};
107+
```
108+
</TabItem>
109+
<TabItem value="java" label="Java">
110+
<SolutionAuthor name="@Ajay-Dhangar"/>
111+
```java
112+
import java.util.*;
113+
114+
public class Solution {
115+
public long minOperationsToMakeMedianK(List<Integer> nums, int k) {
116+
int n = nums.size();
117+
Collections.sort(nums);
118+
long ans = 0;
119+
for (int i = 0; i < n; i++) {
120+
if (i < n / 2)
121+
ans += Math.max(0, nums.get(i) - k); // 1st case
122+
else if (i == n / 2)
123+
ans += Math.abs(nums.get(i) - k); // 2nd case
124+
else
125+
ans += Math.max(0, k - nums.get(i)); // 3rd case
126+
}
127+
return ans;
128+
}
129+
}
130+
```
131+
</TabItem>
132+
<TabItem value="python" label="Python">
133+
<SolutionAuthor name="@Ajay-Dhangar"/>
134+
```python
135+
from typing import List
136+
137+
class Solution:
138+
def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int:
139+
n = len(nums)
140+
nums.sort()
141+
ans = 0
142+
for i in range(n):
143+
if i < n // 2:
144+
ans += max(0, nums[i] - k) # 1st case
145+
elif i == n // 2:
146+
ans += abs(nums[i] - k) # 2nd case
147+
else:
148+
ans += max(0, k - nums[i]) # 3rd case
149+
return ans
150+
```
151+
</TabItem>
152+
<TabItem value="c" label="C">
153+
<SolutionAuthor name="@Ajay-Dhangar"/>
154+
```c
155+
#include <stdio.h>
156+
#include <stdlib.h>
157+
#include <limits.h>
158+
159+
int cmp(const void* a, const void* b) {
160+
return (*(int*)a - *(int*)b);
161+
}
162+
163+
long long minOperationsToMakeMedianK(int* nums, int numsSize, int k) {
164+
qsort(nums, numsSize, sizeof(int), cmp);
165+
long long ans = 0;
166+
for (int i = 0; i < numsSize; i++) {
167+
if (i < numsSize / 2)
168+
ans += nums[i] > k ? nums[i] - k : 0; // 1st case
169+
else if (i == numsSize / 2)
170+
ans += abs(nums[i] - k); // 2nd case
171+
else
172+
ans += nums[i] < k ? k - nums[i] : 0; // 3rd case
173+
}
174+
return ans;
175+
}
176+
177+
int main() {
178+
int nums[] = {1, 3, 2, 5, 4};
179+
int numsSize = sizeof(nums) / sizeof(nums[0]);
180+
int k = 3;
181+
printf("%lld\n", minOperationsToMakeMedianK(nums, numsSize, k));
182+
return 0;
183+
}
184+
```
185+
</TabItem>
186+
187+
</Tabs>
188+
189+
## Complexity
190+
191+
Time complexity: $O(nlogn)$
192+
193+
Space complexity: $O(1)$
974 KB
Loading

0 commit comments

Comments
 (0)