Skip to content

Commit dc35b58

Browse files
Add new daily problem code
1 parent ceb2ee5 commit dc35b58

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Intuition
2+
The key insights behind this intution is:
3+
4+
If the array has less than 5 elements, the minimum difference will be 0, as we can't form two groups of 4 elements.
5+
Sorting the array in ascending order allows us to easily identify the 4 smallest and 4 largest elements.
6+
By calculating the difference between the sum of the 4 largest elements and the sum of the 4 smallest elements, we can find the minimum difference.
7+
Approach
8+
The approach used in the provided code is to find the minimum difference between the sum of the largest 4 elements and the sum of the smallest 4 elements in the given array A.
9+
The intuition behind this approach is that the minimum difference will be achieved by either:
10+
11+
Removing the 4 smallest elements and keeping the 4 largest elements.
12+
Removing the 4 largest elements and keeping the 4 smallest elements.
13+
Complexity
14+
Time complexity:O(n log n)
15+
Space complexity:O(1)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
class Solution
7+
{
8+
public:
9+
int minDifference(vector<int> &A)
10+
{
11+
int n = A.size();
12+
if (n < 5)
13+
return 0;
14+
sort(A.begin(), A.end());
15+
return min({A[n - 1] - A[3], A[n - 2] - A[2], A[n - 3] - A[1], A[n - 4] - A[0]});
16+
}
17+
};

0 commit comments

Comments
 (0)