Skip to content

Commit 2aff954

Browse files
authored
Merge branch 'CodeHarborHub:main' into main
2 parents b212430 + 12092fb commit 2aff954

File tree

3 files changed

+282
-0
lines changed

3 files changed

+282
-0
lines changed

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,12 @@ export const problems = [
442442
"leetCodeLink": "https://leetcode.com/problems/maximum-total-reward-using-operations-i",
443443
"solutionLink": "#"
444444
},
445+
{
446+
"problemName": "3181. Maximum Total Reward Using Operations II",
447+
"difficulty": "Hard",
448+
"leetCodeLink": "https://leetcode.com/problems/maximum-total-reward-using-operations-ii",
449+
"solutionLink": "#"
450+
},
445451
];
446452

447453
<Table
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
---
2+
id: patching-array
3+
title: Patching Array
4+
level: hard
5+
sidebar_label: Patching Array
6+
tags:
7+
- Greedy
8+
- Array
9+
- Binary Search
10+
- Java
11+
description: "This document provides solutions for the Patching Array problem."
12+
---
13+
14+
## Problem Statement
15+
16+
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array.
17+
18+
Return the minimum number of patches required.
19+
20+
**Example:**
21+
22+
Example 1:
23+
24+
Input: `nums = [1,3]`, `n = 6`
25+
26+
Output: `1`
27+
28+
Explanation:
29+
30+
Combinations of nums are `[1]`, `[3]`, `[1,3]`, which form possible sums of: `1, 3, 4`.
31+
Now if we add/patch `2` to nums, the combinations are: `[1]`, `[2]`, `[3]`, `[1,3]`, `[2,3]`, `[1,2,3]`.
32+
Possible sums are `1, 2, 3, 4, 5, 6`, which now covers the range `[1, 6]`.
33+
So we only need `1` patch.
34+
35+
Example 2:
36+
37+
Input: `nums = [1,5,10]`, `n = 20`
38+
39+
Output: `2`
40+
41+
Explanation:
42+
43+
The two patches can be `[2, 4]`.
44+
45+
Example 3:
46+
47+
Input: `nums = [1,2,2]`, `n = 5`
48+
49+
Output: `0`
50+
51+
Explanation:
52+
53+
In this case, the array `nums` already covers all sums up to `5`, so no patches are needed.
54+
55+
**Constraints:**
56+
57+
- `1 <= nums.length <= 1000`
58+
- `1 <= nums[i] <= 10^4`
59+
- `nums` is sorted in ascending order.
60+
- `1 <= n <= 2 * 10^9 - 1`
61+
62+
## Solutions
63+
64+
### Approach
65+
66+
The problem can be efficiently solved using a greedy approach:
67+
68+
1. **Initialization:**
69+
- Initialize `miss` to `1`, which represents the smallest number that cannot be formed with the current elements in `nums`.
70+
- Initialize `result` to `0` to count the number of patches needed.
71+
- Initialize `i` to `0` to iterate through `nums`.
72+
73+
2. **Iterate Until Covering `n`:**
74+
- While `miss` is less than or equal to `n`, check if the current number `miss` can be formed by adding elements from `nums`.
75+
- If `nums[i]` is less than or equal to `miss`, add `nums[i]` to `miss` and move to the next element (`i++`).
76+
- If `nums[i]` is greater than `miss` or `i` exceeds the length of `nums`, it means `miss` cannot be formed with the current elements. Therefore, add `miss` itself to `nums` to extend the range of possible sums and increment `result`.
77+
78+
3. **Return Result:**
79+
- Once the loop ends and `miss` is greater than `n`, return `result`, which is the minimum number of patches required to cover all sums up to `n`.
80+
81+
### Java
82+
83+
```java
84+
class Solution {
85+
public int minPatches(int[] nums, int n) {
86+
long miss = 1;
87+
int result = 0;
88+
int i = 0;
89+
90+
while (miss <= n) {
91+
if (i < nums.length && nums[i] <= miss) {
92+
miss += nums[i];
93+
i++;
94+
} else {
95+
miss += miss;
96+
result++;
97+
}
98+
}
99+
100+
return result;
101+
}
102+
```
103+
### Python
104+
105+
```Python
106+
from typing import List
107+
108+
class Solution:
109+
def minPatches(self, nums: List[int], n: int) -> int:
110+
miss = 1
111+
result = 0
112+
i = 0
113+
114+
while miss <= n:
115+
if i < len(nums) and nums[i] <= miss:
116+
miss += nums[i]
117+
i += 1
118+
else:
119+
miss += miss
120+
result += 1
121+
122+
return result
123+
```
124+
125+
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
---
2+
id: split-array-with-same-average
3+
title: Split Array With Same Average
4+
sidebar_label: 0805 Split Array With Same Average
5+
tags:
6+
- Java
7+
- Math
8+
- Array
9+
- Binary Search
10+
- Dynamic Programming
11+
- Bitmask
12+
description: "This document provides a solution where we split an array into two non-empty subsets such that both subsets have the same average."
13+
---
14+
15+
## Problem
16+
17+
You are given an integer array $nums$.
18+
19+
You should move each element of $nums$ into one of the two arrays $A$ and $B$ such that $A$ and $B$ are non-empty, and $average(A) == average(B)$.
20+
21+
Return $true$ if it is possible to achieve that and $false$ otherwise.
22+
23+
**Note** that for an array $arr$, $average(arr)$ is the sum of all the elements of $arr$ over the length of $arr$.
24+
25+
### Examples
26+
27+
**Example 1:**
28+
29+
```
30+
Input: nums = [1,2,3,4,5,6,7,8]
31+
32+
Output: true
33+
34+
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5 .
35+
36+
```
37+
**Example 2:**
38+
39+
```
40+
Input: nums = [3,1]
41+
42+
Output: false
43+
44+
```
45+
46+
### Constraints
47+
48+
- $1 <= nums.length <= 30$
49+
- $0 <= nums[i] <= 10^4$
50+
---
51+
52+
## Approach
53+
54+
To solve the problem, we need to understand the nature of the allowed moves:
55+
56+
1. **Calculate Total Sum**:
57+
58+
- First, calculate the total sum of the array.
59+
60+
2. **Sort the Array**:
61+
62+
- Sorting helps in pruning the search space.
63+
64+
3. **Iterate Over Possible Sizes**:
65+
66+
- Iterate over possible subset sizes from 1 to n/2. For each size, check if the corresponding subset sum can be an integer.
67+
68+
4. **Check for Possible Partition**:
69+
70+
- Use a recursive function with memoization to check if it’s possible to partition the array into subsets with the required sum and size.
71+
72+
## Solution for Split Array With Same Average
73+
74+
- The problem requires us to split an array into two non-empty subsets such that both subsets have the same average.
75+
76+
- For two subsets to have the same average, the sum of elements in each subset divided by their respective lengths must be equal.
77+
78+
#### Code in Java
79+
80+
```java
81+
import java.util.Arrays;
82+
83+
class Solution {
84+
public boolean splitArraySameAverage(int[] nums) {
85+
int n = nums.length;
86+
int totalSum = Arrays.stream(nums).sum();
87+
88+
Arrays.sort(nums);
89+
90+
for (int size = 1; size <= n / 2; size++) {
91+
if (totalSum * size % n == 0) {
92+
int target = totalSum * size / n;
93+
if (canPartition(nums, size, target, 0)) {
94+
return true;
95+
}
96+
}
97+
}
98+
99+
return false;
100+
}
101+
102+
private boolean canPartition(int[] nums, int size, int target, int start) {
103+
if (size == 0) {
104+
return target == 0;
105+
}
106+
107+
for (int i = start; i <= nums.length - size; i++) {
108+
if (i > start && nums[i] == nums[i - 1]) {
109+
continue;
110+
}
111+
112+
if (nums[i] > target) {
113+
break;
114+
}
115+
116+
if (canPartition(nums, size - 1, target - nums[i], i + 1)) {
117+
return true;
118+
}
119+
}
120+
121+
return false;
122+
}
123+
124+
public static void main(String[] args) {
125+
Solution sol = new Solution();
126+
127+
// Test cases
128+
int[] nums1 = {1, 2, 3, 4, 5, 6, 7, 8};
129+
System.out.println(sol.splitArraySameAverage(nums1)); // Output: true
130+
131+
int[] nums2 = {3, 1};
132+
System.out.println(sol.splitArraySameAverage(nums2)); // Output: false
133+
}
134+
}
135+
```
136+
137+
### Complexity Analysis
138+
139+
#### Time Complexity: $O(2^ n/2)$
140+
141+
> **Reason**: Time Complexity is $O(2^ n/2)$. Because Each half of the array can generate $O(2^ n/2)$ subsets.
142+
143+
#### Space Complexity: $O(2^ n/2)$
144+
145+
> **Reason**: The space complexity is $O(2^ n/2)$, Because it helps in Storing subset sums and sizes.
146+
147+
# References
148+
149+
- **LeetCode Problem:** [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/description/)
150+
- **Solution Link:** [Split Array With Same Average Solution on LeetCode](https://leetcode.com/problems/split-array-with-same-average/solutions/)
151+
- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/)

0 commit comments

Comments
 (0)