id
int64 1
3.64k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,365 |
Rearrange K Substrings to Form Target String
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p>
<p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p>
<p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p>
<p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p>
<p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcd", t = "cdab", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>s</code> into 2 substrings of length 2: <code>["ab", "cd"]</code>.</li>
<li>Rearranging these substrings as <code>["cd", "ab"]</code>, and then concatenating them results in <code>"cdab"</code>, which matches <code>t</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabbcc", t = "bbaacc", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>s</code> into 3 substrings of length 2: <code>["aa", "bb", "cc"]</code>.</li>
<li>Rearranging these substrings as <code>["bb", "aa", "cc"]</code>, and then concatenating them results in <code>"bbaacc"</code>, which matches <code>t</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aabbcc", t = "bbaacc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>s</code> into 2 substrings of length 3: <code>["aab", "bcc"]</code>.</li>
<li>These substrings cannot be rearranged to form <code>t = "bbaacc"</code>, so the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length == t.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= k <= s.length</code></li>
<li><code>s.length</code> is divisible by <code>k</code>.</li>
<li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li>
<li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li>
</ul>
|
Hash Table; String; Sorting
|
TypeScript
|
function isPossibleToRearrange(s: string, t: string, k: number): boolean {
const cnt: Record<string, number> = {};
const n = s.length;
const m = Math.floor(n / k);
for (let i = 0; i < n; i += m) {
const a = s.slice(i, i + m);
cnt[a] = (cnt[a] || 0) + 1;
const b = t.slice(i, i + m);
cnt[b] = (cnt[b] || 0) - 1;
}
return Object.values(cnt).every(x => x === 0);
}
|
3,366 |
Minimum Array Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p>
<p>You can perform the following operations on <code>nums</code>:</p>
<ul>
<li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li>
<li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li>
</ul>
<p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p>
<p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">23</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li>
<li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li>
<li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li>
<li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li>
<li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li>
<li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 10<sup>5</sup></font></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= op1, op2 <= nums.length</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int minArraySum(vector<int>& nums, int d, int op1, int op2) {
int n = nums.size();
int f[n + 1][op1 + 1][op2 + 1];
memset(f, 0x3f, sizeof f);
f[0][0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums[i - 1];
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
f[i][j][k] = f[i - 1][j][k] + x;
if (j > 0) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2);
}
if (k > 0 && x >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
int y = (x + 1) / 2;
if (y >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2);
}
}
}
}
}
int ans = INT_MAX;
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
ans = min(ans, f[n][j][k]);
}
}
return ans;
}
};
|
3,366 |
Minimum Array Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p>
<p>You can perform the following operations on <code>nums</code>:</p>
<ul>
<li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li>
<li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li>
</ul>
<p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p>
<p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">23</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li>
<li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li>
<li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li>
<li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li>
<li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li>
<li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 10<sup>5</sup></font></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= op1, op2 <= nums.length</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func minArraySum(nums []int, d int, op1 int, op2 int) int {
n := len(nums)
const inf = int(1e9)
f := make([][][]int, n+1)
for i := range f {
f[i] = make([][]int, op1+1)
for j := range f[i] {
f[i][j] = make([]int, op2+1)
for k := range f[i][j] {
f[i][j][k] = inf
}
}
}
f[0][0][0] = 0
for i := 1; i <= n; i++ {
x := nums[i-1]
for j := 0; j <= op1; j++ {
for k := 0; k <= op2; k++ {
f[i][j][k] = f[i-1][j][k] + x
if j > 0 {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k]+(x+1)/2)
}
if k > 0 && x >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j][k-1]+(x-d))
}
if j > 0 && k > 0 {
y := (x + 1) / 2
if y >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(y-d))
}
if x >= d {
f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(x-d+1)/2)
}
}
}
}
}
ans := inf
for j := 0; j <= op1; j++ {
for k := 0; k <= op2; k++ {
ans = min(ans, f[n][j][k])
}
}
return ans
}
|
3,366 |
Minimum Array Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p>
<p>You can perform the following operations on <code>nums</code>:</p>
<ul>
<li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li>
<li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li>
</ul>
<p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p>
<p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">23</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li>
<li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li>
<li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li>
<li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li>
<li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li>
<li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 10<sup>5</sup></font></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= op1, op2 <= nums.length</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int minArraySum(int[] nums, int d, int op1, int op2) {
int n = nums.length;
int[][][] f = new int[n + 1][op1 + 1][op2 + 1];
final int inf = 1 << 29;
for (var g : f) {
for (var h : g) {
Arrays.fill(h, inf);
}
}
f[0][0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums[i - 1];
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
f[i][j][k] = f[i - 1][j][k] + x;
if (j > 0) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2);
}
if (k > 0 && x >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
int y = (x + 1) / 2;
if (y >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k]
= Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2);
}
}
}
}
}
int ans = inf;
for (int j = 0; j <= op1; ++j) {
for (int k = 0; k <= op2; ++k) {
ans = Math.min(ans, f[n][j][k]);
}
}
return ans;
}
}
|
3,366 |
Minimum Array Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p>
<p>You can perform the following operations on <code>nums</code>:</p>
<ul>
<li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li>
<li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li>
</ul>
<p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p>
<p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">23</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li>
<li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li>
<li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li>
<li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li>
<li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li>
<li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 10<sup>5</sup></font></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= op1, op2 <= nums.length</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def minArraySum(self, nums: List[int], d: int, op1: int, op2: int) -> int:
n = len(nums)
f = [[[inf] * (op2 + 1) for _ in range(op1 + 1)] for _ in range(n + 1)]
f[0][0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(op1 + 1):
for k in range(op2 + 1):
f[i][j][k] = f[i - 1][j][k] + x
if j > 0:
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) // 2)
if k > 0 and x >= d:
f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d))
if j > 0 and k > 0:
y = (x + 1) // 2
if y >= d:
f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + y - d)
if x >= d:
f[i][j][k] = min(
f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) // 2
)
ans = inf
for j in range(op1 + 1):
for k in range(op2 + 1):
ans = min(ans, f[n][j][k])
return ans
|
3,366 |
Minimum Array Sum
|
Medium
|
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p>
<p>You can perform the following operations on <code>nums</code>:</p>
<ul>
<li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li>
<li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li>
</ul>
<p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p>
<p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">23</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li>
<li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li>
<li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li>
<li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li>
<li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li>
<li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 10<sup>5</sup></font></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
<li><code>0 <= op1, op2 <= nums.length</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function minArraySum(nums: number[], d: number, op1: number, op2: number): number {
const n = nums.length;
const inf = Number.MAX_SAFE_INTEGER;
const f: number[][][] = Array.from({ length: n + 1 }, () =>
Array.from({ length: op1 + 1 }, () => Array(op2 + 1).fill(inf)),
);
f[0][0][0] = 0;
for (let i = 1; i <= n; i++) {
const x = nums[i - 1];
for (let j = 0; j <= op1; j++) {
for (let k = 0; k <= op2; k++) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + x);
if (j > 0) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + Math.floor((x + 1) / 2));
}
if (k > 0 && x >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d));
}
if (j > 0 && k > 0) {
const y = Math.floor((x + 1) / 2);
if (y >= d) {
f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d));
}
if (x >= d) {
f[i][j][k] = Math.min(
f[i][j][k],
f[i - 1][j - 1][k - 1] + Math.floor((x - d + 1) / 2),
);
}
}
}
}
}
let ans = inf;
for (let j = 0; j <= op1; j++) {
for (let l = 0; l <= op2; l++) {
ans = Math.min(ans, f[n][j][l]);
}
}
return ans;
}
|
3,367 |
Maximize Sum of Weights after Edge Removals
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p>
<p>Your task is to remove <em>zero or more</em> edges such that:</p>
<ul>
<li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li>
<li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li>
</ul>
<p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p>
<ul>
<li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li>
<li>The sum of weights is 22, and we can't achieve a greater sum. Thus, the answer is 22.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">65</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don't remove any edges.</li>
<li>The sum of weights is 65. Thus, the answer is 65.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n - 1</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code><font face="monospace">0 <= edges[i][0] <= n - 1</font></code></li>
<li><code><font face="monospace">0 <= edges[i][1] <= n - 1</font></code></li>
<li><code><font face="monospace">1 <= edges[i][2] <= 10<sup>6</sup></font></code></li>
<li>The input is generated such that <code>edges</code> form a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
C++
|
class Solution {
public:
long long maximizeSumOfWeights(vector<vector<int>>& edges, int k) {
int n = edges.size() + 1;
vector<vector<pair<int, int>>> g(n);
for (auto& e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
using ll = long long;
auto dfs = [&](this auto&& dfs, int u, int fa) -> pair<ll, ll> {
ll s = 0;
vector<ll> t;
for (auto& [v, w] : g[u]) {
if (v == fa) {
continue;
}
auto [a, b] = dfs(v, u);
s += a;
ll d = w + b - a;
if (d > 0) {
t.push_back(d);
}
}
ranges::sort(t, greater<>());
for (int i = 0; i < min((int) t.size(), k - 1); ++i) {
s += t[i];
}
return {s + (t.size() >= k ? t[k - 1] : 0), s};
};
auto [x, y] = dfs(0, -1);
return max(x, y);
}
};
|
3,367 |
Maximize Sum of Weights after Edge Removals
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p>
<p>Your task is to remove <em>zero or more</em> edges such that:</p>
<ul>
<li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li>
<li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li>
</ul>
<p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p>
<ul>
<li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li>
<li>The sum of weights is 22, and we can't achieve a greater sum. Thus, the answer is 22.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">65</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don't remove any edges.</li>
<li>The sum of weights is 65. Thus, the answer is 65.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n - 1</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code><font face="monospace">0 <= edges[i][0] <= n - 1</font></code></li>
<li><code><font face="monospace">0 <= edges[i][1] <= n - 1</font></code></li>
<li><code><font face="monospace">1 <= edges[i][2] <= 10<sup>6</sup></font></code></li>
<li>The input is generated such that <code>edges</code> form a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Go
|
func maximizeSumOfWeights(edges [][]int, k int) int64 {
n := len(edges) + 1
g := make([][][]int, n)
for _, e := range edges {
u, v, w := e[0], e[1], e[2]
g[u] = append(g[u], []int{v, w})
g[v] = append(g[v], []int{u, w})
}
var dfs func(u, fa int) (int64, int64)
dfs = func(u, fa int) (int64, int64) {
var s int64
var t []int64
for _, e := range g[u] {
v, w := e[0], e[1]
if v == fa {
continue
}
a, b := dfs(v, u)
s += a
d := int64(w) + b - a
if d > 0 {
t = append(t, d)
}
}
sort.Slice(t, func(i, j int) bool {
return t[i] > t[j]
})
for i := 0; i < min(len(t), k-1); i++ {
s += t[i]
}
s2 := s
if len(t) >= k {
s += t[k-1]
}
return s, s2
}
x, y := dfs(0, -1)
return max(x, y)
}
|
3,367 |
Maximize Sum of Weights after Edge Removals
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p>
<p>Your task is to remove <em>zero or more</em> edges such that:</p>
<ul>
<li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li>
<li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li>
</ul>
<p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p>
<ul>
<li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li>
<li>The sum of weights is 22, and we can't achieve a greater sum. Thus, the answer is 22.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">65</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don't remove any edges.</li>
<li>The sum of weights is 65. Thus, the answer is 65.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n - 1</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code><font face="monospace">0 <= edges[i][0] <= n - 1</font></code></li>
<li><code><font face="monospace">0 <= edges[i][1] <= n - 1</font></code></li>
<li><code><font face="monospace">1 <= edges[i][2] <= 10<sup>6</sup></font></code></li>
<li>The input is generated such that <code>edges</code> form a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Java
|
class Solution {
private List<int[]>[] g;
private int k;
public long maximizeSumOfWeights(int[][] edges, int k) {
this.k = k;
int n = edges.length + 1;
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].add(new int[] {v, w});
g[v].add(new int[] {u, w});
}
var ans = dfs(0, -1);
return Math.max(ans[0], ans[1]);
}
private long[] dfs(int u, int fa) {
long s = 0;
List<Long> t = new ArrayList<>();
for (var e : g[u]) {
int v = e[0], w = e[1];
if (v == fa) {
continue;
}
var res = dfs(v, u);
s += res[0];
long d = w + res[1] - res[0];
if (d > 0) {
t.add(d);
}
}
t.sort(Comparator.reverseOrder());
for (int i = 0; i < Math.min(t.size(), k - 1); ++i) {
s += t.get(i);
}
return new long[] {s + (t.size() >= k ? t.get(k - 1) : 0), s};
}
}
|
3,367 |
Maximize Sum of Weights after Edge Removals
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p>
<p>Your task is to remove <em>zero or more</em> edges such that:</p>
<ul>
<li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li>
<li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li>
</ul>
<p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p>
<ul>
<li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li>
<li>The sum of weights is 22, and we can't achieve a greater sum. Thus, the answer is 22.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">65</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don't remove any edges.</li>
<li>The sum of weights is 65. Thus, the answer is 65.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n - 1</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code><font face="monospace">0 <= edges[i][0] <= n - 1</font></code></li>
<li><code><font face="monospace">0 <= edges[i][1] <= n - 1</font></code></li>
<li><code><font face="monospace">1 <= edges[i][2] <= 10<sup>6</sup></font></code></li>
<li>The input is generated such that <code>edges</code> form a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Python
|
class Solution:
def maximizeSumOfWeights(self, edges: List[List[int]], k: int) -> int:
def dfs(u: int, fa: int) -> Tuple[int, int]:
s = 0
t = []
for v, w in g[u]:
if v == fa:
continue
a, b = dfs(v, u)
s += a
if (d := (w + b - a)) > 0:
t.append(d)
t.sort(reverse=True)
return s + sum(t[:k]), s + sum(t[: k - 1])
n = len(edges) + 1
g: List[List[Tuple[int, int]]] = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
x, y = dfs(0, -1)
return max(x, y)
|
3,367 |
Maximize Sum of Weights after Edge Removals
|
Hard
|
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p>
<p>Your task is to remove <em>zero or more</em> edges such that:</p>
<ul>
<li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li>
<li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li>
</ul>
<p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">22</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p>
<ul>
<li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li>
<li>The sum of weights is 22, and we can't achieve a greater sum. Thus, the answer is 22.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">65</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don't remove any edges.</li>
<li>The sum of weights is 65. Thus, the answer is 65.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n - 1</code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 3</code></li>
<li><code><font face="monospace">0 <= edges[i][0] <= n - 1</font></code></li>
<li><code><font face="monospace">0 <= edges[i][1] <= n - 1</font></code></li>
<li><code><font face="monospace">1 <= edges[i][2] <= 10<sup>6</sup></font></code></li>
<li>The input is generated such that <code>edges</code> form a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
TypeScript
|
function maximizeSumOfWeights(edges: number[][], k: number): number {
const n = edges.length + 1;
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (const [u, v, w] of edges) {
g[u].push([v, w]);
g[v].push([u, w]);
}
const dfs = (u: number, fa: number): [number, number] => {
let s = 0;
const t: number[] = [];
for (const [v, w] of g[u]) {
if (v === fa) continue;
const [a, b] = dfs(v, u);
s += a;
const d = w + b - a;
if (d > 0) t.push(d);
}
t.sort((a, b) => b - a);
for (let i = 0; i < Math.min(t.length, k - 1); i++) {
s += t[i];
}
const s2 = s;
if (t.length >= k) {
s += t[k - 1];
}
return [s, s2];
};
const [x, y] = dfs(0, -1);
return Math.max(x, y);
}
|
3,368 |
First Letter Capitalization
|
Hard
|
<p>Table: <code>user_content</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| content_id | int |
| content_text| varchar |
+-------------+---------+
content_id is the unique key for this table.
Each row contains a unique ID and the corresponding text content.
</pre>
<p>Write a solution to transform the text in the <code>content_text</code> column by applying the following rules:</p>
<ul>
<li>Convert the first letter of each word to uppercase</li>
<li>Keep all other letters in lowercase</li>
<li>Preserve all existing spaces</li>
</ul>
<p><strong>Note</strong>: There will be no special character in <code>content_text</code>.</p>
<p>Return <em>the result table that includes both the original <code>content_text</code> and the modified text where each word starts with a capital letter</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>user_content table:</p>
<pre class="example-io">
+------------+-----------------------------------+
| content_id | content_text |
+------------+-----------------------------------+
| 1 | hello world of SQL |
| 2 | the QUICK brown fox |
| 3 | data science AND machine learning |
| 4 | TOP rated programming BOOKS |
+------------+-----------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+-----------------------------------+-----------------------------------+
| content_id | original_text | converted_text |
+------------+-----------------------------------+-----------------------------------+
| 1 | hello world of SQL | Hello World Of Sql |
| 2 | the QUICK brown fox | The Quick Brown Fox |
| 3 | data science AND machine learning | Data Science And Machine Learning |
| 4 | TOP rated programming BOOKS | Top Rated Programming Books |
+------------+-----------------------------------+-----------------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For content_id = 1:
<ul>
<li>Each word's first letter is capitalized: Hello World Of Sql</li>
</ul>
</li>
<li>For content_id = 2:
<ul>
<li>Original mixed-case text is transformed to title case: The Quick Brown Fox</li>
</ul>
</li>
<li>For content_id = 3:
<ul>
<li>The word AND is converted to "And": "Data Science And Machine Learning"</li>
</ul>
</li>
<li>For content_id = 4:
<ul>
<li>Handles word TOP rated correctly: Top Rated</li>
<li>Converts BOOKS from all caps to title case: Books</li>
</ul>
</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def process_text(user_content: pd.DataFrame) -> pd.DataFrame:
user_content["converted_text"] = user_content["content_text"].apply(
lambda text: " ".join(word.capitalize() for word in text.split(" "))
)
return user_content[["content_id", "content_text", "converted_text"]].rename(
columns={"content_text": "original_text"}
)
|
3,368 |
First Letter Capitalization
|
Hard
|
<p>Table: <code>user_content</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| content_id | int |
| content_text| varchar |
+-------------+---------+
content_id is the unique key for this table.
Each row contains a unique ID and the corresponding text content.
</pre>
<p>Write a solution to transform the text in the <code>content_text</code> column by applying the following rules:</p>
<ul>
<li>Convert the first letter of each word to uppercase</li>
<li>Keep all other letters in lowercase</li>
<li>Preserve all existing spaces</li>
</ul>
<p><strong>Note</strong>: There will be no special character in <code>content_text</code>.</p>
<p>Return <em>the result table that includes both the original <code>content_text</code> and the modified text where each word starts with a capital letter</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>user_content table:</p>
<pre class="example-io">
+------------+-----------------------------------+
| content_id | content_text |
+------------+-----------------------------------+
| 1 | hello world of SQL |
| 2 | the QUICK brown fox |
| 3 | data science AND machine learning |
| 4 | TOP rated programming BOOKS |
+------------+-----------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+-----------------------------------+-----------------------------------+
| content_id | original_text | converted_text |
+------------+-----------------------------------+-----------------------------------+
| 1 | hello world of SQL | Hello World Of Sql |
| 2 | the QUICK brown fox | The Quick Brown Fox |
| 3 | data science AND machine learning | Data Science And Machine Learning |
| 4 | TOP rated programming BOOKS | Top Rated Programming Books |
+------------+-----------------------------------+-----------------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For content_id = 1:
<ul>
<li>Each word's first letter is capitalized: Hello World Of Sql</li>
</ul>
</li>
<li>For content_id = 2:
<ul>
<li>Original mixed-case text is transformed to title case: The Quick Brown Fox</li>
</ul>
</li>
<li>For content_id = 3:
<ul>
<li>The word AND is converted to "And": "Data Science And Machine Learning"</li>
</ul>
</li>
<li>For content_id = 4:
<ul>
<li>Handles word TOP rated correctly: Top Rated</li>
<li>Converts BOOKS from all caps to title case: Books</li>
</ul>
</li>
</ul>
</div>
|
Database
|
SQL
|
WITH RECURSIVE
capitalized_words AS (
SELECT
content_id,
content_text,
SUBSTRING_INDEX(content_text, ' ', 1) AS word,
SUBSTRING(
content_text,
LENGTH(SUBSTRING_INDEX(content_text, ' ', 1)) + 2
) AS remaining_text,
CONCAT(
UPPER(LEFT(SUBSTRING_INDEX(content_text, ' ', 1), 1)),
LOWER(SUBSTRING(SUBSTRING_INDEX(content_text, ' ', 1), 2))
) AS processed_word
FROM user_content
UNION ALL
SELECT
c.content_id,
c.content_text,
SUBSTRING_INDEX(c.remaining_text, ' ', 1),
SUBSTRING(c.remaining_text, LENGTH(SUBSTRING_INDEX(c.remaining_text, ' ', 1)) + 2),
CONCAT(
c.processed_word,
' ',
CONCAT(
UPPER(LEFT(SUBSTRING_INDEX(c.remaining_text, ' ', 1), 1)),
LOWER(SUBSTRING(SUBSTRING_INDEX(c.remaining_text, ' ', 1), 2))
)
)
FROM capitalized_words c
WHERE c.remaining_text != ''
)
SELECT
content_id,
content_text AS original_text,
MAX(processed_word) AS converted_text
FROM capitalized_words
GROUP BY 1, 2;
|
3,369 |
Design an Array Statistics Tracker
|
Hard
|
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their mean, median, and mode.</p>
<p>Implement the <code>StatisticsTracker</code> class.</p>
<ul>
<li><code>StatisticsTracker()</code>: Initialize the <code>StatisticsTracker</code> object with an empty array.</li>
<li><code>void addNumber(int number)</code>: Add <code>number</code> to the data structure.</li>
<li><code>void removeFirstAddedNumber()</code>: Remove the earliest added number from the data structure.</li>
<li><code>int getMean()</code>: Return the floored <strong>mean</strong> of the numbers in the data structure.</li>
<li><code>int getMedian()</code>: Return the <strong>median</strong> of the numbers in the data structure.</li>
<li><code>int getMode()</code>: Return the <strong>mode</strong> of the numbers in the data structure. If there are multiple modes, return the smallest one.</li>
</ul>
<p><strong>Note</strong>:</p>
<ul>
<li>The <strong>mean</strong> of an array is the sum of all the values divided by the number of values in the array.</li>
<li>The <strong>median</strong> of an array is 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.</li>
<li>The <strong>mode</strong> of an array is the element that appears most often in the array.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "addNumber", "addNumber", "getMean", "getMedian", "getMode", "removeFirstAddedNumber", "getMode"]<br />
[[], [4], [4], [2], [3], [], [], [], [], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, null, null, 3, 4, 4, null, 2] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(4); // The data structure now contains [4]<br />
statisticsTracker.addNumber(4); // The data structure now contains [4, 4]<br />
statisticsTracker.addNumber(2); // The data structure now contains [4, 4, 2]<br />
statisticsTracker.addNumber(3); // The data structure now contains [4, 4, 2, 3]<br />
statisticsTracker.getMean(); // return 3<br />
statisticsTracker.getMedian(); // return 4<br />
statisticsTracker.getMode(); // return 4<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [4, 2, 3]<br />
statisticsTracker.getMode(); // return 2</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "getMean", "removeFirstAddedNumber", "addNumber", "addNumber", "removeFirstAddedNumber", "getMedian", "addNumber", "getMode"]<br />
[[], [9], [5], [], [], [5], [6], [], [], [8], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 7, null, null, null, null, 6, null, 5] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(9); // The data structure now contains [9]<br />
statisticsTracker.addNumber(5); // The data structure now contains [9, 5]<br />
statisticsTracker.getMean(); // return 7<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5]<br />
statisticsTracker.addNumber(5); // The data structure now contains [5, 5]<br />
statisticsTracker.addNumber(6); // The data structure now contains [5, 5, 6]<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5, 6]<br />
statisticsTracker.getMedian(); // return 6<br />
statisticsTracker.addNumber(8); // The data structure now contains [5, 6, 8]<br />
statisticsTracker.getMode(); // return 5</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= number <= 10<sup>9</sup></code></li>
<li>At most, <code>10<sup>5</sup></code> calls will be made to <code>addNumber</code>, <code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> in total.</li>
<li><code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> will be called only if there is at least one element in the data structure.</li>
</ul>
|
Design; Queue; Hash Table; Binary Search; Data Stream; Ordered Set; Heap (Priority Queue)
|
C++
|
class MedianFinder {
public:
void addNum(int num) {
if (small.empty() || num <= small.top()) {
small.push(num);
++smallSize;
} else {
large.push(num);
++largeSize;
}
reblance();
}
void removeNum(int num) {
++delayed[num];
if (num <= small.top()) {
--smallSize;
if (num == small.top()) {
prune(small);
}
} else {
--largeSize;
if (num == large.top()) {
prune(large);
}
}
reblance();
}
int findMedian() {
return smallSize == largeSize ? large.top() : small.top();
}
private:
priority_queue<int> small;
priority_queue<int, vector<int>, greater<int>> large;
unordered_map<int, int> delayed;
int smallSize = 0;
int largeSize = 0;
template <typename T>
void prune(T& pq) {
while (!pq.empty() && delayed[pq.top()]) {
if (--delayed[pq.top()] == 0) {
delayed.erase(pq.top());
}
pq.pop();
}
}
void reblance() {
if (smallSize > largeSize + 1) {
large.push(small.top());
small.pop();
--smallSize;
++largeSize;
prune(small);
} else if (smallSize < largeSize) {
small.push(large.top());
large.pop();
++smallSize;
--largeSize;
prune(large);
}
}
};
class StatisticsTracker {
private:
queue<int> q;
long long s = 0;
unordered_map<int, int> cnt;
MedianFinder medianFinder;
set<pair<int, int>> ts;
public:
StatisticsTracker() {}
void addNumber(int number) {
q.push(number);
s += number;
ts.erase({-cnt[number], number});
cnt[number]++;
medianFinder.addNum(number);
ts.insert({-cnt[number], number});
}
void removeFirstAddedNumber() {
int number = q.front();
q.pop();
s -= number;
ts.erase({-cnt[number], number});
cnt[number]--;
if (cnt[number] > 0) {
ts.insert({-cnt[number], number});
}
medianFinder.removeNum(number);
}
int getMean() {
return static_cast<int>(s / q.size());
}
int getMedian() {
return medianFinder.findMedian();
}
int getMode() {
return ts.begin()->second;
}
};
|
3,369 |
Design an Array Statistics Tracker
|
Hard
|
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their mean, median, and mode.</p>
<p>Implement the <code>StatisticsTracker</code> class.</p>
<ul>
<li><code>StatisticsTracker()</code>: Initialize the <code>StatisticsTracker</code> object with an empty array.</li>
<li><code>void addNumber(int number)</code>: Add <code>number</code> to the data structure.</li>
<li><code>void removeFirstAddedNumber()</code>: Remove the earliest added number from the data structure.</li>
<li><code>int getMean()</code>: Return the floored <strong>mean</strong> of the numbers in the data structure.</li>
<li><code>int getMedian()</code>: Return the <strong>median</strong> of the numbers in the data structure.</li>
<li><code>int getMode()</code>: Return the <strong>mode</strong> of the numbers in the data structure. If there are multiple modes, return the smallest one.</li>
</ul>
<p><strong>Note</strong>:</p>
<ul>
<li>The <strong>mean</strong> of an array is the sum of all the values divided by the number of values in the array.</li>
<li>The <strong>median</strong> of an array is 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.</li>
<li>The <strong>mode</strong> of an array is the element that appears most often in the array.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "addNumber", "addNumber", "getMean", "getMedian", "getMode", "removeFirstAddedNumber", "getMode"]<br />
[[], [4], [4], [2], [3], [], [], [], [], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, null, null, 3, 4, 4, null, 2] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(4); // The data structure now contains [4]<br />
statisticsTracker.addNumber(4); // The data structure now contains [4, 4]<br />
statisticsTracker.addNumber(2); // The data structure now contains [4, 4, 2]<br />
statisticsTracker.addNumber(3); // The data structure now contains [4, 4, 2, 3]<br />
statisticsTracker.getMean(); // return 3<br />
statisticsTracker.getMedian(); // return 4<br />
statisticsTracker.getMode(); // return 4<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [4, 2, 3]<br />
statisticsTracker.getMode(); // return 2</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "getMean", "removeFirstAddedNumber", "addNumber", "addNumber", "removeFirstAddedNumber", "getMedian", "addNumber", "getMode"]<br />
[[], [9], [5], [], [], [5], [6], [], [], [8], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 7, null, null, null, null, 6, null, 5] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(9); // The data structure now contains [9]<br />
statisticsTracker.addNumber(5); // The data structure now contains [9, 5]<br />
statisticsTracker.getMean(); // return 7<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5]<br />
statisticsTracker.addNumber(5); // The data structure now contains [5, 5]<br />
statisticsTracker.addNumber(6); // The data structure now contains [5, 5, 6]<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5, 6]<br />
statisticsTracker.getMedian(); // return 6<br />
statisticsTracker.addNumber(8); // The data structure now contains [5, 6, 8]<br />
statisticsTracker.getMode(); // return 5</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= number <= 10<sup>9</sup></code></li>
<li>At most, <code>10<sup>5</sup></code> calls will be made to <code>addNumber</code>, <code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> in total.</li>
<li><code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> will be called only if there is at least one element in the data structure.</li>
</ul>
|
Design; Queue; Hash Table; Binary Search; Data Stream; Ordered Set; Heap (Priority Queue)
|
Java
|
class MedianFinder {
private final PriorityQueue<Integer> small = new PriorityQueue<>(Comparator.reverseOrder());
private final PriorityQueue<Integer> large = new PriorityQueue<>();
private final Map<Integer, Integer> delayed = new HashMap<>();
private int smallSize;
private int largeSize;
public void addNum(int num) {
if (small.isEmpty() || num <= small.peek()) {
small.offer(num);
++smallSize;
} else {
large.offer(num);
++largeSize;
}
rebalance();
}
public Integer findMedian() {
return smallSize == largeSize ? large.peek() : small.peek();
}
public void removeNum(int num) {
delayed.merge(num, 1, Integer::sum);
if (num <= small.peek()) {
--smallSize;
if (num == small.peek()) {
prune(small);
}
} else {
--largeSize;
if (num == large.peek()) {
prune(large);
}
}
rebalance();
}
private void prune(PriorityQueue<Integer> pq) {
while (!pq.isEmpty() && delayed.containsKey(pq.peek())) {
if (delayed.merge(pq.peek(), -1, Integer::sum) == 0) {
delayed.remove(pq.peek());
}
pq.poll();
}
}
private void rebalance() {
if (smallSize > largeSize + 1) {
large.offer(small.poll());
--smallSize;
++largeSize;
prune(small);
} else if (smallSize < largeSize) {
small.offer(large.poll());
--largeSize;
++smallSize;
prune(large);
}
}
}
class StatisticsTracker {
private final Deque<Integer> q = new ArrayDeque<>();
private long s;
private final Map<Integer, Integer> cnt = new HashMap<>();
private final MedianFinder medianFinder = new MedianFinder();
private final TreeSet<int[]> ts
= new TreeSet<>((a, b) -> a[1] == b[1] ? a[0] - b[0] : b[1] - a[1]);
public StatisticsTracker() {
}
public void addNumber(int number) {
q.offerLast(number);
s += number;
ts.remove(new int[] {number, cnt.getOrDefault(number, 0)});
cnt.merge(number, 1, Integer::sum);
medianFinder.addNum(number);
ts.add(new int[] {number, cnt.get(number)});
}
public void removeFirstAddedNumber() {
int number = q.pollFirst();
s -= number;
ts.remove(new int[] {number, cnt.get(number)});
cnt.merge(number, -1, Integer::sum);
medianFinder.removeNum(number);
ts.add(new int[] {number, cnt.get(number)});
}
public int getMean() {
return (int) (s / q.size());
}
public int getMedian() {
return medianFinder.findMedian();
}
public int getMode() {
return ts.first()[0];
}
}
|
3,369 |
Design an Array Statistics Tracker
|
Hard
|
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their mean, median, and mode.</p>
<p>Implement the <code>StatisticsTracker</code> class.</p>
<ul>
<li><code>StatisticsTracker()</code>: Initialize the <code>StatisticsTracker</code> object with an empty array.</li>
<li><code>void addNumber(int number)</code>: Add <code>number</code> to the data structure.</li>
<li><code>void removeFirstAddedNumber()</code>: Remove the earliest added number from the data structure.</li>
<li><code>int getMean()</code>: Return the floored <strong>mean</strong> of the numbers in the data structure.</li>
<li><code>int getMedian()</code>: Return the <strong>median</strong> of the numbers in the data structure.</li>
<li><code>int getMode()</code>: Return the <strong>mode</strong> of the numbers in the data structure. If there are multiple modes, return the smallest one.</li>
</ul>
<p><strong>Note</strong>:</p>
<ul>
<li>The <strong>mean</strong> of an array is the sum of all the values divided by the number of values in the array.</li>
<li>The <strong>median</strong> of an array is 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.</li>
<li>The <strong>mode</strong> of an array is the element that appears most often in the array.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "addNumber", "addNumber", "getMean", "getMedian", "getMode", "removeFirstAddedNumber", "getMode"]<br />
[[], [4], [4], [2], [3], [], [], [], [], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, null, null, 3, 4, 4, null, 2] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(4); // The data structure now contains [4]<br />
statisticsTracker.addNumber(4); // The data structure now contains [4, 4]<br />
statisticsTracker.addNumber(2); // The data structure now contains [4, 4, 2]<br />
statisticsTracker.addNumber(3); // The data structure now contains [4, 4, 2, 3]<br />
statisticsTracker.getMean(); // return 3<br />
statisticsTracker.getMedian(); // return 4<br />
statisticsTracker.getMode(); // return 4<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [4, 2, 3]<br />
statisticsTracker.getMode(); // return 2</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["StatisticsTracker", "addNumber", "addNumber", "getMean", "removeFirstAddedNumber", "addNumber", "addNumber", "removeFirstAddedNumber", "getMedian", "addNumber", "getMode"]<br />
[[], [9], [5], [], [], [5], [6], [], [], [8], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 7, null, null, null, null, 6, null, 5] </span></p>
<p><strong>Explanation</strong></p>
StatisticsTracker statisticsTracker = new StatisticsTracker();<br />
statisticsTracker.addNumber(9); // The data structure now contains [9]<br />
statisticsTracker.addNumber(5); // The data structure now contains [9, 5]<br />
statisticsTracker.getMean(); // return 7<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5]<br />
statisticsTracker.addNumber(5); // The data structure now contains [5, 5]<br />
statisticsTracker.addNumber(6); // The data structure now contains [5, 5, 6]<br />
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5, 6]<br />
statisticsTracker.getMedian(); // return 6<br />
statisticsTracker.addNumber(8); // The data structure now contains [5, 6, 8]<br />
statisticsTracker.getMode(); // return 5</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= number <= 10<sup>9</sup></code></li>
<li>At most, <code>10<sup>5</sup></code> calls will be made to <code>addNumber</code>, <code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> in total.</li>
<li><code>removeFirstAddedNumber</code>, <code>getMean</code>, <code>getMedian</code>, and <code>getMode</code> will be called only if there is at least one element in the data structure.</li>
</ul>
|
Design; Queue; Hash Table; Binary Search; Data Stream; Ordered Set; Heap (Priority Queue)
|
Python
|
class StatisticsTracker:
def __init__(self):
self.q = deque()
self.s = 0
self.cnt = defaultdict(int)
self.sl = SortedList()
self.sl2 = SortedList(key=lambda x: (-x[1], x[0]))
def addNumber(self, number: int) -> None:
self.q.append(number)
self.sl.add(number)
self.sl2.discard((number, self.cnt[number]))
self.cnt[number] += 1
self.sl2.add((number, self.cnt[number]))
self.s += number
def removeFirstAddedNumber(self) -> None:
number = self.q.popleft()
self.sl.remove(number)
self.sl2.discard((number, self.cnt[number]))
self.cnt[number] -= 1
self.sl2.add((number, self.cnt[number]))
self.s -= number
def getMean(self) -> int:
return self.s // len(self.q)
def getMedian(self) -> int:
return self.sl[len(self.q) // 2]
def getMode(self) -> int:
return self.sl2[0][0]
# Your StatisticsTracker object will be instantiated and called as such:
# obj = StatisticsTracker()
# obj.addNumber(number)
# obj.removeFirstAddedNumber()
# param_3 = obj.getMean()
# param_4 = obj.getMedian()
# param_5 = obj.getMode()
|
3,370 |
Smallest Number With All Set Bits
|
Easy
|
<p>You are given a <em>positive</em> number <code>n</code>.</p>
<p>Return the <strong>smallest</strong> number <code>x</code> <strong>greater than</strong> or <strong>equal to</strong> <code>n</code>, such that the binary representation of <code>x</code> contains only <span data-keyword="set-bit">set bits</span></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 7 is <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 15 is <code>"1111"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 3 is <code>"11"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation; Math
|
C++
|
class Solution {
public:
int smallestNumber(int n) {
int x = 1;
while (x - 1 < n) {
x <<= 1;
}
return x - 1;
}
};
|
3,370 |
Smallest Number With All Set Bits
|
Easy
|
<p>You are given a <em>positive</em> number <code>n</code>.</p>
<p>Return the <strong>smallest</strong> number <code>x</code> <strong>greater than</strong> or <strong>equal to</strong> <code>n</code>, such that the binary representation of <code>x</code> contains only <span data-keyword="set-bit">set bits</span></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 7 is <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 15 is <code>"1111"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 3 is <code>"11"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation; Math
|
Go
|
func smallestNumber(n int) int {
x := 1
for x-1 < n {
x <<= 1
}
return x - 1
}
|
3,370 |
Smallest Number With All Set Bits
|
Easy
|
<p>You are given a <em>positive</em> number <code>n</code>.</p>
<p>Return the <strong>smallest</strong> number <code>x</code> <strong>greater than</strong> or <strong>equal to</strong> <code>n</code>, such that the binary representation of <code>x</code> contains only <span data-keyword="set-bit">set bits</span></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 7 is <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 15 is <code>"1111"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 3 is <code>"11"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation; Math
|
Java
|
class Solution {
public int smallestNumber(int n) {
int x = 1;
while (x - 1 < n) {
x <<= 1;
}
return x - 1;
}
}
|
3,370 |
Smallest Number With All Set Bits
|
Easy
|
<p>You are given a <em>positive</em> number <code>n</code>.</p>
<p>Return the <strong>smallest</strong> number <code>x</code> <strong>greater than</strong> or <strong>equal to</strong> <code>n</code>, such that the binary representation of <code>x</code> contains only <span data-keyword="set-bit">set bits</span></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 7 is <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 15 is <code>"1111"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 3 is <code>"11"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation; Math
|
Python
|
class Solution:
def smallestNumber(self, n: int) -> int:
x = 1
while x - 1 < n:
x <<= 1
return x - 1
|
3,370 |
Smallest Number With All Set Bits
|
Easy
|
<p>You are given a <em>positive</em> number <code>n</code>.</p>
<p>Return the <strong>smallest</strong> number <code>x</code> <strong>greater than</strong> or <strong>equal to</strong> <code>n</code>, such that the binary representation of <code>x</code> contains only <span data-keyword="set-bit">set bits</span></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 7 is <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 15 is <code>"1111"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 3 is <code>"11"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation; Math
|
TypeScript
|
function smallestNumber(n: number): number {
let x = 1;
while (x - 1 < n) {
x <<= 1;
}
return x - 1;
}
|
3,371 |
Identify the Largest Outlier in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>. This array contains <code>n</code> elements, where <strong>exactly</strong> <code>n - 2</code> elements are <strong>special</strong><strong> numbers</strong>. One of the remaining <strong>two</strong> elements is the <em>sum</em> of these <strong>special numbers</strong>, and the other is an <strong>outlier</strong>.</p>
<p>An <strong>outlier</strong> is defined as a number that is <em>neither</em> one of the original special numbers <em>nor</em> the element representing the sum of those numbers.</p>
<p><strong>Note</strong> that special numbers, the sum element, and the outlier must have <strong>distinct</strong> indices, but <em>may </em>share the <strong>same</strong> value.</p>
<p>Return the <strong>largest</strong><strong> </strong>potential<strong> outlier</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-2,-1,-3,-6,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li>The input is generated such that at least <strong>one</strong> potential outlier exists in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Counting; Enumeration
|
C++
|
class Solution {
public:
int getLargestOutlier(vector<int>& nums) {
int s = 0;
unordered_map<int, int> cnt;
for (int x : nums) {
s += x;
cnt[x]++;
}
int ans = INT_MIN;
for (auto [x, v] : cnt) {
int t = s - x;
if (t % 2 || !cnt.contains(t / 2)) {
continue;
}
if (x != t / 2 || v > 1) {
ans = max(ans, x);
}
}
return ans;
}
};
|
3,371 |
Identify the Largest Outlier in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>. This array contains <code>n</code> elements, where <strong>exactly</strong> <code>n - 2</code> elements are <strong>special</strong><strong> numbers</strong>. One of the remaining <strong>two</strong> elements is the <em>sum</em> of these <strong>special numbers</strong>, and the other is an <strong>outlier</strong>.</p>
<p>An <strong>outlier</strong> is defined as a number that is <em>neither</em> one of the original special numbers <em>nor</em> the element representing the sum of those numbers.</p>
<p><strong>Note</strong> that special numbers, the sum element, and the outlier must have <strong>distinct</strong> indices, but <em>may </em>share the <strong>same</strong> value.</p>
<p>Return the <strong>largest</strong><strong> </strong>potential<strong> outlier</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-2,-1,-3,-6,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li>The input is generated such that at least <strong>one</strong> potential outlier exists in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Counting; Enumeration
|
Go
|
func getLargestOutlier(nums []int) int {
s := 0
cnt := map[int]int{}
for _, x := range nums {
s += x
cnt[x]++
}
ans := math.MinInt32
for x, v := range cnt {
t := s - x
if t%2 != 0 || cnt[t/2] == 0 {
continue
}
if x != t/2 || v > 1 {
ans = max(ans, x)
}
}
return ans
}
|
3,371 |
Identify the Largest Outlier in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>. This array contains <code>n</code> elements, where <strong>exactly</strong> <code>n - 2</code> elements are <strong>special</strong><strong> numbers</strong>. One of the remaining <strong>two</strong> elements is the <em>sum</em> of these <strong>special numbers</strong>, and the other is an <strong>outlier</strong>.</p>
<p>An <strong>outlier</strong> is defined as a number that is <em>neither</em> one of the original special numbers <em>nor</em> the element representing the sum of those numbers.</p>
<p><strong>Note</strong> that special numbers, the sum element, and the outlier must have <strong>distinct</strong> indices, but <em>may </em>share the <strong>same</strong> value.</p>
<p>Return the <strong>largest</strong><strong> </strong>potential<strong> outlier</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-2,-1,-3,-6,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li>The input is generated such that at least <strong>one</strong> potential outlier exists in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Counting; Enumeration
|
Java
|
class Solution {
public int getLargestOutlier(int[] nums) {
int s = 0;
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
s += x;
cnt.merge(x, 1, Integer::sum);
}
int ans = Integer.MIN_VALUE;
for (var e : cnt.entrySet()) {
int x = e.getKey(), v = e.getValue();
int t = s - x;
if (t % 2 != 0 || !cnt.containsKey(t / 2)) {
continue;
}
if (x != t / 2 || v > 1) {
ans = Math.max(ans, x);
}
}
return ans;
}
}
|
3,371 |
Identify the Largest Outlier in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>. This array contains <code>n</code> elements, where <strong>exactly</strong> <code>n - 2</code> elements are <strong>special</strong><strong> numbers</strong>. One of the remaining <strong>two</strong> elements is the <em>sum</em> of these <strong>special numbers</strong>, and the other is an <strong>outlier</strong>.</p>
<p>An <strong>outlier</strong> is defined as a number that is <em>neither</em> one of the original special numbers <em>nor</em> the element representing the sum of those numbers.</p>
<p><strong>Note</strong> that special numbers, the sum element, and the outlier must have <strong>distinct</strong> indices, but <em>may </em>share the <strong>same</strong> value.</p>
<p>Return the <strong>largest</strong><strong> </strong>potential<strong> outlier</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-2,-1,-3,-6,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li>The input is generated such that at least <strong>one</strong> potential outlier exists in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Counting; Enumeration
|
Python
|
class Solution:
def getLargestOutlier(self, nums: List[int]) -> int:
s = sum(nums)
cnt = Counter(nums)
ans = -inf
for x, v in cnt.items():
t = s - x
if t % 2 or cnt[t // 2] == 0:
continue
if x != t // 2 or v > 1:
ans = max(ans, x)
return ans
|
3,371 |
Identify the Largest Outlier in an Array
|
Medium
|
<p>You are given an integer array <code>nums</code>. This array contains <code>n</code> elements, where <strong>exactly</strong> <code>n - 2</code> elements are <strong>special</strong><strong> numbers</strong>. One of the remaining <strong>two</strong> elements is the <em>sum</em> of these <strong>special numbers</strong>, and the other is an <strong>outlier</strong>.</p>
<p>An <strong>outlier</strong> is defined as a number that is <em>neither</em> one of the original special numbers <em>nor</em> the element representing the sum of those numbers.</p>
<p><strong>Note</strong> that special numbers, the sum element, and the outlier must have <strong>distinct</strong> indices, but <em>may </em>share the <strong>same</strong> value.</p>
<p>Return the <strong>largest</strong><strong> </strong>potential<strong> outlier</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,10]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-2,-1,-3,-6,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1,5,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-1000 <= nums[i] <= 1000</code></li>
<li>The input is generated such that at least <strong>one</strong> potential outlier exists in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Counting; Enumeration
|
TypeScript
|
function getLargestOutlier(nums: number[]): number {
let s = 0;
const cnt: Record<number, number> = {};
for (const x of nums) {
s += x;
cnt[x] = (cnt[x] || 0) + 1;
}
let ans = -Infinity;
for (const [x, v] of Object.entries(cnt)) {
const t = s - +x;
if (t % 2 || !cnt.hasOwnProperty((t / 2) | 0)) {
continue;
}
if (+x != ((t / 2) | 0) || v > 1) {
ans = Math.max(ans, +x);
}
}
return ans;
}
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
C++
|
class Solution {
public:
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2, int k) {
auto g2 = build(edges2);
int m = edges2.size() + 1;
int t = 0;
for (int i = 0; i < m; ++i) {
t = max(t, dfs(g2, i, -1, k - 1));
}
auto g1 = build(edges1);
int n = edges1.size() + 1;
vector<int> ans(n, t);
for (int i = 0; i < n; ++i) {
ans[i] += dfs(g1, i, -1, k);
}
return ans;
}
private:
vector<vector<int>> build(const vector<vector<int>>& edges) {
int n = edges.size() + 1;
vector<vector<int>> g(n);
for (const auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
return g;
}
int dfs(const vector<vector<int>>& g, int a, int fa, int d) {
if (d < 0) {
return 0;
}
int cnt = 1;
for (int b : g[a]) {
if (b != fa) {
cnt += dfs(g, b, a, d - 1);
}
}
return cnt;
}
};
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
C#
|
public class Solution {
public int[] MaxTargetNodes(int[][] edges1, int[][] edges2, int k) {
var g2 = Build(edges2);
int m = edges2.Length + 1;
int t = 0;
for (int i = 0; i < m; i++) {
t = Math.Max(t, Dfs(g2, i, -1, k - 1));
}
var g1 = Build(edges1);
int n = edges1.Length + 1;
var ans = new int[n];
Array.Fill(ans, t);
for (int i = 0; i < n; i++) {
ans[i] += Dfs(g1, i, -1, k);
}
return ans;
}
private List<int>[] Build(int[][] edges) {
int n = edges.Length + 1;
var g = new List<int>[n];
for (int i = 0; i < n; i++) {
g[i] = new List<int>();
}
foreach (var e in edges) {
int a = e[0], b = e[1];
g[a].Add(b);
g[b].Add(a);
}
return g;
}
private int Dfs(List<int>[] g, int a, int fa, int d) {
if (d < 0) {
return 0;
}
int cnt = 1;
foreach (var b in g[a]) {
if (b != fa) {
cnt += Dfs(g, b, a, d - 1);
}
}
return cnt;
}
}
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Go
|
func maxTargetNodes(edges1 [][]int, edges2 [][]int, k int) []int {
g2 := build(edges2)
m := len(edges2) + 1
t := 0
for i := 0; i < m; i++ {
t = max(t, dfs(g2, i, -1, k-1))
}
g1 := build(edges1)
n := len(edges1) + 1
ans := make([]int, n)
for i := 0; i < n; i++ {
ans[i] = t + dfs(g1, i, -1, k)
}
return ans
}
func build(edges [][]int) [][]int {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
return g
}
func dfs(g [][]int, a, fa, d int) int {
if d < 0 {
return 0
}
cnt := 1
for _, b := range g[a] {
if b != fa {
cnt += dfs(g, b, a, d-1)
}
}
return cnt
}
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Java
|
class Solution {
public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {
var g2 = build(edges2);
int m = edges2.length + 1;
int t = 0;
for (int i = 0; i < m; ++i) {
t = Math.max(t, dfs(g2, i, -1, k - 1));
}
var g1 = build(edges1);
int n = edges1.length + 1;
int[] ans = new int[n];
Arrays.fill(ans, t);
for (int i = 0; i < n; ++i) {
ans[i] += dfs(g1, i, -1, k);
}
return ans;
}
private List<Integer>[] build(int[][] edges) {
int n = edges.length + 1;
List<Integer>[] g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
return g;
}
private int dfs(List<Integer>[] g, int a, int fa, int d) {
if (d < 0) {
return 0;
}
int cnt = 1;
for (int b : g[a]) {
if (b != fa) {
cnt += dfs(g, b, a, d - 1);
}
}
return cnt;
}
}
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Python
|
class Solution:
def maxTargetNodes(
self, edges1: List[List[int]], edges2: List[List[int]], k: int
) -> List[int]:
def build(edges: List[List[int]]) -> List[List[int]]:
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
return g
def dfs(g: List[List[int]], a: int, fa: int, d: int) -> int:
if d < 0:
return 0
cnt = 1
for b in g[a]:
if b != fa:
cnt += dfs(g, b, a, d - 1)
return cnt
g2 = build(edges2)
m = len(edges2) + 1
t = max(dfs(g2, i, -1, k - 1) for i in range(m))
g1 = build(edges1)
n = len(edges1) + 1
return [dfs(g1, i, -1, k) + t for i in range(n)]
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Rust
|
impl Solution {
pub fn max_target_nodes(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>, k: i32) -> Vec<i32> {
fn build(edges: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = edges.len() + 1;
let mut g = vec![vec![]; n];
for e in edges {
let a = e[0] as usize;
let b = e[1] as usize;
g[a].push(b as i32);
g[b].push(a as i32);
}
g
}
fn dfs(g: &Vec<Vec<i32>>, a: usize, fa: i32, d: i32) -> i32 {
if d < 0 {
return 0;
}
let mut cnt = 1;
for &b in &g[a] {
if b != fa {
cnt += dfs(g, b as usize, a as i32, d - 1);
}
}
cnt
}
let g2 = build(&edges2);
let m = edges2.len() + 1;
let mut t = 0;
for i in 0..m {
t = t.max(dfs(&g2, i, -1, k - 1));
}
let g1 = build(&edges1);
let n = edges1.len() + 1;
let mut ans = vec![t; n];
for i in 0..n {
ans[i] += dfs(&g1, i, -1, k);
}
ans
}
}
|
3,372 |
Maximize the Number of Target Nodes After Connecting Trees I
|
Medium
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, with <strong>distinct</strong> labels in ranges <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree. You are also given an integer <code>k</code>.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is less than or equal to <code>k</code>. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes <strong>target</strong> to node <code>i</code> of the first tree if you have to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[9,7,9,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[6,3,3,3,3]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3372.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20I/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 1000</code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
<li><code>0 <= k <= 1000</code></li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
TypeScript
|
function maxTargetNodes(edges1: number[][], edges2: number[][], k: number): number[] {
const g2 = build(edges2);
const m = edges2.length + 1;
let t = 0;
for (let i = 0; i < m; i++) {
t = Math.max(t, dfs(g2, i, -1, k - 1));
}
const g1 = build(edges1);
const n = edges1.length + 1;
const ans = Array(n).fill(t);
for (let i = 0; i < n; i++) {
ans[i] += dfs(g1, i, -1, k);
}
return ans;
}
function build(edges: number[][]): number[][] {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
return g;
}
function dfs(g: number[][], a: number, fa: number, d: number): number {
if (d < 0) {
return 0;
}
let cnt = 1;
for (const b of g[a]) {
if (b !== fa) {
cnt += dfs(g, b, a, d - 1);
}
}
return cnt;
}
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
C++
|
class Solution {
public:
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2) {
auto g1 = build(edges1);
auto g2 = build(edges2);
int n = g1.size(), m = g2.size();
vector<int> c1(n, 0), c2(m, 0);
vector<int> cnt1(2, 0), cnt2(2, 0);
dfs(g2, 0, -1, c2, 0, cnt2);
dfs(g1, 0, -1, c1, 0, cnt1);
int t = max(cnt2[0], cnt2[1]);
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ans[i] = t + cnt1[c1[i]];
}
return ans;
}
private:
vector<vector<int>> build(const vector<vector<int>>& edges) {
int n = edges.size() + 1;
vector<vector<int>> g(n);
for (const auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
return g;
}
void dfs(const vector<vector<int>>& g, int a, int fa, vector<int>& c, int d, vector<int>& cnt) {
c[a] = d;
cnt[d]++;
for (int b : g[a]) {
if (b != fa) {
dfs(g, b, a, c, d ^ 1, cnt);
}
}
}
};
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
C#
|
public class Solution {
public int[] MaxTargetNodes(int[][] edges1, int[][] edges2) {
var g1 = Build(edges1);
var g2 = Build(edges2);
int n = g1.Length, m = g2.Length;
var c1 = new int[n];
var c2 = new int[m];
var cnt1 = new int[2];
var cnt2 = new int[2];
Dfs(g2, 0, -1, c2, 0, cnt2);
Dfs(g1, 0, -1, c1, 0, cnt1);
int t = Math.Max(cnt2[0], cnt2[1]);
var ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = t + cnt1[c1[i]];
}
return ans;
}
private List<int>[] Build(int[][] edges) {
int n = edges.Length + 1;
var g = new List<int>[n];
for (int i = 0; i < n; i++) {
g[i] = new List<int>();
}
foreach (var e in edges) {
int a = e[0], b = e[1];
g[a].Add(b);
g[b].Add(a);
}
return g;
}
private void Dfs(List<int>[] g, int a, int fa, int[] c, int d, int[] cnt) {
c[a] = d;
cnt[d]++;
foreach (var b in g[a]) {
if (b != fa) {
Dfs(g, b, a, c, d ^ 1, cnt);
}
}
}
}
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Go
|
func maxTargetNodes(edges1 [][]int, edges2 [][]int) []int {
g1 := build(edges1)
g2 := build(edges2)
n, m := len(g1), len(g2)
c1 := make([]int, n)
c2 := make([]int, m)
cnt1 := make([]int, 2)
cnt2 := make([]int, 2)
dfs(g2, 0, -1, c2, 0, cnt2)
dfs(g1, 0, -1, c1, 0, cnt1)
t := max(cnt2[0], cnt2[1])
ans := make([]int, n)
for i := 0; i < n; i++ {
ans[i] = t + cnt1[c1[i]]
}
return ans
}
func build(edges [][]int) [][]int {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
return g
}
func dfs(g [][]int, a, fa int, c []int, d int, cnt []int) {
c[a] = d
cnt[d]++
for _, b := range g[a] {
if b != fa {
dfs(g, b, a, c, d^1, cnt)
}
}
}
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Java
|
class Solution {
public int[] maxTargetNodes(int[][] edges1, int[][] edges2) {
var g1 = build(edges1);
var g2 = build(edges2);
int n = g1.length, m = g2.length;
int[] c1 = new int[n];
int[] c2 = new int[m];
int[] cnt1 = new int[2];
int[] cnt2 = new int[2];
dfs(g2, 0, -1, c2, 0, cnt2);
dfs(g1, 0, -1, c1, 0, cnt1);
int t = Math.max(cnt2[0], cnt2[1]);
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = t + cnt1[c1[i]];
}
return ans;
}
private List<Integer>[] build(int[][] edges) {
int n = edges.length + 1;
List<Integer>[] g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
return g;
}
private void dfs(List<Integer>[] g, int a, int fa, int[] c, int d, int[] cnt) {
c[a] = d;
cnt[d]++;
for (int b : g[a]) {
if (b != fa) {
dfs(g, b, a, c, d ^ 1, cnt);
}
}
}
}
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Python
|
class Solution:
def maxTargetNodes(
self, edges1: List[List[int]], edges2: List[List[int]]
) -> List[int]:
def build(edges: List[List[int]]) -> List[List[int]]:
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
return g
def dfs(
g: List[List[int]], a: int, fa: int, c: List[int], d: int, cnt: List[int]
):
c[a] = d
cnt[d] += 1
for b in g[a]:
if b != fa:
dfs(g, b, a, c, d ^ 1, cnt)
g1 = build(edges1)
g2 = build(edges2)
n, m = len(g1), len(g2)
c1 = [0] * n
c2 = [0] * m
cnt1 = [0, 0]
cnt2 = [0, 0]
dfs(g2, 0, -1, c2, 0, cnt2)
dfs(g1, 0, -1, c1, 0, cnt1)
t = max(cnt2)
return [t + cnt1[c1[i]] for i in range(n)]
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
Rust
|
impl Solution {
pub fn max_target_nodes(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>) -> Vec<i32> {
fn build(edges: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = edges.len() + 1;
let mut g = vec![vec![]; n];
for e in edges {
let a = e[0] as usize;
let b = e[1] as usize;
g[a].push(b as i32);
g[b].push(a as i32);
}
g
}
fn dfs(g: &Vec<Vec<i32>>, a: usize, fa: i32, c: &mut Vec<i32>, d: i32, cnt: &mut Vec<i32>) {
c[a] = d;
cnt[d as usize] += 1;
for &b in &g[a] {
if b != fa {
dfs(g, b as usize, a as i32, c, d ^ 1, cnt);
}
}
}
let g1 = build(&edges1);
let g2 = build(&edges2);
let n = g1.len();
let m = g2.len();
let mut c1 = vec![0; n];
let mut c2 = vec![0; m];
let mut cnt1 = vec![0; 2];
let mut cnt2 = vec![0; 2];
dfs(&g2, 0, -1, &mut c2, 0, &mut cnt2);
dfs(&g1, 0, -1, &mut c1, 0, &mut cnt1);
let t = cnt2[0].max(cnt2[1]);
let mut ans = vec![0; n];
for i in 0..n {
ans[i] = t + cnt1[c1[i] as usize];
}
ans
}
}
|
3,373 |
Maximize the Number of Target Nodes After Connecting Trees II
|
Hard
|
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, labeled from <code>[0, n - 1]</code> and <code>[0, m - 1]</code>, respectively.</p>
<p>You are given two 2D integer arrays <code>edges1</code> and <code>edges2</code> of lengths <code>n - 1</code> and <code>m - 1</code>, respectively, where <code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the first tree and <code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the second tree.</p>
<p>Node <code>u</code> is <strong>target</strong> to node <code>v</code> if the number of edges on the path from <code>u</code> to <code>v</code> is even. <strong>Note</strong> that a node is <em>always</em> <strong>target</strong> to itself.</p>
<p>Return an array of <code>n</code> integers <code>answer</code>, where <code>answer[i]</code> is the <strong>maximum</strong> possible number of nodes that are <strong>target</strong> to node <code>i</code> of the first tree if you had to connect one node from the first tree to another node in the second tree.</p>
<p><strong>Note</strong> that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[8,7,7,8,8]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, connect node 0 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 1</code>, connect node 1 from the first tree to node 4 from the second tree.</li>
<li>For <code>i = 2</code>, connect node 2 from the first tree to node 7 from the second tree.</li>
<li>For <code>i = 3</code>, connect node 3 from the first tree to node 0 from the second tree.</li>
<li>For <code>i = 4</code>, connect node 4 from the first tree to node 4 from the second tree.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3982-1.png" style="width: 600px; height: 169px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[3,6,6,6,6]</span></p>
<p><strong>Explanation:</strong></p>
<p>For every <code>i</code>, connect node <code>i</code> of the first tree with any node of the second tree.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3373.Maximize%20the%20Number%20of%20Target%20Nodes%20After%20Connecting%20Trees%20II/images/3928-2.png" style="height: 281px; width: 500px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>5</sup></code></li>
<li><code>edges1.length == n - 1</code></li>
<li><code>edges2.length == m - 1</code></li>
<li><code>edges1[i].length == edges2[i].length == 2</code></li>
<li><code>edges1[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < m</code></li>
<li>The input is generated such that <code>edges1</code> and <code>edges2</code> represent valid trees.</li>
</ul>
|
Tree; Depth-First Search; Breadth-First Search
|
TypeScript
|
function maxTargetNodes(edges1: number[][], edges2: number[][]): number[] {
const g1 = build(edges1);
const g2 = build(edges2);
const [n, m] = [g1.length, g2.length];
const c1 = Array(n).fill(0);
const c2 = Array(m).fill(0);
const cnt1 = [0, 0];
const cnt2 = [0, 0];
dfs(g2, 0, -1, c2, 0, cnt2);
dfs(g1, 0, -1, c1, 0, cnt1);
const t = Math.max(...cnt2);
const ans = Array(n);
for (let i = 0; i < n; i++) {
ans[i] = t + cnt1[c1[i]];
}
return ans;
}
function build(edges: number[][]): number[][] {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
return g;
}
function dfs(g: number[][], a: number, fa: number, c: number[], d: number, cnt: number[]): void {
c[a] = d;
cnt[d]++;
for (const b of g[a]) {
if (b !== fa) {
dfs(g, b, a, c, d ^ 1, cnt);
}
}
}
|
3,374 |
First Letter Capitalization II
|
Hard
|
<p>Table: <code>user_content</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| content_id | int |
| content_text| varchar |
+-------------+---------+
content_id is the unique key for this table.
Each row contains a unique ID and the corresponding text content.
</pre>
<p>Write a solution to transform the text in the <code>content_text</code> column by applying the following rules:</p>
<ul>
<li>Convert the <strong>first letter</strong> of each word to <strong>uppercase</strong> and the <strong>remaining</strong> letters to <strong>lowercase</strong></li>
<li>Special handling for words containing special characters:
<ul>
<li>For words connected with a hyphen <code>-</code>, <strong>both parts</strong> should be <strong>capitalized</strong> (<strong>e.g.</strong>, top-rated → Top-Rated)</li>
</ul>
</li>
<li>All other <strong>formatting</strong> and <strong>spacing</strong> should remain <strong>unchanged</strong></li>
</ul>
<p>Return <em>the result table that includes both the original <code>content_text</code> and the modified text following the above rules</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>user_content table:</p>
<pre class="example-io">
+------------+---------------------------------+
| content_id | content_text |
+------------+---------------------------------+
| 1 | hello world of SQL |
| 2 | the QUICK-brown fox |
| 3 | modern-day DATA science |
| 4 | web-based FRONT-end development |
+------------+---------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+---------------------------------+---------------------------------+
| content_id | original_text | converted_text |
+------------+---------------------------------+---------------------------------+
| 1 | hello world of SQL | Hello World Of Sql |
| 2 | the QUICK-brown fox | The Quick-Brown Fox |
| 3 | modern-day DATA science | Modern-Day Data Science |
| 4 | web-based FRONT-end development | Web-Based Front-End Development |
+------------+---------------------------------+---------------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For content_id = 1:
<ul>
<li>Each word's first letter is capitalized: "Hello World Of Sql"</li>
</ul>
</li>
<li>For content_id = 2:
<ul>
<li>Contains the hyphenated word "QUICK-brown" which becomes "Quick-Brown"</li>
<li>Other words follow normal capitalization rules</li>
</ul>
</li>
<li>For content_id = 3:
<ul>
<li>Hyphenated word "modern-day" becomes "Modern-Day"</li>
<li>"DATA" is converted to "Data"</li>
</ul>
</li>
<li>For content_id = 4:
<ul>
<li>Contains two hyphenated words: "web-based" → "Web-Based"</li>
<li>And "FRONT-end" → "Front-End"</li>
</ul>
</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def capitalize_content(user_content: pd.DataFrame) -> pd.DataFrame:
def convert_text(text: str) -> str:
return " ".join(
(
"-".join([part.capitalize() for part in word.split("-")])
if "-" in word
else word.capitalize()
)
for word in text.split(" ")
)
user_content["converted_text"] = user_content["content_text"].apply(convert_text)
return user_content.rename(columns={"content_text": "original_text"})[
["content_id", "original_text", "converted_text"]
]
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
unordered_set<int> s;
int mi = INT_MAX;
for (int x : nums) {
if (x < k) {
return -1;
}
mi = min(mi, x);
s.insert(x);
}
return s.size() - (mi == k);
}
};
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func minOperations(nums []int, k int) int {
mi := 1 << 30
s := map[int]bool{}
for _, x := range nums {
if x < k {
return -1
}
s[x] = true
mi = min(mi, x)
}
if mi == k {
return len(s) - 1
}
return len(s)
}
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
Set<Integer> s = new HashSet<>();
int mi = 1 << 30;
for (int x : nums) {
if (x < k) {
return -1;
}
mi = Math.min(mi, x);
s.add(x);
}
return s.size() - (mi == k ? 1 : 0);
}
}
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
JavaScript
|
function minOperations(nums, k) {
const s = new Set([k]);
for (const x of nums) {
if (x < k) return -1;
s.add(x);
}
return s.size - 1;
}
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
s = set()
mi = inf
for x in nums:
if x < k:
return -1
mi = min(mi, x)
s.add(x)
return len(s) - int(k == mi)
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
Rust
|
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
use std::collections::HashSet;
let mut s = HashSet::new();
let mut mi = i32::MAX;
for &x in &nums {
if x < k {
return -1;
}
s.insert(x);
mi = mi.min(x);
}
(s.len() as i32) - if mi == k { 1 } else { 0 }
}
}
|
3,375 |
Minimum Operations to Make Array Values Equal to K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>h</code> is called <strong>valid</strong> if all values in the array that are <strong>strictly greater</strong> than <code>h</code> are <em>identical</em>.</p>
<p>For example, if <code>nums = [10, 8, 10, 8]</code>, a <strong>valid</strong> integer is <code>h = 9</code> because all <code>nums[i] > 9</code> are equal to 10, but 5 is not a <strong>valid</strong> integer.</p>
<p>You are allowed to perform the following operation on <code>nums</code>:</p>
<ul>
<li>Select an integer <code>h</code> that is <em>valid</em> for the <strong>current</strong> values in <code>nums</code>.</li>
<li>For each index <code>i</code> where <code>nums[i] > h</code>, set <code>nums[i]</code> to <code>h</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make every element in <code>nums</code> <strong>equal</strong> to <code>k</code>. If it is impossible to make all elements equal to <code>k</code>, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,2,5,4,5], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed in order using valid integers 4 and then 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make all the values equal to 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [9,7,5,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The operations can be performed using valid integers in the order 7, 5, 3, and 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100 </code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
const s = new Set<number>([k]);
for (const x of nums) {
if (x < k) return -1;
s.add(x);
}
return s.size - 1;
}
|
3,376 |
Minimum Time to Break Locks I
|
Medium
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">x</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>x</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach <strong>at least</strong> <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>x</code> increases by a given value <code>k</code>.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 3<sup>rd</sup> Lock</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Break 2<sup>nd</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">6</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 2<sup>n</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">5</td>
</tr>
<tr>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">Break 3<sup>r</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">7</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 5 minutes; thus, the answer is 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 8</code></li>
<li><code>1 <= K <= 10</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Array; Dynamic Programming; Backtracking; Bitmask
|
C++
|
class Solution {
public:
int findMinimumTime(vector<int>& strength, int K) {
int n = strength.size();
int f[1 << n];
memset(f, -1, sizeof(f));
int k = K;
auto dfs = [&](this auto&& dfs, int i) -> int {
if (i == (1 << n) - 1) {
return 0;
}
if (f[i] != -1) {
return f[i];
}
int cnt = __builtin_popcount(i);
int x = 1 + k * cnt;
f[i] = INT_MAX;
for (int j = 0; j < n; ++j) {
if (i >> j & 1 ^ 1) {
f[i] = min(f[i], dfs(i | 1 << j) + (strength[j] + x - 1) / x);
}
}
return f[i];
};
return dfs(0);
}
};
|
3,376 |
Minimum Time to Break Locks I
|
Medium
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">x</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>x</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach <strong>at least</strong> <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>x</code> increases by a given value <code>k</code>.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 3<sup>rd</sup> Lock</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Break 2<sup>nd</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">6</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 2<sup>n</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">5</td>
</tr>
<tr>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">Break 3<sup>r</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">7</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 5 minutes; thus, the answer is 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 8</code></li>
<li><code>1 <= K <= 10</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Array; Dynamic Programming; Backtracking; Bitmask
|
Go
|
func findMinimumTime(strength []int, K int) int {
n := len(strength)
f := make([]int, 1<<n)
for i := range f {
f[i] = -1
}
var dfs func(int) int
dfs = func(i int) int {
if i == 1<<n-1 {
return 0
}
if f[i] != -1 {
return f[i]
}
x := 1 + K*bits.OnesCount(uint(i))
f[i] = 1 << 30
for j, s := range strength {
if i>>j&1 == 0 {
f[i] = min(f[i], dfs(i|1<<j)+(s+x-1)/x)
}
}
return f[i]
}
return dfs(0)
}
|
3,376 |
Minimum Time to Break Locks I
|
Medium
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">x</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>x</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach <strong>at least</strong> <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>x</code> increases by a given value <code>k</code>.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 3<sup>rd</sup> Lock</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Break 2<sup>nd</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">6</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 2<sup>n</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">5</td>
</tr>
<tr>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">Break 3<sup>r</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">7</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 5 minutes; thus, the answer is 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 8</code></li>
<li><code>1 <= K <= 10</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Array; Dynamic Programming; Backtracking; Bitmask
|
Java
|
class Solution {
private List<Integer> strength;
private Integer[] f;
private int k;
private int n;
public int findMinimumTime(List<Integer> strength, int K) {
n = strength.size();
f = new Integer[1 << n];
k = K;
this.strength = strength;
return dfs(0);
}
private int dfs(int i) {
if (i == (1 << n) - 1) {
return 0;
}
if (f[i] != null) {
return f[i];
}
int cnt = Integer.bitCount(i);
int x = 1 + cnt * k;
f[i] = 1 << 30;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 0) {
f[i] = Math.min(f[i], dfs(i | 1 << j) + (strength.get(j) + x - 1) / x);
}
}
return f[i];
}
}
|
3,376 |
Minimum Time to Break Locks I
|
Medium
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">x</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>x</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach <strong>at least</strong> <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>x</code> increases by a given value <code>k</code>.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 3<sup>rd</sup> Lock</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Break 2<sup>nd</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">6</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 2<sup>n</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">5</td>
</tr>
<tr>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">Break 3<sup>r</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">7</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 5 minutes; thus, the answer is 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 8</code></li>
<li><code>1 <= K <= 10</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Array; Dynamic Programming; Backtracking; Bitmask
|
Python
|
class Solution:
def findMinimumTime(self, strength: List[int], K: int) -> int:
@cache
def dfs(i: int) -> int:
if i == (1 << len(strength)) - 1:
return 0
cnt = i.bit_count()
x = 1 + cnt * K
ans = inf
for j, s in enumerate(strength):
if i >> j & 1 ^ 1:
ans = min(ans, dfs(i | 1 << j) + (s + x - 1) // x)
return ans
return dfs(0)
|
3,376 |
Minimum Time to Break Locks I
|
Medium
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">x</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>x</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach <strong>at least</strong> <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>x</code> increases by a given value <code>k</code>.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 3<sup>rd</sup> Lock</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">Break 2<sup>nd</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Time</th>
<th style="border: 1px solid black;">Energy</th>
<th style="border: 1px solid black;">x</th>
<th style="border: 1px solid black;">Action</th>
<th style="border: 1px solid black;">Updated x</th>
</tr>
<tr>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">Break 1<sup>st</sup> Lock</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Nothing</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">6</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">Break 2<sup>n</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">5</td>
</tr>
<tr>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">5</td>
<td style="border: 1px solid black;">Break 3<sup>r</sup><sup>d</sup> Lock</td>
<td style="border: 1px solid black;">7</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 5 minutes; thus, the answer is 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 8</code></li>
<li><code>1 <= K <= 10</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Depth-First Search; Array; Dynamic Programming; Backtracking; Bitmask
|
TypeScript
|
function findMinimumTime(strength: number[], K: number): number {
const n = strength.length;
const f: number[] = Array(1 << n).fill(-1);
const dfs = (i: number): number => {
if (i === (1 << n) - 1) {
return 0;
}
if (f[i] !== -1) {
return f[i];
}
f[i] = Infinity;
const x = 1 + K * bitCount(i);
for (let j = 0; j < n; ++j) {
if (((i >> j) & 1) == 0) {
f[i] = Math.min(f[i], dfs(i | (1 << j)) + Math.ceil(strength[j] / x));
}
}
return f[i];
};
return dfs(0);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
3,377 |
Digit Operations to Make Two Integers Equal
|
Medium
|
<p>You are given two integers <code>n</code> and <code>m</code> that consist of the <strong>same</strong> number of digits.</p>
<p>You can perform the following operations <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 9 and <strong>increase</strong> it by 1.</li>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 0 and <strong>decrease</strong> it by 1.</li>
</ul>
<p>The integer <code>n</code> must not be a <span data-keyword="prime-number">prime</span> number at any point, including its original value and after each operation.</p>
<p>The cost of a transformation is the sum of <strong>all</strong> values that <code>n</code> takes throughout the operations performed.</p>
<p>Return the <strong>minimum</strong> cost to transform <code>n</code> into <code>m</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10, m = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">85</span></p>
<p><strong>Explanation:</strong></p>
<p>We perform the following operations:</p>
<ul>
<li>Increase the first digit, now <code>n = <u><strong>2</strong></u>0</code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>1</u></strong></code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>2</u></strong></code>.</li>
<li>Decrease the first digit, now <code>n = <strong><u>1</u></strong>2</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 8</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>n</code> equal to <code>m</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, m = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> </p>
<p>Since 2 is already a prime, we can't make <code>n</code> equal to <code>m</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m < 10<sup>4</sup></code></li>
<li><code>n</code> and <code>m</code> consist of the same number of digits.</li>
</ul>
|
Graph; Math; Number Theory; Shortest Path; Heap (Priority Queue)
|
C++
|
class Solution {
private:
vector<bool> sieve;
void runSieve() {
sieve.resize(100000, true);
sieve[0] = false, sieve[1] = false;
for (int i = 2; i < 1e5; ++i) {
if (sieve[i]) {
for (int j = 2 * i; j < 1e5; j += i) {
sieve[j] = false;
}
}
}
}
int solve(int n, int m) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
unordered_set<int> vis;
pq.push({n, n});
while (!pq.empty()) {
int sum = pq.top().first, cur = pq.top().second;
pq.pop();
if (vis.find(cur) != vis.end()) continue;
vis.insert(cur);
if (cur == m) return sum;
string s = to_string(cur);
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
if (s[i] < '9') {
s[i]++;
int next = stoi(s);
if (!sieve[next] && vis.find(next) == vis.end()) {
pq.push({sum + next, next});
}
s[i] = c;
}
if (s[i] > '0' && !(i == 0 && s[i] == '1')) {
s[i]--;
int next = stoi(s);
if (!sieve[next] && vis.find(next) == vis.end()) {
pq.push({sum + next, next});
}
s[i] = c;
}
}
}
return -1;
}
public:
int minOperations(int n, int m) {
runSieve();
if (sieve[n] || sieve[m]) return -1;
return solve(n, m);
}
};
|
3,377 |
Digit Operations to Make Two Integers Equal
|
Medium
|
<p>You are given two integers <code>n</code> and <code>m</code> that consist of the <strong>same</strong> number of digits.</p>
<p>You can perform the following operations <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 9 and <strong>increase</strong> it by 1.</li>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 0 and <strong>decrease</strong> it by 1.</li>
</ul>
<p>The integer <code>n</code> must not be a <span data-keyword="prime-number">prime</span> number at any point, including its original value and after each operation.</p>
<p>The cost of a transformation is the sum of <strong>all</strong> values that <code>n</code> takes throughout the operations performed.</p>
<p>Return the <strong>minimum</strong> cost to transform <code>n</code> into <code>m</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10, m = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">85</span></p>
<p><strong>Explanation:</strong></p>
<p>We perform the following operations:</p>
<ul>
<li>Increase the first digit, now <code>n = <u><strong>2</strong></u>0</code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>1</u></strong></code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>2</u></strong></code>.</li>
<li>Decrease the first digit, now <code>n = <strong><u>1</u></strong>2</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 8</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>n</code> equal to <code>m</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, m = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> </p>
<p>Since 2 is already a prime, we can't make <code>n</code> equal to <code>m</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m < 10<sup>4</sup></code></li>
<li><code>n</code> and <code>m</code> consist of the same number of digits.</li>
</ul>
|
Graph; Math; Number Theory; Shortest Path; Heap (Priority Queue)
|
Go
|
package main
import (
"container/heap"
"strconv"
)
type MinHeap [][]int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i][0] < h[j][0] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.([]int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
var sieve []bool
func runSieve() {
sieve = make([]bool, 100000)
for i := range sieve {
sieve[i] = true
}
sieve[0], sieve[1] = false, false
for i := 2; i < 100000; i++ {
if sieve[i] {
for j := 2 * i; j < 100000; j += i {
sieve[j] = false
}
}
}
}
func solve(n int, m int) int {
pq := &MinHeap{}
heap.Init(pq)
heap.Push(pq, []int{n, n})
visited := make(map[int]bool)
for pq.Len() > 0 {
top := heap.Pop(pq).([]int)
sum, cur := top[0], top[1]
if visited[cur] {
continue
}
visited[cur] = true
if cur == m {
return sum
}
s := []rune(strconv.Itoa(cur))
for i := 0; i < len(s); i++ {
c := s[i]
if s[i] < '9' {
s[i]++
next, _ := strconv.Atoi(string(s))
if !sieve[next] && !visited[next] {
heap.Push(pq, []int{sum + next, next})
}
s[i] = c
}
if s[i] > '0' && !(i == 0 && s[i] == '1') {
s[i]--
next, _ := strconv.Atoi(string(s))
if !sieve[next] && !visited[next] {
heap.Push(pq, []int{sum + next, next})
}
s[i] = c
}
}
}
return -1
}
func minOperations(n int, m int) int {
runSieve()
if sieve[n] || sieve[m] {
return -1
}
return solve(n, m)
}
|
3,377 |
Digit Operations to Make Two Integers Equal
|
Medium
|
<p>You are given two integers <code>n</code> and <code>m</code> that consist of the <strong>same</strong> number of digits.</p>
<p>You can perform the following operations <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 9 and <strong>increase</strong> it by 1.</li>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 0 and <strong>decrease</strong> it by 1.</li>
</ul>
<p>The integer <code>n</code> must not be a <span data-keyword="prime-number">prime</span> number at any point, including its original value and after each operation.</p>
<p>The cost of a transformation is the sum of <strong>all</strong> values that <code>n</code> takes throughout the operations performed.</p>
<p>Return the <strong>minimum</strong> cost to transform <code>n</code> into <code>m</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10, m = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">85</span></p>
<p><strong>Explanation:</strong></p>
<p>We perform the following operations:</p>
<ul>
<li>Increase the first digit, now <code>n = <u><strong>2</strong></u>0</code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>1</u></strong></code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>2</u></strong></code>.</li>
<li>Decrease the first digit, now <code>n = <strong><u>1</u></strong>2</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 8</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>n</code> equal to <code>m</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, m = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> </p>
<p>Since 2 is already a prime, we can't make <code>n</code> equal to <code>m</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m < 10<sup>4</sup></code></li>
<li><code>n</code> and <code>m</code> consist of the same number of digits.</li>
</ul>
|
Graph; Math; Number Theory; Shortest Path; Heap (Priority Queue)
|
Java
|
class Solution {
private boolean[] sieve;
private void runSieve() {
sieve = new boolean[100000];
Arrays.fill(sieve, true);
sieve[0] = false;
sieve[1] = false;
for (int i = 2; i < 100000; i++) {
if (sieve[i]) {
for (int j = 2 * i; j < 100000; j += i) {
sieve[j] = false;
}
}
}
}
private int solve(int n, int m) {
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.add(new int[] {n, n});
Set<Integer> visited = new HashSet<>();
while (!pq.isEmpty()) {
int[] top = pq.poll();
int sum = top[0], cur = top[1];
if (visited.contains(cur)) {
continue;
}
visited.add(cur);
if (cur == m) {
return sum;
}
char[] s = String.valueOf(cur).toCharArray();
for (int i = 0; i < s.length; i++) {
char c = s[i];
if (s[i] < '9') {
s[i] = (char) (s[i] + 1);
int next = Integer.parseInt(new String(s));
if (!sieve[next] && !visited.contains(next)) {
pq.add(new int[] {sum + next, next});
}
s[i] = c;
}
if (s[i] > '0' && !(i == 0 && s[i] == '1')) {
s[i] = (char) (s[i] - 1);
int next = Integer.parseInt(new String(s));
if (!sieve[next] && !visited.contains(next)) {
pq.add(new int[] {sum + next, next});
}
s[i] = c;
}
}
}
return -1;
}
public int minOperations(int n, int m) {
runSieve();
if (sieve[n] || sieve[m]) {
return -1;
}
return solve(n, m);
}
}
|
3,377 |
Digit Operations to Make Two Integers Equal
|
Medium
|
<p>You are given two integers <code>n</code> and <code>m</code> that consist of the <strong>same</strong> number of digits.</p>
<p>You can perform the following operations <strong>any</strong> number of times:</p>
<ul>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 9 and <strong>increase</strong> it by 1.</li>
<li>Choose <strong>any</strong> digit from <code>n</code> that is not 0 and <strong>decrease</strong> it by 1.</li>
</ul>
<p>The integer <code>n</code> must not be a <span data-keyword="prime-number">prime</span> number at any point, including its original value and after each operation.</p>
<p>The cost of a transformation is the sum of <strong>all</strong> values that <code>n</code> takes throughout the operations performed.</p>
<p>Return the <strong>minimum</strong> cost to transform <code>n</code> into <code>m</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 10, m = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">85</span></p>
<p><strong>Explanation:</strong></p>
<p>We perform the following operations:</p>
<ul>
<li>Increase the first digit, now <code>n = <u><strong>2</strong></u>0</code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>1</u></strong></code>.</li>
<li>Increase the second digit, now <code>n = 2<strong><u>2</u></strong></code>.</li>
<li>Decrease the first digit, now <code>n = <strong><u>1</u></strong>2</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 8</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>n</code> equal to <code>m</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, m = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong> </p>
<p>Since 2 is already a prime, we can't make <code>n</code> equal to <code>m</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m < 10<sup>4</sup></code></li>
<li><code>n</code> and <code>m</code> consist of the same number of digits.</li>
</ul>
|
Graph; Math; Number Theory; Shortest Path; Heap (Priority Queue)
|
Python
|
import heapq
class Solution:
def __init__(self):
self.sieve = []
def run_sieve(self):
self.sieve = [True] * 100000
self.sieve[0], self.sieve[1] = False, False
for i in range(2, 100000):
if self.sieve[i]:
for j in range(2 * i, 100000, i):
self.sieve[j] = False
def solve(self, n, m):
pq = []
heapq.heappush(pq, (n, n))
visited = set()
while pq:
sum_, cur = heapq.heappop(pq)
if cur in visited:
continue
visited.add(cur)
if cur == m:
return sum_
s = list(str(cur))
for i in range(len(s)):
c = s[i]
if s[i] < '9':
s[i] = chr(ord(s[i]) + 1)
next_ = int(''.join(s))
if not self.sieve[next_] and next_ not in visited:
heapq.heappush(pq, (sum_ + next_, next_))
s[i] = c
if s[i] > '0' and not (i == 0 and s[i] == '1'):
s[i] = chr(ord(s[i]) - 1)
next_ = int(''.join(s))
if not self.sieve[next_] and next_ not in visited:
heapq.heappush(pq, (sum_ + next_, next_))
s[i] = c
return -1
def minOperations(self, n, m):
self.run_sieve()
if self.sieve[n] or self.sieve[m]:
return -1
return self.solve(n, m)
|
3,378 |
Count Connected Components in LCM Graph
|
Hard
|
<p>You are given an array of integers <code>nums</code> of size <code>n</code> and a <strong>positive</strong> integer <code>threshold</code>.</p>
<p>There is a graph consisting of <code>n</code> nodes with the <code>i<sup>th</sup></code> node having a value of <code>nums[i]</code>. Two nodes <code>i</code> and <code>j</code> in the graph are connected via an <strong>undirected</strong> edge if <code>lcm(nums[i], nums[j]) <= threshold</code>.</p>
<p>Return the number of <strong>connected components</strong> in this graph.</p>
<p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p>
<p>The term <code>lcm(a, b)</code> denotes the <strong>least common multiple</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9], threshold = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example0.png" style="width: 250px; height: 251px;" /></p>
<p> </p>
<p>The four connected components are <code>(2, 4)</code>, <code>(3)</code>, <code>(8)</code>, <code>(9)</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9,12], threshold = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example1.png" style="width: 250px; height: 252px;" /></p>
<p>The two connected components are <code>(2, 3, 4, 8, 9)</code>, and <code>(12)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>All elements of <code>nums</code> are unique.</li>
<li><code>1 <= threshold <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Union Find; Array; Hash Table; Math; Number Theory
|
C++
|
typedef struct DSU {
unordered_map<int, int> par, rank;
DSU(int n) {
for (int i = 0; i < n; ++i) {
par[i] = i;
rank[i] = 0;
}
}
void makeSet(int v) {
par[v] = v;
rank[v] = 1;
}
int find(int x) {
if (par[x] == x) {
return x;
}
return par[x] = find(par[x]);
}
void unionSet(int u, int v) {
u = find(u);
v = find(v);
if (u != v) {
if (rank[u] < rank[v]) swap(u, v);
par[v] = u;
if (rank[u] == rank[v]) rank[u]++;
}
}
} DSU;
class Solution {
public:
int countComponents(vector<int>& nums, int threshold) {
DSU dsu(threshold);
for (auto& num : nums) {
for (int j = num; j <= threshold; j += num) {
dsu.unionSet(num, j);
}
}
unordered_set<int> par;
for (auto& num : nums) {
if (num > threshold) {
par.insert(num);
} else {
par.insert(dsu.find(num));
}
}
return par.size();
}
};
|
3,378 |
Count Connected Components in LCM Graph
|
Hard
|
<p>You are given an array of integers <code>nums</code> of size <code>n</code> and a <strong>positive</strong> integer <code>threshold</code>.</p>
<p>There is a graph consisting of <code>n</code> nodes with the <code>i<sup>th</sup></code> node having a value of <code>nums[i]</code>. Two nodes <code>i</code> and <code>j</code> in the graph are connected via an <strong>undirected</strong> edge if <code>lcm(nums[i], nums[j]) <= threshold</code>.</p>
<p>Return the number of <strong>connected components</strong> in this graph.</p>
<p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p>
<p>The term <code>lcm(a, b)</code> denotes the <strong>least common multiple</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9], threshold = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example0.png" style="width: 250px; height: 251px;" /></p>
<p> </p>
<p>The four connected components are <code>(2, 4)</code>, <code>(3)</code>, <code>(8)</code>, <code>(9)</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9,12], threshold = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example1.png" style="width: 250px; height: 252px;" /></p>
<p>The two connected components are <code>(2, 3, 4, 8, 9)</code>, and <code>(12)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>All elements of <code>nums</code> are unique.</li>
<li><code>1 <= threshold <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Union Find; Array; Hash Table; Math; Number Theory
|
Go
|
type DSU struct {
parent map[int]int
rank map[int]int
}
func NewDSU(n int) *DSU {
dsu := &DSU{
parent: make(map[int]int),
rank: make(map[int]int),
}
for i := 0; i <= n; i++ {
dsu.parent[i] = i
dsu.rank[i] = 0
}
return dsu
}
func (dsu *DSU) Find(x int) int {
if dsu.parent[x] != x {
dsu.parent[x] = dsu.Find(dsu.parent[x])
}
return dsu.parent[x]
}
func (dsu *DSU) Union(u, v int) {
uRoot := dsu.Find(u)
vRoot := dsu.Find(v)
if uRoot != vRoot {
if dsu.rank[uRoot] < dsu.rank[vRoot] {
uRoot, vRoot = vRoot, uRoot
}
dsu.parent[vRoot] = uRoot
if dsu.rank[uRoot] == dsu.rank[vRoot] {
dsu.rank[uRoot]++
}
}
}
func countComponents(nums []int, threshold int) int {
dsu := NewDSU(threshold)
for _, num := range nums {
for j := num; j <= threshold; j += num {
dsu.Union(num, j)
}
}
uniqueParents := make(map[int]struct{})
for _, num := range nums {
if num > threshold {
uniqueParents[num] = struct{}{}
} else {
uniqueParents[dsu.Find(num)] = struct{}{}
}
}
return len(uniqueParents)
}
|
3,378 |
Count Connected Components in LCM Graph
|
Hard
|
<p>You are given an array of integers <code>nums</code> of size <code>n</code> and a <strong>positive</strong> integer <code>threshold</code>.</p>
<p>There is a graph consisting of <code>n</code> nodes with the <code>i<sup>th</sup></code> node having a value of <code>nums[i]</code>. Two nodes <code>i</code> and <code>j</code> in the graph are connected via an <strong>undirected</strong> edge if <code>lcm(nums[i], nums[j]) <= threshold</code>.</p>
<p>Return the number of <strong>connected components</strong> in this graph.</p>
<p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p>
<p>The term <code>lcm(a, b)</code> denotes the <strong>least common multiple</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9], threshold = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example0.png" style="width: 250px; height: 251px;" /></p>
<p> </p>
<p>The four connected components are <code>(2, 4)</code>, <code>(3)</code>, <code>(8)</code>, <code>(9)</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9,12], threshold = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example1.png" style="width: 250px; height: 252px;" /></p>
<p>The two connected components are <code>(2, 3, 4, 8, 9)</code>, and <code>(12)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>All elements of <code>nums</code> are unique.</li>
<li><code>1 <= threshold <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Union Find; Array; Hash Table; Math; Number Theory
|
Java
|
class DSU {
private Map<Integer, Integer> parent;
private Map<Integer, Integer> rank;
public DSU(int n) {
parent = new HashMap<>();
rank = new HashMap<>();
for (int i = 0; i <= n; i++) {
parent.put(i, i);
rank.put(i, 0);
}
}
public void makeSet(int v) {
parent.put(v, v);
rank.put(v, 1);
}
public int find(int x) {
if (parent.get(x) != x) {
parent.put(x, find(parent.get(x)));
}
return parent.get(x);
}
public void unionSet(int u, int v) {
u = find(u);
v = find(v);
if (u != v) {
if (rank.get(u) < rank.get(v)) {
int temp = u;
u = v;
v = temp;
}
parent.put(v, u);
if (rank.get(u).equals(rank.get(v))) {
rank.put(u, rank.get(u) + 1);
}
}
}
}
class Solution {
public int countComponents(int[] nums, int threshold) {
DSU dsu = new DSU(threshold);
for (int num : nums) {
for (int j = num; j <= threshold; j += num) {
dsu.unionSet(num, j);
}
}
Set<Integer> uniqueParents = new HashSet<>();
for (int num : nums) {
if (num > threshold) {
uniqueParents.add(num);
} else {
uniqueParents.add(dsu.find(num));
}
}
return uniqueParents.size();
}
}
|
3,378 |
Count Connected Components in LCM Graph
|
Hard
|
<p>You are given an array of integers <code>nums</code> of size <code>n</code> and a <strong>positive</strong> integer <code>threshold</code>.</p>
<p>There is a graph consisting of <code>n</code> nodes with the <code>i<sup>th</sup></code> node having a value of <code>nums[i]</code>. Two nodes <code>i</code> and <code>j</code> in the graph are connected via an <strong>undirected</strong> edge if <code>lcm(nums[i], nums[j]) <= threshold</code>.</p>
<p>Return the number of <strong>connected components</strong> in this graph.</p>
<p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p>
<p>The term <code>lcm(a, b)</code> denotes the <strong>least common multiple</strong> of <code>a</code> and <code>b</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9], threshold = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example0.png" style="width: 250px; height: 251px;" /></p>
<p> </p>
<p>The four connected components are <code>(2, 4)</code>, <code>(3)</code>, <code>(8)</code>, <code>(9)</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,8,3,9,12], threshold = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3378.Count%20Connected%20Components%20in%20LCM%20Graph/images/example1.png" style="width: 250px; height: 252px;" /></p>
<p>The two connected components are <code>(2, 3, 4, 8, 9)</code>, and <code>(12)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>All elements of <code>nums</code> are unique.</li>
<li><code>1 <= threshold <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Union Find; Array; Hash Table; Math; Number Theory
|
Python
|
class DSU:
def __init__(self, n):
self.parent = {i: i for i in range(n)}
self.rank = {i: 0 for i in range(n)}
def make_set(self, v):
self.parent[v] = v
self.rank[v] = 1
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union_set(self, u, v):
u = self.find(u)
v = self.find(v)
if u != v:
if self.rank[u] < self.rank[v]:
u, v = v, u
self.parent[v] = u
if self.rank[u] == self.rank[v]:
self.rank[u] += 1
class Solution:
def countComponents(self, nums, threshold):
dsu = DSU(threshold + 1)
for num in nums:
for j in range(num, threshold + 1, num):
dsu.union_set(num, j)
unique_parents = set()
for num in nums:
if num > threshold:
unique_parents.add(num)
else:
unique_parents.add(dsu.find(num))
return len(unique_parents)
|
3,379 |
Transformed Array
|
Easy
|
<p>You are given an integer array <code>nums</code> that represents a circular array. Your task is to create a new array <code>result</code> of the <strong>same</strong> size, following these rules:</p>
For each index <code>i</code> (where <code>0 <= i < nums.length</code>), perform the following <strong>independent</strong> actions:
<ul>
<li>If <code>nums[i] > 0</code>: Start at index <code>i</code> and move <code>nums[i]</code> steps to the <strong>right</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] < 0</code>: Start at index <code>i</code> and move <code>abs(nums[i])</code> steps to the <strong>left</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] == 0</code>: Set <code>result[i]</code> to <code>nums[i]</code>.</li>
</ul>
<p>Return the new array <code>result</code>.</p>
<p><strong>Note:</strong> Since <code>nums</code> is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,-2,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to 3, If we move 3 steps to right, we reach <code>nums[3]</code>. So <code>result[0]</code> should be 1.</li>
<li>For <code>nums[1]</code> that is equal to -2, If we move 2 steps to left, we reach <code>nums[3]</code>. So <code>result[1]</code> should be 1.</li>
<li>For <code>nums[2]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[3]</code>. So <code>result[2]</code> should be 1.</li>
<li>For <code>nums[3]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[0]</code>. So <code>result[3]</code> should be 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,4,-1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[2]</code>. So <code>result[0]</code> should be -1.</li>
<li>For <code>nums[1]</code> that is equal to 4, If we move 4 steps to right, we reach <code>nums[2]</code>. So <code>result[1]</code> should be -1.</li>
<li>For <code>nums[2]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[1]</code>. So <code>result[2]</code> should be 4.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
vector<int> constructTransformedArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ans[i] = nums[i] ? nums[(i + nums[i] % n + n) % n] : 0;
}
return ans;
}
};
|
3,379 |
Transformed Array
|
Easy
|
<p>You are given an integer array <code>nums</code> that represents a circular array. Your task is to create a new array <code>result</code> of the <strong>same</strong> size, following these rules:</p>
For each index <code>i</code> (where <code>0 <= i < nums.length</code>), perform the following <strong>independent</strong> actions:
<ul>
<li>If <code>nums[i] > 0</code>: Start at index <code>i</code> and move <code>nums[i]</code> steps to the <strong>right</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] < 0</code>: Start at index <code>i</code> and move <code>abs(nums[i])</code> steps to the <strong>left</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] == 0</code>: Set <code>result[i]</code> to <code>nums[i]</code>.</li>
</ul>
<p>Return the new array <code>result</code>.</p>
<p><strong>Note:</strong> Since <code>nums</code> is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,-2,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to 3, If we move 3 steps to right, we reach <code>nums[3]</code>. So <code>result[0]</code> should be 1.</li>
<li>For <code>nums[1]</code> that is equal to -2, If we move 2 steps to left, we reach <code>nums[3]</code>. So <code>result[1]</code> should be 1.</li>
<li>For <code>nums[2]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[3]</code>. So <code>result[2]</code> should be 1.</li>
<li>For <code>nums[3]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[0]</code>. So <code>result[3]</code> should be 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,4,-1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[2]</code>. So <code>result[0]</code> should be -1.</li>
<li>For <code>nums[1]</code> that is equal to 4, If we move 4 steps to right, we reach <code>nums[2]</code>. So <code>result[1]</code> should be -1.</li>
<li>For <code>nums[2]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[1]</code>. So <code>result[2]</code> should be 4.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Array; Simulation
|
Go
|
func constructTransformedArray(nums []int) []int {
n := len(nums)
ans := make([]int, n)
for i, x := range nums {
if x != 0 {
ans[i] = nums[(i+x%n+n)%n]
}
}
return ans
}
|
3,379 |
Transformed Array
|
Easy
|
<p>You are given an integer array <code>nums</code> that represents a circular array. Your task is to create a new array <code>result</code> of the <strong>same</strong> size, following these rules:</p>
For each index <code>i</code> (where <code>0 <= i < nums.length</code>), perform the following <strong>independent</strong> actions:
<ul>
<li>If <code>nums[i] > 0</code>: Start at index <code>i</code> and move <code>nums[i]</code> steps to the <strong>right</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] < 0</code>: Start at index <code>i</code> and move <code>abs(nums[i])</code> steps to the <strong>left</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] == 0</code>: Set <code>result[i]</code> to <code>nums[i]</code>.</li>
</ul>
<p>Return the new array <code>result</code>.</p>
<p><strong>Note:</strong> Since <code>nums</code> is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,-2,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to 3, If we move 3 steps to right, we reach <code>nums[3]</code>. So <code>result[0]</code> should be 1.</li>
<li>For <code>nums[1]</code> that is equal to -2, If we move 2 steps to left, we reach <code>nums[3]</code>. So <code>result[1]</code> should be 1.</li>
<li>For <code>nums[2]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[3]</code>. So <code>result[2]</code> should be 1.</li>
<li>For <code>nums[3]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[0]</code>. So <code>result[3]</code> should be 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,4,-1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[2]</code>. So <code>result[0]</code> should be -1.</li>
<li>For <code>nums[1]</code> that is equal to 4, If we move 4 steps to right, we reach <code>nums[2]</code>. So <code>result[1]</code> should be -1.</li>
<li>For <code>nums[2]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[1]</code>. So <code>result[2]</code> should be 4.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int[] constructTransformedArray(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = nums[i] != 0 ? nums[(i + nums[i] % n + n) % n] : 0;
}
return ans;
}
}
|
3,379 |
Transformed Array
|
Easy
|
<p>You are given an integer array <code>nums</code> that represents a circular array. Your task is to create a new array <code>result</code> of the <strong>same</strong> size, following these rules:</p>
For each index <code>i</code> (where <code>0 <= i < nums.length</code>), perform the following <strong>independent</strong> actions:
<ul>
<li>If <code>nums[i] > 0</code>: Start at index <code>i</code> and move <code>nums[i]</code> steps to the <strong>right</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] < 0</code>: Start at index <code>i</code> and move <code>abs(nums[i])</code> steps to the <strong>left</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] == 0</code>: Set <code>result[i]</code> to <code>nums[i]</code>.</li>
</ul>
<p>Return the new array <code>result</code>.</p>
<p><strong>Note:</strong> Since <code>nums</code> is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,-2,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to 3, If we move 3 steps to right, we reach <code>nums[3]</code>. So <code>result[0]</code> should be 1.</li>
<li>For <code>nums[1]</code> that is equal to -2, If we move 2 steps to left, we reach <code>nums[3]</code>. So <code>result[1]</code> should be 1.</li>
<li>For <code>nums[2]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[3]</code>. So <code>result[2]</code> should be 1.</li>
<li>For <code>nums[3]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[0]</code>. So <code>result[3]</code> should be 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,4,-1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[2]</code>. So <code>result[0]</code> should be -1.</li>
<li>For <code>nums[1]</code> that is equal to 4, If we move 4 steps to right, we reach <code>nums[2]</code>. So <code>result[1]</code> should be -1.</li>
<li>For <code>nums[2]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[1]</code>. So <code>result[2]</code> should be 4.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
ans = []
n = len(nums)
for i, x in enumerate(nums):
ans.append(nums[(i + x + n) % n] if x else 0)
return ans
|
3,379 |
Transformed Array
|
Easy
|
<p>You are given an integer array <code>nums</code> that represents a circular array. Your task is to create a new array <code>result</code> of the <strong>same</strong> size, following these rules:</p>
For each index <code>i</code> (where <code>0 <= i < nums.length</code>), perform the following <strong>independent</strong> actions:
<ul>
<li>If <code>nums[i] > 0</code>: Start at index <code>i</code> and move <code>nums[i]</code> steps to the <strong>right</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] < 0</code>: Start at index <code>i</code> and move <code>abs(nums[i])</code> steps to the <strong>left</strong> in the circular array. Set <code>result[i]</code> to the value of the index where you land.</li>
<li>If <code>nums[i] == 0</code>: Set <code>result[i]</code> to <code>nums[i]</code>.</li>
</ul>
<p>Return the new array <code>result</code>.</p>
<p><strong>Note:</strong> Since <code>nums</code> is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,-2,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,3]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to 3, If we move 3 steps to right, we reach <code>nums[3]</code>. So <code>result[0]</code> should be 1.</li>
<li>For <code>nums[1]</code> that is equal to -2, If we move 2 steps to left, we reach <code>nums[3]</code>. So <code>result[1]</code> should be 1.</li>
<li>For <code>nums[2]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[3]</code>. So <code>result[2]</code> should be 1.</li>
<li>For <code>nums[3]</code> that is equal to 1, If we move 1 step to right, we reach <code>nums[0]</code>. So <code>result[3]</code> should be 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,4,-1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>nums[0]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[2]</code>. So <code>result[0]</code> should be -1.</li>
<li>For <code>nums[1]</code> that is equal to 4, If we move 4 steps to right, we reach <code>nums[2]</code>. So <code>result[1]</code> should be -1.</li>
<li>For <code>nums[2]</code> that is equal to -1, If we move 1 step to left, we reach <code>nums[1]</code>. So <code>result[2]</code> should be 4.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-100 <= nums[i] <= 100</code></li>
</ul>
|
Array; Simulation
|
TypeScript
|
function constructTransformedArray(nums: number[]): number[] {
const n = nums.length;
const ans: number[] = [];
for (let i = 0; i < n; ++i) {
ans.push(nums[i] ? nums[(i + (nums[i] % n) + n) % n] : 0);
}
return ans;
}
|
3,380 |
Maximum Area Rectangle With Point Constraints I
|
Medium
|
<p>You are given an array <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the coordinates of a point on an infinite plane.</p>
<p>Your task is to find the <strong>maximum </strong>area of a rectangle that:</p>
<ul>
<li>Can be formed using <strong>four</strong> of these points as its corners.</li>
<li>Does <strong>not</strong> contain any other point inside or on its border.</li>
<li>Has its edges <strong>parallel</strong> to the axes.</li>
</ul>
<p>Return the <strong>maximum area</strong> that you can obtain or -1 if no such rectangle is possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3]]</span></p>
<p><strong>Output: </strong>4</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 1 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example1.png" style="width: 229px; height: 228px;" /></strong></p>
<p>We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border<!-- notionvc: f270d0a3-a596-4ed6-9997-2c7416b2b4ee -->. Hence, the maximum possible area would be 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[2,2]]</span></p>
<p><strong>Output:</strong><b> </b>-1</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 2 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example2.png" style="width: 229px; height: 228px;" /></strong></p>
<p>There is only one rectangle possible is with points <code>[1,1], [1,3], [3,1]</code> and <code>[3,3]</code> but <code>[2,2]</code> will always lie inside it. Hence, returning -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]</span></p>
<p><strong>Output: </strong>2</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 3 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example3.png" style="width: 229px; height: 228px;" /></strong></p>
<p>The maximum area rectangle is formed by the points <code>[1,3], [1,2], [3,2], [3,3]</code>, which has an area of 2. Additionally, the points <code>[1,1], [1,2], [3,1], [3,2]</code> also form a valid rectangle with the same area.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Geometry; Array; Math; Enumeration; Sorting
|
C++
|
class Solution {
public:
int maxRectangleArea(vector<vector<int>>& points) {
auto check = [&](int x1, int y1, int x2, int y2) -> bool {
int cnt = 0;
for (const auto& point : points) {
int x = point[0];
int y = point[1];
if (x < x1 || x > x2 || y < y1 || y > y2) {
continue;
}
if ((x == x1 || x == x2) && (y == y1 || y == y2)) {
cnt++;
continue;
}
return false;
}
return cnt == 4;
};
int ans = -1;
for (int i = 0; i < points.size(); i++) {
int x1 = points[i][0], y1 = points[i][1];
for (int j = 0; j < i; j++) {
int x2 = points[j][0], y2 = points[j][1];
int x3 = min(x1, x2), y3 = min(y1, y2);
int x4 = max(x1, x2), y4 = max(y1, y2);
if (check(x3, y3, x4, y4)) {
ans = max(ans, (x4 - x3) * (y4 - y3));
}
}
}
return ans;
}
};
|
3,380 |
Maximum Area Rectangle With Point Constraints I
|
Medium
|
<p>You are given an array <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the coordinates of a point on an infinite plane.</p>
<p>Your task is to find the <strong>maximum </strong>area of a rectangle that:</p>
<ul>
<li>Can be formed using <strong>four</strong> of these points as its corners.</li>
<li>Does <strong>not</strong> contain any other point inside or on its border.</li>
<li>Has its edges <strong>parallel</strong> to the axes.</li>
</ul>
<p>Return the <strong>maximum area</strong> that you can obtain or -1 if no such rectangle is possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3]]</span></p>
<p><strong>Output: </strong>4</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 1 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example1.png" style="width: 229px; height: 228px;" /></strong></p>
<p>We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border<!-- notionvc: f270d0a3-a596-4ed6-9997-2c7416b2b4ee -->. Hence, the maximum possible area would be 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[2,2]]</span></p>
<p><strong>Output:</strong><b> </b>-1</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 2 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example2.png" style="width: 229px; height: 228px;" /></strong></p>
<p>There is only one rectangle possible is with points <code>[1,1], [1,3], [3,1]</code> and <code>[3,3]</code> but <code>[2,2]</code> will always lie inside it. Hence, returning -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]</span></p>
<p><strong>Output: </strong>2</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 3 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example3.png" style="width: 229px; height: 228px;" /></strong></p>
<p>The maximum area rectangle is formed by the points <code>[1,3], [1,2], [3,2], [3,3]</code>, which has an area of 2. Additionally, the points <code>[1,1], [1,2], [3,1], [3,2]</code> also form a valid rectangle with the same area.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Geometry; Array; Math; Enumeration; Sorting
|
Go
|
func maxRectangleArea(points [][]int) int {
check := func(x1, y1, x2, y2 int) bool {
cnt := 0
for _, point := range points {
x, y := point[0], point[1]
if x < x1 || x > x2 || y < y1 || y > y2 {
continue
}
if (x == x1 || x == x2) && (y == y1 || y == y2) {
cnt++
continue
}
return false
}
return cnt == 4
}
ans := -1
for i := 0; i < len(points); i++ {
x1, y1 := points[i][0], points[i][1]
for j := 0; j < i; j++ {
x2, y2 := points[j][0], points[j][1]
x3, y3 := min(x1, x2), min(y1, y2)
x4, y4 := max(x1, x2), max(y1, y2)
if check(x3, y3, x4, y4) {
ans = max(ans, (x4-x3)*(y4-y3))
}
}
}
return ans
}
|
3,380 |
Maximum Area Rectangle With Point Constraints I
|
Medium
|
<p>You are given an array <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the coordinates of a point on an infinite plane.</p>
<p>Your task is to find the <strong>maximum </strong>area of a rectangle that:</p>
<ul>
<li>Can be formed using <strong>four</strong> of these points as its corners.</li>
<li>Does <strong>not</strong> contain any other point inside or on its border.</li>
<li>Has its edges <strong>parallel</strong> to the axes.</li>
</ul>
<p>Return the <strong>maximum area</strong> that you can obtain or -1 if no such rectangle is possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3]]</span></p>
<p><strong>Output: </strong>4</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 1 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example1.png" style="width: 229px; height: 228px;" /></strong></p>
<p>We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border<!-- notionvc: f270d0a3-a596-4ed6-9997-2c7416b2b4ee -->. Hence, the maximum possible area would be 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[2,2]]</span></p>
<p><strong>Output:</strong><b> </b>-1</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 2 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example2.png" style="width: 229px; height: 228px;" /></strong></p>
<p>There is only one rectangle possible is with points <code>[1,1], [1,3], [3,1]</code> and <code>[3,3]</code> but <code>[2,2]</code> will always lie inside it. Hence, returning -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]</span></p>
<p><strong>Output: </strong>2</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 3 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example3.png" style="width: 229px; height: 228px;" /></strong></p>
<p>The maximum area rectangle is formed by the points <code>[1,3], [1,2], [3,2], [3,3]</code>, which has an area of 2. Additionally, the points <code>[1,1], [1,2], [3,1], [3,2]</code> also form a valid rectangle with the same area.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Geometry; Array; Math; Enumeration; Sorting
|
Java
|
class Solution {
public int maxRectangleArea(int[][] points) {
int ans = -1;
for (int i = 0; i < points.length; ++i) {
int x1 = points[i][0], y1 = points[i][1];
for (int j = 0; j < i; ++j) {
int x2 = points[j][0], y2 = points[j][1];
int x3 = Math.min(x1, x2), y3 = Math.min(y1, y2);
int x4 = Math.max(x1, x2), y4 = Math.max(y1, y2);
if (check(points, x3, y3, x4, y4)) {
ans = Math.max(ans, (x4 - x3) * (y4 - y3));
}
}
}
return ans;
}
private boolean check(int[][] points, int x1, int y1, int x2, int y2) {
int cnt = 0;
for (var p : points) {
int x = p[0];
int y = p[1];
if (x < x1 || x > x2 || y < y1 || y > y2) {
continue;
}
if ((x == x1 || x == x2) && (y == y1 || y == y2)) {
cnt++;
continue;
}
return false;
}
return cnt == 4;
}
}
|
3,380 |
Maximum Area Rectangle With Point Constraints I
|
Medium
|
<p>You are given an array <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the coordinates of a point on an infinite plane.</p>
<p>Your task is to find the <strong>maximum </strong>area of a rectangle that:</p>
<ul>
<li>Can be formed using <strong>four</strong> of these points as its corners.</li>
<li>Does <strong>not</strong> contain any other point inside or on its border.</li>
<li>Has its edges <strong>parallel</strong> to the axes.</li>
</ul>
<p>Return the <strong>maximum area</strong> that you can obtain or -1 if no such rectangle is possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3]]</span></p>
<p><strong>Output: </strong>4</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 1 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example1.png" style="width: 229px; height: 228px;" /></strong></p>
<p>We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border<!-- notionvc: f270d0a3-a596-4ed6-9997-2c7416b2b4ee -->. Hence, the maximum possible area would be 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[2,2]]</span></p>
<p><strong>Output:</strong><b> </b>-1</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 2 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example2.png" style="width: 229px; height: 228px;" /></strong></p>
<p>There is only one rectangle possible is with points <code>[1,1], [1,3], [3,1]</code> and <code>[3,3]</code> but <code>[2,2]</code> will always lie inside it. Hence, returning -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]</span></p>
<p><strong>Output: </strong>2</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 3 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example3.png" style="width: 229px; height: 228px;" /></strong></p>
<p>The maximum area rectangle is formed by the points <code>[1,3], [1,2], [3,2], [3,3]</code>, which has an area of 2. Additionally, the points <code>[1,1], [1,2], [3,1], [3,2]</code> also form a valid rectangle with the same area.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Geometry; Array; Math; Enumeration; Sorting
|
Python
|
class Solution:
def maxRectangleArea(self, points: List[List[int]]) -> int:
def check(x1: int, y1: int, x2: int, y2: int) -> bool:
cnt = 0
for x, y in points:
if x < x1 or x > x2 or y < y1 or y > y2:
continue
if (x == x1 or x == x2) and (y == y1 or y == y2):
cnt += 1
continue
return False
return cnt == 4
ans = -1
for i, (x1, y1) in enumerate(points):
for x2, y2 in points[:i]:
x3, y3 = min(x1, x2), min(y1, y2)
x4, y4 = max(x1, x2), max(y1, y2)
if check(x3, y3, x4, y4):
ans = max(ans, (x4 - x3) * (y4 - y3))
return ans
|
3,380 |
Maximum Area Rectangle With Point Constraints I
|
Medium
|
<p>You are given an array <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the coordinates of a point on an infinite plane.</p>
<p>Your task is to find the <strong>maximum </strong>area of a rectangle that:</p>
<ul>
<li>Can be formed using <strong>four</strong> of these points as its corners.</li>
<li>Does <strong>not</strong> contain any other point inside or on its border.</li>
<li>Has its edges <strong>parallel</strong> to the axes.</li>
</ul>
<p>Return the <strong>maximum area</strong> that you can obtain or -1 if no such rectangle is possible.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3]]</span></p>
<p><strong>Output: </strong>4</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 1 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example1.png" style="width: 229px; height: 228px;" /></strong></p>
<p>We can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border<!-- notionvc: f270d0a3-a596-4ed6-9997-2c7416b2b4ee -->. Hence, the maximum possible area would be 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[2,2]]</span></p>
<p><strong>Output:</strong><b> </b>-1</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 2 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example2.png" style="width: 229px; height: 228px;" /></strong></p>
<p>There is only one rectangle possible is with points <code>[1,1], [1,3], [3,1]</code> and <code>[3,3]</code> but <code>[2,2]</code> will always lie inside it. Hence, returning -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]</span></p>
<p><strong>Output: </strong>2</p>
<p><strong>Explanation:</strong></p>
<p><strong class="example"><img alt="Example 3 diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3380.Maximum%20Area%20Rectangle%20With%20Point%20Constraints%20I/images/example3.png" style="width: 229px; height: 228px;" /></strong></p>
<p>The maximum area rectangle is formed by the points <code>[1,3], [1,2], [3,2], [3,3]</code>, which has an area of 2. Additionally, the points <code>[1,1], [1,2], [3,1], [3,2]</code> also form a valid rectangle with the same area.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Geometry; Array; Math; Enumeration; Sorting
|
TypeScript
|
function maxRectangleArea(points: number[][]): number {
const check = (x1: number, y1: number, x2: number, y2: number): boolean => {
let cnt = 0;
for (const point of points) {
const [x, y] = point;
if (x < x1 || x > x2 || y < y1 || y > y2) {
continue;
}
if ((x === x1 || x === x2) && (y === y1 || y === y2)) {
cnt++;
continue;
}
return false;
}
return cnt === 4;
};
let ans = -1;
for (let i = 0; i < points.length; i++) {
const [x1, y1] = points[i];
for (let j = 0; j < i; j++) {
const [x2, y2] = points[j];
const [x3, y3] = [Math.min(x1, x2), Math.min(y1, y2)];
const [x4, y4] = [Math.max(x1, x2), Math.max(y1, y2)];
if (check(x3, y3, x4, y4)) {
ans = Math.max(ans, (x4 - x3) * (y4 - y3));
}
}
}
return ans;
}
|
3,381 |
Maximum Subarray Sum With Length Divisible by K
|
Medium
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>Return the <strong>maximum</strong> sum of a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>, such that the size of the subarray is <strong>divisible</strong> by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1, 2]</code> with sum 3 has length equal to 2 which is divisible by 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3,-4,-5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-10</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[-1, -2, -3, -4]</code> which has length equal to 4 which is divisible by 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-5,1,2,-3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[1, 2, -3, 4]</code> which has length equal to 4 which is divisible by 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
C++
|
class Solution {
public:
long long maxSubarraySum(vector<int>& nums, int k) {
using ll = long long;
ll inf = 1e18;
vector<ll> f(k, inf);
ll ans = -inf;
ll s = 0;
f[k - 1] = 0;
for (int i = 0; i < nums.size(); ++i) {
s += nums[i];
ans = max(ans, s - f[i % k]);
f[i % k] = min(f[i % k], s);
}
return ans;
}
};
|
3,381 |
Maximum Subarray Sum With Length Divisible by K
|
Medium
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>Return the <strong>maximum</strong> sum of a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>, such that the size of the subarray is <strong>divisible</strong> by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1, 2]</code> with sum 3 has length equal to 2 which is divisible by 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3,-4,-5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-10</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[-1, -2, -3, -4]</code> which has length equal to 4 which is divisible by 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-5,1,2,-3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[1, 2, -3, 4]</code> which has length equal to 4 which is divisible by 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Go
|
func maxSubarraySum(nums []int, k int) int64 {
inf := int64(1) << 62
f := make([]int64, k)
for i := range f {
f[i] = inf
}
f[k-1] = 0
var s, ans int64
ans = -inf
for i := 0; i < len(nums); i++ {
s += int64(nums[i])
ans = max(ans, s-f[i%k])
f[i%k] = min(f[i%k], s)
}
return ans
}
|
3,381 |
Maximum Subarray Sum With Length Divisible by K
|
Medium
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>Return the <strong>maximum</strong> sum of a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>, such that the size of the subarray is <strong>divisible</strong> by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1, 2]</code> with sum 3 has length equal to 2 which is divisible by 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3,-4,-5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-10</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[-1, -2, -3, -4]</code> which has length equal to 4 which is divisible by 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-5,1,2,-3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[1, 2, -3, 4]</code> which has length equal to 4 which is divisible by 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Java
|
class Solution {
public long maxSubarraySum(int[] nums, int k) {
long[] f = new long[k];
final long inf = 1L << 62;
Arrays.fill(f, inf);
f[k - 1] = 0;
long s = 0;
long ans = -inf;
for (int i = 0; i < nums.length; ++i) {
s += nums[i];
ans = Math.max(ans, s - f[i % k]);
f[i % k] = Math.min(f[i % k], s);
}
return ans;
}
}
|
3,381 |
Maximum Subarray Sum With Length Divisible by K
|
Medium
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>Return the <strong>maximum</strong> sum of a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>, such that the size of the subarray is <strong>divisible</strong> by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1, 2]</code> with sum 3 has length equal to 2 which is divisible by 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3,-4,-5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-10</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[-1, -2, -3, -4]</code> which has length equal to 4 which is divisible by 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-5,1,2,-3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[1, 2, -3, 4]</code> which has length equal to 4 which is divisible by 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Python
|
class Solution:
def maxSubarraySum(self, nums: List[int], k: int) -> int:
f = [inf] * k
ans = -inf
s = f[-1] = 0
for i, x in enumerate(nums):
s += x
ans = max(ans, s - f[i % k])
f[i % k] = min(f[i % k], s)
return ans
|
3,381 |
Maximum Subarray Sum With Length Divisible by K
|
Medium
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>Return the <strong>maximum</strong> sum of a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>, such that the size of the subarray is <strong>divisible</strong> by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The subarray <code>[1, 2]</code> with sum 3 has length equal to 2 which is divisible by 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3,-4,-5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-10</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[-1, -2, -3, -4]</code> which has length equal to 4 which is divisible by 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-5,1,2,-3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum sum subarray is <code>[1, 2, -3, 4]</code> which has length equal to 4 which is divisible by 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
TypeScript
|
function maxSubarraySum(nums: number[], k: number): number {
const f: number[] = Array(k).fill(Infinity);
f[k - 1] = 0;
let ans = -Infinity;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i];
ans = Math.max(ans, s - f[i % k]);
f[i % k] = Math.min(f[i % k], s);
}
return ans;
}
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
C++
|
class Solution {
public:
vector<int> vis;
vector<vector<int>> g;
vector<int> seq;
int minRunesToAdd(int n, vector<int>& crystals, vector<int>& flowFrom, vector<int>& flowTo) {
g.resize(n);
for (int i = 0; i < flowFrom.size(); ++i) {
g[flowFrom[i]].push_back(flowTo[i]);
}
deque<int> q;
vis.resize(n, 0);
for (int i : crystals) {
vis[i] = 1;
q.push_back(i);
}
bfs(q);
for (int i = 0; i < n; ++i) {
if (vis[i] == 0) {
dfs(i);
}
}
int ans = 0;
for (int i = seq.size() - 1; i >= 0; --i) {
int a = seq[i];
if (vis[a] == 2) {
vis[a] = 1;
q.clear();
q.push_back(a);
bfs(q);
++ans;
}
}
return ans;
}
private:
void bfs(deque<int>& q) {
while (!q.empty()) {
int a = q.front();
q.pop_front();
for (int b : g[a]) {
if (vis[b] == 1) {
continue;
}
vis[b] = 1;
q.push_back(b);
}
}
}
void dfs(int a) {
vis[a] = 2;
for (int b : g[a]) {
if (vis[b] > 0) {
continue;
}
dfs(b);
}
seq.push_back(a);
}
};
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Go
|
func minRunesToAdd(n int, crystals []int, flowFrom []int, flowTo []int) (ans int) {
g := make([][]int, n)
for i := 0; i < len(flowFrom); i++ {
a, b := flowFrom[i], flowTo[i]
g[a] = append(g[a], b)
}
vis := make([]int, n)
for _, x := range crystals {
vis[x] = 1
}
bfs := func(q []int) {
for len(q) > 0 {
a := q[0]
q = q[1:]
for _, b := range g[a] {
if vis[b] == 1 {
continue
}
vis[b] = 1
q = append(q, b)
}
}
}
seq := []int{}
var dfs func(a int)
dfs = func(a int) {
vis[a] = 2
for _, b := range g[a] {
if vis[b] > 0 {
continue
}
dfs(b)
}
seq = append(seq, a)
}
q := crystals
bfs(q)
for i := 0; i < n; i++ {
if vis[i] == 0 {
dfs(i)
}
}
for i, j := 0, len(seq)-1; i < j; i, j = i+1, j-1 {
seq[i], seq[j] = seq[j], seq[i]
}
for _, i := range seq {
if vis[i] == 2 {
q = []int{i}
vis[i] = 1
bfs(q)
ans++
}
}
return
}
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Java
|
class Solution {
private int[] vis;
private List<Integer>[] g;
private List<Integer> seq = new ArrayList<>();
public int minRunesToAdd(int n, int[] crystals, int[] flowFrom, int[] flowTo) {
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 0; i < flowFrom.length; ++i) {
g[flowFrom[i]].add(flowTo[i]);
}
Deque<Integer> q = new ArrayDeque<>();
vis = new int[n];
for (int i : crystals) {
vis[i] = 1;
q.offer(i);
}
bfs(q);
for (int i = 0; i < n; ++i) {
if (vis[i] == 0) {
dfs(i);
}
}
int ans = 0;
for (int i = seq.size() - 1; i >= 0; --i) {
int a = seq.get(i);
if (vis[a] == 2) {
vis[a] = 1;
q.clear();
q.offer(a);
bfs(q);
++ans;
}
}
return ans;
}
private void bfs(Deque<Integer> q) {
while (!q.isEmpty()) {
int a = q.poll();
for (int b : g[a]) {
if (vis[b] == 1) {
continue;
}
vis[b] = 1;
q.offer(b);
}
}
}
private void dfs(int a) {
vis[a] = 2;
for (int b : g[a]) {
if (vis[b] > 0) {
continue;
}
dfs(b);
}
seq.add(a);
}
}
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Python
|
class Solution:
def minRunesToAdd(
self, n: int, crystals: List[int], flowFrom: List[int], flowTo: List[int]
) -> int:
def bfs(q: Deque[int]):
while q:
a = q.popleft()
for b in g[a]:
if vis[b] == 1:
continue
vis[b] = 1
q.append(b)
def dfs(a: int):
vis[a] = 2
for b in g[a]:
if vis[b] > 0:
continue
dfs(b)
seq.append(a)
g = [[] for _ in range(n)]
for a, b in zip(flowFrom, flowTo):
g[a].append(b)
q = deque(crystals)
vis = [0] * n
for x in crystals:
vis[x] = 1
bfs(q)
seq = []
for i in range(n):
if vis[i] == 0:
dfs(i)
seq.reverse()
ans = 0
for i in seq:
if vis[i] == 2:
q = deque([i])
vis[i] = 1
bfs(q)
ans += 1
return ans
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
TypeScript
|
function minRunesToAdd(
n: number,
crystals: number[],
flowFrom: number[],
flowTo: number[],
): number {
const g: number[][] = Array.from({ length: n }, () => []);
for (let i = 0; i < flowFrom.length; i++) {
const a = flowFrom[i],
b = flowTo[i];
g[a].push(b);
}
const vis: number[] = Array(n).fill(0);
for (const x of crystals) {
vis[x] = 1;
}
const bfs = (q: number[]) => {
while (q.length > 0) {
const a = q.shift()!;
for (const b of g[a]) {
if (vis[b] === 1) continue;
vis[b] = 1;
q.push(b);
}
}
};
const seq: number[] = [];
const dfs = (a: number) => {
vis[a] = 2;
for (const b of g[a]) {
if (vis[b] > 0) continue;
dfs(b);
}
seq.push(a);
};
bfs(crystals);
for (let i = 0; i < n; i++) {
if (vis[i] === 0) {
dfs(i);
}
}
seq.reverse();
let ans = 0;
for (const i of seq) {
if (vis[i] === 2) {
bfs([i]);
vis[i] = 1;
ans++;
}
}
return ans;
}
|
3,384 |
Team Dominance by Pass Success
|
Hard
|
<p>Table: <code>Teams</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| player_id | int |
| team_name | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
</pre>
<p>Table: <code>Passes</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| pass_from | int |
| time_stamp | varchar |
| pass_to | int |
+-------------+---------+
(pass_from, time_stamp) is the primary key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
</pre>
<p>Write a solution to calculate the <strong>dominance score</strong> for each team in<strong> both halves of the match</strong>. The rules are as follows:</p>
<ul>
<li>A match is divided into two halves: <strong>first half</strong> (<code>00:00</code>-<code><font face="monospace">45:00</font></code> minutes) and <strong>second half </strong>(<code>45:01</code>-<code>90:00</code> minutes)</li>
<li>The dominance score is calculated based on successful and intercepted passes:
<ul>
<li>When pass_to is a player from the <strong>same team</strong>: +<code>1</code> point</li>
<li>When pass_to is a player from the <strong>opposing team</strong> (interception): <code>-1</code> point</li>
</ul>
</li>
<li>A higher dominance score indicates better passing performance</li>
</ul>
<p>Return <em>the result table ordered </em><em>by</em> <code>team_name</code> and <code>half_number</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Teams table:</p>
<pre class="example-io">
+------------+-----------+
| player_id | team_name |
+------------+-----------+
| 1 | Arsenal |
| 2 | Arsenal |
| 3 | Arsenal |
| 4 | Chelsea |
| 5 | Chelsea |
| 6 | Chelsea |
+------------+-----------+
</pre>
<p>Passes table:</p>
<pre class="example-io">
+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1 | 00:15 | 2 |
| 2 | 00:45 | 3 |
| 3 | 01:15 | 1 |
| 4 | 00:30 | 1 |
| 2 | 46:00 | 3 |
| 3 | 46:15 | 4 |
| 1 | 46:45 | 2 |
| 5 | 46:30 | 6 |
+-----------+------------+---------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-------------+-----------+
| team_name | half_number | dominance |
+-----------+-------------+-----------+
| Arsenal | 1 | 3 |
| Arsenal | 2 | 1 |
| Chelsea | 1 | -1 |
| Chelsea | 2 | 1 |
+-----------+-------------+-----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>First Half (00:00-45:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>1 → 2 (00:15): Successful pass (+1)</li>
<li>2 → 3 (00:45): Successful pass (+1)</li>
<li>3 → 1 (01:15): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>4 → 1 (00:30): Intercepted by Arsenal (-1)</li>
</ul>
</li>
</ul>
</li>
<li><strong>Second Half (45:01-90:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>2 → 3 (46:00): Successful pass (+1)</li>
<li>3 → 4 (46:15): Intercepted by Chelsea (-1)</li>
<li>1 → 2 (46:45): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>5 → 6 (46:30): Successful pass (+1)</li>
</ul>
</li>
</ul>
</li>
<li>The results are ordered by team_name and then half_number</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def calculate_team_dominance(teams: pd.DataFrame, passes: pd.DataFrame) -> pd.DataFrame:
passes_with_teams = passes.merge(
teams, left_on="pass_from", right_on="player_id", suffixes=("", "_team_from")
).merge(
teams,
left_on="pass_to",
right_on="player_id",
suffixes=("_team_from", "_team_to"),
)
passes_with_teams["half_number"] = passes_with_teams["time_stamp"].apply(
lambda x: 1 if x <= "45:00" else 2
)
passes_with_teams["dominance"] = passes_with_teams.apply(
lambda row: 1 if row["team_name_team_from"] == row["team_name_team_to"] else -1,
axis=1,
)
result = (
passes_with_teams.groupby(["team_name_team_from", "half_number"])["dominance"]
.sum()
.reset_index()
)
result.columns = ["team_name", "half_number", "dominance"]
result = result.sort_values(by=["team_name", "half_number"])
return result
|
3,384 |
Team Dominance by Pass Success
|
Hard
|
<p>Table: <code>Teams</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| player_id | int |
| team_name | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
</pre>
<p>Table: <code>Passes</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| pass_from | int |
| time_stamp | varchar |
| pass_to | int |
+-------------+---------+
(pass_from, time_stamp) is the primary key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
</pre>
<p>Write a solution to calculate the <strong>dominance score</strong> for each team in<strong> both halves of the match</strong>. The rules are as follows:</p>
<ul>
<li>A match is divided into two halves: <strong>first half</strong> (<code>00:00</code>-<code><font face="monospace">45:00</font></code> minutes) and <strong>second half </strong>(<code>45:01</code>-<code>90:00</code> minutes)</li>
<li>The dominance score is calculated based on successful and intercepted passes:
<ul>
<li>When pass_to is a player from the <strong>same team</strong>: +<code>1</code> point</li>
<li>When pass_to is a player from the <strong>opposing team</strong> (interception): <code>-1</code> point</li>
</ul>
</li>
<li>A higher dominance score indicates better passing performance</li>
</ul>
<p>Return <em>the result table ordered </em><em>by</em> <code>team_name</code> and <code>half_number</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Teams table:</p>
<pre class="example-io">
+------------+-----------+
| player_id | team_name |
+------------+-----------+
| 1 | Arsenal |
| 2 | Arsenal |
| 3 | Arsenal |
| 4 | Chelsea |
| 5 | Chelsea |
| 6 | Chelsea |
+------------+-----------+
</pre>
<p>Passes table:</p>
<pre class="example-io">
+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1 | 00:15 | 2 |
| 2 | 00:45 | 3 |
| 3 | 01:15 | 1 |
| 4 | 00:30 | 1 |
| 2 | 46:00 | 3 |
| 3 | 46:15 | 4 |
| 1 | 46:45 | 2 |
| 5 | 46:30 | 6 |
+-----------+------------+---------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-------------+-----------+
| team_name | half_number | dominance |
+-----------+-------------+-----------+
| Arsenal | 1 | 3 |
| Arsenal | 2 | 1 |
| Chelsea | 1 | -1 |
| Chelsea | 2 | 1 |
+-----------+-------------+-----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>First Half (00:00-45:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>1 → 2 (00:15): Successful pass (+1)</li>
<li>2 → 3 (00:45): Successful pass (+1)</li>
<li>3 → 1 (01:15): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>4 → 1 (00:30): Intercepted by Arsenal (-1)</li>
</ul>
</li>
</ul>
</li>
<li><strong>Second Half (45:01-90:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>2 → 3 (46:00): Successful pass (+1)</li>
<li>3 → 4 (46:15): Intercepted by Chelsea (-1)</li>
<li>1 → 2 (46:45): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>5 → 6 (46:30): Successful pass (+1)</li>
</ul>
</li>
</ul>
</li>
<li>The results are ordered by team_name and then half_number</li>
</ul>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
t1.team_name,
IF(time_stamp <= '45:00', 1, 2) half_number,
IF(t1.team_name = t2.team_name, 1, -1) dominance
FROM
Passes p
JOIN Teams t1 ON p.pass_from = t1.player_id
JOIN Teams t2 ON p.pass_to = t2.player_id
)
SELECT team_name, half_number, SUM(dominance) dominance
FROM T
GROUP BY 1, 2
ORDER BY 1, 2;
|
3,385 |
Minimum Time to Break Locks II
|
Hard
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">X</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>X</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach at least <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>X</code> increases by 1.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>2</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>3</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>1</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>2</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>3</td>
<td>Nothing</td>
<td>3</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>3</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>4</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 6 minutes; thus, the answer is 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 80</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
<li><code>n == strength.length</code></li>
</ul>
|
Depth-First Search; Graph; Array
|
Java
|
class MCFGraph {
static class Edge {
int src, dst, cap, flow, cost;
Edge(int src, int dst, int cap, int flow, int cost) {
this.src = src;
this.dst = dst;
this.cap = cap;
this.flow = flow;
this.cost = cost;
}
}
static class _Edge {
int dst, cap, cost;
_Edge rev;
_Edge(int dst, int cap, int cost) {
this.dst = dst;
this.cap = cap;
this.cost = cost;
this.rev = null;
}
}
private int n;
private List<List<_Edge>> graph;
private List<_Edge> edges;
public MCFGraph(int n) {
this.n = n;
this.graph = new ArrayList<>();
this.edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
}
public int addEdge(int src, int dst, int cap, int cost) {
assert (0 <= src && src < n);
assert (0 <= dst && dst < n);
assert (0 <= cap);
int m = edges.size();
_Edge e = new _Edge(dst, cap, cost);
_Edge re = new _Edge(src, 0, -cost);
e.rev = re;
re.rev = e;
graph.get(src).add(e);
graph.get(dst).add(re);
edges.add(e);
return m;
}
public Edge getEdge(int i) {
assert (0 <= i && i < edges.size());
_Edge e = edges.get(i);
_Edge re = e.rev;
return new Edge(re.dst, e.dst, e.cap + re.cap, re.cap, e.cost);
}
public List<Edge> edges() {
List<Edge> result = new ArrayList<>();
for (int i = 0; i < edges.size(); i++) {
result.add(getEdge(i));
}
return result;
}
public int[] flow(int s, int t, Integer flowLimit) {
List<int[]> result = slope(s, t, flowLimit);
return result.get(result.size() - 1);
}
public List<int[]> slope(int s, int t, Integer flowLimit) {
assert (0 <= s && s < n);
assert (0 <= t && t < n);
assert (s != t);
if (flowLimit == null) {
flowLimit = graph.get(s).stream().mapToInt(e -> e.cap).sum();
}
int[] dual = new int[n];
Tuple[] prev = new Tuple[n];
List<int[]> result = new ArrayList<>();
result.add(new int[] {0, 0});
while (true) {
if (!refineDual(s, t, dual, prev)) {
break;
}
int f = flowLimit;
int v = t;
while (prev[v] != null) {
Tuple tuple = prev[v];
int u = tuple.first;
_Edge e = tuple.second;
f = Math.min(f, e.cap);
v = u;
}
v = t;
while (prev[v] != null) {
Tuple tuple = prev[v];
int u = tuple.first;
_Edge e = tuple.second;
e.cap -= f;
e.rev.cap += f;
v = u;
}
int c = -dual[s];
result.add(new int[] {
result.get(result.size() - 1)[0] + f, result.get(result.size() - 1)[1] + f * c});
if (c == result.get(result.size() - 2)[1]) {
result.remove(result.size() - 2);
}
}
return result;
}
private boolean refineDual(int s, int t, int[] dual, Tuple[] prev) {
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.add(new int[] {0, s});
boolean[] visited = new boolean[n];
Integer[] dist = new Integer[n];
Arrays.fill(dist, null);
dist[s] = 0;
while (!pq.isEmpty()) {
int[] current = pq.poll();
int distV = current[0];
int v = current[1];
if (visited[v]) continue;
visited[v] = true;
if (v == t) break;
int dualV = dual[v];
for (_Edge e : graph.get(v)) {
int w = e.dst;
if (visited[w] || e.cap == 0) continue;
int reducedCost = e.cost - dual[w] + dualV;
int newDist = distV + reducedCost;
Integer distW = dist[w];
if (distW == null || newDist < distW) {
dist[w] = newDist;
prev[w] = new Tuple(v, e);
pq.add(new int[] {newDist, w});
}
}
}
if (!visited[t]) return false;
int distT = dist[t];
for (int v = 0; v < n; v++) {
if (visited[v]) {
dual[v] -= distT - dist[v];
}
}
return true;
}
static class Tuple {
int first;
_Edge second;
Tuple(int first, _Edge second) {
this.first = first;
this.second = second;
}
}
}
class Solution {
public int findMinimumTime(int[] strength) {
int n = strength.length;
int s = n * 2;
int t = s + 1;
MCFGraph g = new MCFGraph(t + 1);
for (int i = 0; i < n; i++) {
g.addEdge(s, i, 1, 0);
g.addEdge(i + n, t, 1, 0);
for (int j = 0; j < n; j++) {
g.addEdge(i, j + n, 1, (strength[i] - 1) / (j + 1) + 1);
}
}
return g.flow(s, t, n)[1];
}
}
|
3,385 |
Minimum Time to Break Locks II
|
Hard
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">X</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>X</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach at least <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>X</code> increases by 1.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>2</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>3</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>1</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>2</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>3</td>
<td>Nothing</td>
<td>3</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>3</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>4</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 6 minutes; thus, the answer is 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 80</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
<li><code>n == strength.length</code></li>
</ul>
|
Depth-First Search; Graph; Array
|
Python
|
class MCFGraph:
class Edge(NamedTuple):
src: int
dst: int
cap: int
flow: int
cost: int
class _Edge:
def __init__(self, dst: int, cap: int, cost: int) -> None:
self.dst = dst
self.cap = cap
self.cost = cost
self.rev: Optional[MCFGraph._Edge] = None
def __init__(self, n: int) -> None:
self._n = n
self._g: List[List[MCFGraph._Edge]] = [[] for _ in range(n)]
self._edges: List[MCFGraph._Edge] = []
def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:
assert 0 <= src < self._n
assert 0 <= dst < self._n
assert 0 <= cap
m = len(self._edges)
e = MCFGraph._Edge(dst, cap, cost)
re = MCFGraph._Edge(src, 0, -cost)
e.rev = re
re.rev = e
self._g[src].append(e)
self._g[dst].append(re)
self._edges.append(e)
return m
def get_edge(self, i: int) -> Edge:
assert 0 <= i < len(self._edges)
e = self._edges[i]
re = cast(MCFGraph._Edge, e.rev)
return MCFGraph.Edge(re.dst, e.dst, e.cap + re.cap, re.cap, e.cost)
def edges(self) -> List[Edge]:
return [self.get_edge(i) for i in range(len(self._edges))]
def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> Tuple[int, int]:
return self.slope(s, t, flow_limit)[-1]
def slope(
self, s: int, t: int, flow_limit: Optional[int] = None
) -> List[Tuple[int, int]]:
assert 0 <= s < self._n
assert 0 <= t < self._n
assert s != t
if flow_limit is None:
flow_limit = cast(int, sum(e.cap for e in self._g[s]))
dual = [0] * self._n
prev: List[Optional[Tuple[int, MCFGraph._Edge]]] = [None] * self._n
def refine_dual() -> bool:
pq = [(0, s)]
visited = [False] * self._n
dist: List[Optional[int]] = [None] * self._n
dist[s] = 0
while pq:
dist_v, v = heappop(pq)
if visited[v]:
continue
visited[v] = True
if v == t:
break
dual_v = dual[v]
for e in self._g[v]:
w = e.dst
if visited[w] or e.cap == 0:
continue
reduced_cost = e.cost - dual[w] + dual_v
new_dist = dist_v + reduced_cost
dist_w = dist[w]
if dist_w is None or new_dist < dist_w:
dist[w] = new_dist
prev[w] = v, e
heappush(pq, (new_dist, w))
else:
return False
dist_t = dist[t]
for v in range(self._n):
if visited[v]:
dual[v] -= cast(int, dist_t) - cast(int, dist[v])
return True
flow = 0
cost = 0
prev_cost_per_flow: Optional[int] = None
result = [(flow, cost)]
while flow < flow_limit:
if not refine_dual():
break
f = flow_limit - flow
v = t
while prev[v] is not None:
u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
f = min(f, e.cap)
v = u
v = t
while prev[v] is not None:
u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
e.cap -= f
assert e.rev is not None
e.rev.cap += f
v = u
c = -dual[s]
flow += f
cost += f * c
if c == prev_cost_per_flow:
result.pop()
result.append((flow, cost))
prev_cost_per_flow = c
return result
class Solution:
def findMinimumTime(self, a: List[int]) -> int:
n = len(a)
s = n * 2
t = s + 1
g = MCFGraph(t + 1)
for i in range(n):
g.add_edge(s, i, 1, 0)
g.add_edge(i + n, t, 1, 0)
for j in range(n):
g.add_edge(i, j + n, 1, (a[i] - 1) // (j + 1) + 1)
return g.flow(s, t, n)[1]
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int buttonWithLongestTime(vector<vector<int>>& events) {
int ans = events[0][0], t = events[0][1];
for (int k = 1; k < events.size(); ++k) {
int i = events[k][0], t2 = events[k][1], t1 = events[k - 1][1];
int d = t2 - t1;
if (d > t || (d == t && ans > i)) {
ans = i;
t = d;
}
}
return ans;
}
};
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Go
|
func buttonWithLongestTime(events [][]int) int {
ans, t := events[0][0], events[0][1]
for k, e := range events[1:] {
i, t2, t1 := e[0], e[1], events[k][1]
d := t2 - t1
if d > t || (d == t && i < ans) {
ans, t = i, d
}
}
return ans
}
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Java
|
class Solution {
public int buttonWithLongestTime(int[][] events) {
int ans = events[0][0], t = events[0][1];
for (int k = 1; k < events.length; ++k) {
int i = events[k][0], t2 = events[k][1], t1 = events[k - 1][1];
int d = t2 - t1;
if (d > t || (d == t && ans > i)) {
ans = i;
t = d;
}
}
return ans;
}
}
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Python
|
class Solution:
def buttonWithLongestTime(self, events: List[List[int]]) -> int:
ans, t = events[0]
for (_, t1), (i, t2) in pairwise(events):
d = t2 - t1
if d > t or (d == t and i < ans):
ans, t = i, d
return ans
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
TypeScript
|
function buttonWithLongestTime(events: number[][]): number {
let [ans, t] = events[0];
for (let k = 1; k < events.length; ++k) {
const [i, t2] = events[k];
const d = t2 - events[k - 1][1];
if (d > t || (d === t && i < ans)) {
ans = i;
t = d;
}
}
return ans;
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
C++
|
class Solution {
public:
double maxAmount(string initialCurrency, vector<vector<string>>& pairs1, vector<double>& rates1, vector<vector<string>>& pairs2, vector<double>& rates2) {
unordered_map<string, double> d1 = build(pairs1, rates1, initialCurrency);
unordered_map<string, double> d2 = build(pairs2, rates2, initialCurrency);
double ans = 0;
for (const auto& [currency, rate] : d2) {
if (d1.find(currency) != d1.end()) {
ans = max(ans, d1[currency] / rate);
}
}
return ans;
}
private:
unordered_map<string, double> build(vector<vector<string>>& pairs, vector<double>& rates, const string& init) {
unordered_map<string, vector<pair<string, double>>> g;
unordered_map<string, double> d;
for (int i = 0; i < pairs.size(); ++i) {
const string& a = pairs[i][0];
const string& b = pairs[i][1];
double r = rates[i];
g[a].push_back({b, r});
g[b].push_back({a, 1 / r});
}
auto dfs = [&](this auto&& dfs, const string& a, double v) -> void {
if (d.find(a) != d.end()) {
return;
}
d[a] = v;
for (const auto& [b, r] : g[a]) {
if (d.find(b) == d.end()) {
dfs(b, v * r);
}
}
};
dfs(init, 1.0);
return d;
}
};
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Go
|
type Pair struct {
Key string
Value float64
}
func maxAmount(initialCurrency string, pairs1 [][]string, rates1 []float64, pairs2 [][]string, rates2 []float64) (ans float64) {
d1 := build(pairs1, rates1, initialCurrency)
d2 := build(pairs2, rates2, initialCurrency)
for currency, rate := range d2 {
if val, found := d1[currency]; found {
ans = max(ans, val/rate)
}
}
return
}
func build(pairs [][]string, rates []float64, init string) map[string]float64 {
g := make(map[string][]Pair)
d := make(map[string]float64)
for i := 0; i < len(pairs); i++ {
a := pairs[i][0]
b := pairs[i][1]
r := rates[i]
g[a] = append(g[a], Pair{Key: b, Value: r})
g[b] = append(g[b], Pair{Key: a, Value: 1.0 / r})
}
dfs(g, d, init, 1.0)
return d
}
func dfs(g map[string][]Pair, d map[string]float64, a string, v float64) {
if _, found := d[a]; found {
return
}
d[a] = v
for _, pair := range g[a] {
b := pair.Key
r := pair.Value
if _, found := d[b]; !found {
dfs(g, d, b, v*r)
}
}
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Java
|
class Solution {
public double maxAmount(String initialCurrency, List<List<String>> pairs1, double[] rates1,
List<List<String>> pairs2, double[] rates2) {
Map<String, Double> d1 = build(pairs1, rates1, initialCurrency);
Map<String, Double> d2 = build(pairs2, rates2, initialCurrency);
double ans = 0;
for (Map.Entry<String, Double> entry : d2.entrySet()) {
String currency = entry.getKey();
double rate = entry.getValue();
if (d1.containsKey(currency)) {
ans = Math.max(ans, d1.get(currency) / rate);
}
}
return ans;
}
private Map<String, Double> build(List<List<String>> pairs, double[] rates, String init) {
Map<String, List<Pair<String, Double>>> g = new HashMap<>();
Map<String, Double> d = new HashMap<>();
for (int i = 0; i < pairs.size(); ++i) {
String a = pairs.get(i).get(0);
String b = pairs.get(i).get(1);
double r = rates[i];
g.computeIfAbsent(a, k -> new ArrayList<>()).add(new Pair<>(b, r));
g.computeIfAbsent(b, k -> new ArrayList<>()).add(new Pair<>(a, 1 / r));
}
dfs(g, d, init, 1.0);
return d;
}
private void dfs(
Map<String, List<Pair<String, Double>>> g, Map<String, Double> d, String a, double v) {
if (d.containsKey(a)) {
return;
}
d.put(a, v);
for (Pair<String, Double> pair : g.getOrDefault(a, List.of())) {
String b = pair.getKey();
double r = pair.getValue();
if (!d.containsKey(b)) {
dfs(g, d, b, v * r);
}
}
}
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Python
|
class Solution:
def maxAmount(
self,
initialCurrency: str,
pairs1: List[List[str]],
rates1: List[float],
pairs2: List[List[str]],
rates2: List[float],
) -> float:
d1 = self.build(pairs1, rates1, initialCurrency)
d2 = self.build(pairs2, rates2, initialCurrency)
return max(d1.get(a, 0) / r2 for a, r2 in d2.items())
def build(
self, pairs: List[List[str]], rates: List[float], init: str
) -> Dict[str, float]:
def dfs(a: str, v: float):
d[a] = v
for b, r in g[a]:
if b not in d:
dfs(b, v * r)
g = defaultdict(list)
for (a, b), r in zip(pairs, rates):
g[a].append((b, r))
g[b].append((a, 1 / r))
d = {}
dfs(init, 1)
return d
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
TypeScript
|
class Pair {
constructor(
public key: string,
public value: number,
) {}
}
function maxAmount(
initialCurrency: string,
pairs1: string[][],
rates1: number[],
pairs2: string[][],
rates2: number[],
): number {
const d1 = build(pairs1, rates1, initialCurrency);
const d2 = build(pairs2, rates2, initialCurrency);
let ans = 0;
for (const [currency, rate] of Object.entries(d2)) {
if (currency in d1) {
ans = Math.max(ans, d1[currency] / rate);
}
}
return ans;
}
function build(pairs: string[][], rates: number[], init: string): { [key: string]: number } {
const g: { [key: string]: Pair[] } = {};
const d: { [key: string]: number } = {};
for (let i = 0; i < pairs.length; ++i) {
const a = pairs[i][0];
const b = pairs[i][1];
const r = rates[i];
if (!g[a]) g[a] = [];
if (!g[b]) g[b] = [];
g[a].push(new Pair(b, r));
g[b].push(new Pair(a, 1 / r));
}
dfs(g, d, init, 1.0);
return d;
}
function dfs(
g: { [key: string]: Pair[] },
d: { [key: string]: number },
a: string,
v: number,
): void {
if (a in d) {
return;
}
d[a] = v;
for (const pair of g[a] || []) {
const b = pair.key;
const r = pair.value;
if (!(b in d)) {
dfs(g, d, b, v * r);
}
}
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int beautifulSplits(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> lcp(n + 1, vector<int>(n + 1, 0));
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (nums[i] == nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
int ans = 0;
for (int i = 1; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
bool a = (i <= j - i) && (lcp[0][i] >= i);
bool b = (j - i <= n - j) && (lcp[i][j] >= j - i);
if (a || b) {
ans++;
}
}
}
return ans;
}
};
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func beautifulSplits(nums []int) (ans int) {
n := len(nums)
lcp := make([][]int, n+1)
for i := range lcp {
lcp[i] = make([]int, n+1)
}
for i := n - 1; i >= 0; i-- {
for j := n - 1; j > i; j-- {
if nums[i] == nums[j] {
lcp[i][j] = lcp[i+1][j+1] + 1
}
}
}
for i := 1; i < n-1; i++ {
for j := i + 1; j < n; j++ {
a := i <= j-i && lcp[0][i] >= i
b := j-i <= n-j && lcp[i][j] >= j-i
if a || b {
ans++
}
}
}
return
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int beautifulSplits(int[] nums) {
int n = nums.length;
int[][] lcp = new int[n + 1][n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (nums[i] == nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
int ans = 0;
for (int i = 1; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
boolean a = (i <= j - i) && (lcp[0][i] >= i);
boolean b = (j - i <= n - j) && (lcp[i][j] >= j - i);
if (a || b) {
ans++;
}
}
}
return ans;
}
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def beautifulSplits(self, nums: List[int]) -> int:
n = len(nums)
lcp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(n - 1, i - 1, -1):
if nums[i] == nums[j]:
lcp[i][j] = lcp[i + 1][j + 1] + 1
ans = 0
for i in range(1, n - 1):
for j in range(i + 1, n):
a = i <= j - i and lcp[0][i] >= i
b = j - i <= n - j and lcp[i][j] >= j - i
ans += int(a or b)
return ans
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function beautifulSplits(nums: number[]): number {
const n = nums.length;
const lcp: number[][] = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j > i; j--) {
if (nums[i] === nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
let ans = 0;
for (let i = 1; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
const a = i <= j - i && lcp[0][i] >= i;
const b = j - i <= n - j && lcp[i][j] >= j - i;
if (a || b) {
ans++;
}
}
}
return ans;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.