id
int64
1
3.71k
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,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
C++
class Solution { public: long long maximumTotalDamage(vector<int>& power) { sort(power.begin(), power.end()); this->power = power; n = power.size(); f.resize(n); nxt.resize(n); for (int i = 0; i < n; ++i) { cnt[power[i]]++; nxt[i] = upper_bound(power.begin() + i + 1, power.end(), power[i] + 2) - power.begin(); } return dfs(0); } private: unordered_map<int, int> cnt; vector<long long> f; vector<int> power; vector<int> nxt; int n; long long dfs(int i) { if (i >= n) { return 0; } if (f[i]) { return f[i]; } long long a = dfs(i + cnt[power[i]]); long long b = 1LL * power[i] * cnt[power[i]] + dfs(nxt[i]); return f[i] = max(a, b); } };
3,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
Go
func maximumTotalDamage(power []int) int64 { n := len(power) sort.Ints(power) cnt := map[int]int{} nxt := make([]int, n) f := make([]int64, n) for i, x := range power { cnt[x]++ nxt[i] = sort.SearchInts(power, x+3) } var dfs func(int) int64 dfs = func(i int) int64 { if i >= n { return 0 } if f[i] != 0 { return f[i] } a := dfs(i + cnt[power[i]]) b := int64(power[i]*cnt[power[i]]) + dfs(nxt[i]) f[i] = max(a, b) return f[i] } return dfs(0) }
3,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
Java
class Solution { private Long[] f; private int[] power; private Map<Integer, Integer> cnt; private int[] nxt; private int n; public long maximumTotalDamage(int[] power) { Arrays.sort(power); this.power = power; n = power.length; f = new Long[n]; cnt = new HashMap<>(n); nxt = new int[n]; for (int i = 0; i < n; ++i) { cnt.merge(power[i], 1, Integer::sum); int l = Arrays.binarySearch(power, power[i] + 3); l = l < 0 ? -l - 1 : l; nxt[i] = l; } return dfs(0); } private long dfs(int i) { if (i >= n) { return 0; } if (f[i] != null) { return f[i]; } long a = dfs(i + cnt.get(power[i])); long b = 1L * power[i] * cnt.get(power[i]) + dfs(nxt[i]); return f[i] = Math.max(a, b); } }
3,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
Python
class Solution: def maximumTotalDamage(self, power: List[int]) -> int: @cache def dfs(i: int) -> int: if i >= n: return 0 a = dfs(i + cnt[power[i]]) b = power[i] * cnt[power[i]] + dfs(nxt[i]) return max(a, b) n = len(power) cnt = Counter(power) power.sort() nxt = [bisect_right(power, x + 2, lo=i + 1) for i, x in enumerate(power)] return dfs(0)
3,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
Rust
use std::collections::HashMap; impl Solution { pub fn maximum_total_damage(mut power: Vec<i32>) -> i64 { power.sort(); let n = power.len(); let mut cnt = HashMap::new(); let mut nxt = vec![0; n]; let mut f = vec![-1_i64; n]; for i in 0..n { *cnt.entry(power[i]).or_insert(0) += 1; let j = match power[i + 1..].binary_search_by(|&x| x.cmp(&(power[i] + 2 + 1))) { Ok(pos) | Err(pos) => i + 1 + pos, }; nxt[i] = j; } fn dfs( i: usize, n: usize, power: &Vec<i32>, nxt: &Vec<usize>, f: &mut Vec<i64>, cnt: &HashMap<i32, i32>, ) -> i64 { if i >= n { return 0; } if f[i] != -1 { return f[i]; } let c = *cnt.get(&power[i]).unwrap(); let a = dfs(i + c as usize, n, power, nxt, f, cnt); let b = power[i] as i64 * c as i64 + dfs(nxt[i], n, power, nxt, f, cnt); f[i] = a.max(b); f[i] } dfs(0, n, &power, &nxt, &mut f, &cnt) } }
3,186
Maximum Total Damage With Spell Casting
Medium
<p>A magician has various spells.</p> <p>You are given an array <code>power</code>, where each element represents the damage of a spell. Multiple spells can have the same damage value.</p> <p>It is a known fact that if a magician decides to cast a spell with a damage of <code>power[i]</code>, they <strong>cannot</strong> cast any spell with a damage of <code>power[i] - 2</code>, <code>power[i] - 1</code>, <code>power[i] + 1</code>, or <code>power[i] + 2</code>.</p> <p>Each spell can be cast <strong>only once</strong>.</p> <p>Return the <strong>maximum</strong> possible <em>total damage</em> that a magician can cast.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [1,1,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">power = [7,1,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= power.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= power[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Dynamic Programming; Counting; Sorting
TypeScript
function maximumTotalDamage(power: number[]): number { const n = power.length; power.sort((a, b) => a - b); const f: number[] = Array(n).fill(0); const cnt: Record<number, number> = {}; const nxt: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { cnt[power[i]] = (cnt[power[i]] || 0) + 1; let [l, r] = [i + 1, n]; while (l < r) { const mid = (l + r) >> 1; if (power[mid] > power[i] + 2) { r = mid; } else { l = mid + 1; } } nxt[i] = l; } const dfs = (i: number): number => { if (i >= n) { return 0; } if (f[i]) { return f[i]; } const a = dfs(i + cnt[power[i]]); const b = power[i] * cnt[power[i]] + dfs(nxt[i]); return (f[i] = Math.max(a, b)); }; return dfs(0); }
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
C++
class BinaryIndexedTree { private: int n; vector<int> c; public: BinaryIndexedTree(int n) : n(n) , c(n + 1) {} void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } }; class Solution { public: vector<int> countOfPeaks(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); BinaryIndexedTree tree(n - 1); auto update = [&](int i, int val) { if (i <= 0 || i >= n - 1) { return; } if (nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) { tree.update(i, val); } }; for (int i = 1; i < n - 1; ++i) { update(i, 1); } vector<int> ans; for (auto& q : queries) { if (q[0] == 1) { int l = q[1] + 1, r = q[2] - 1; ans.push_back(l > r ? 0 : tree.query(r) - tree.query(l - 1)); } else { int idx = q[1], val = q[2]; for (int i = idx - 1; i <= idx + 1; ++i) { update(i, -1); } nums[idx] = val; for (int i = idx - 1; i <= idx + 1; ++i) { update(i, 1); } } } return ans; } };
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
Go
type BinaryIndexedTree struct { n int c []int } func NewBinaryIndexedTree(n int) *BinaryIndexedTree { return &BinaryIndexedTree{n: n, c: make([]int, n+1)} } func (bit *BinaryIndexedTree) update(x, delta int) { for ; x <= bit.n; x += x & -x { bit.c[x] += delta } } func (bit *BinaryIndexedTree) query(x int) int { s := 0 for ; x > 0; x -= x & -x { s += bit.c[x] } return s } func countOfPeaks(nums []int, queries [][]int) (ans []int) { n := len(nums) tree := NewBinaryIndexedTree(n - 1) update := func(i, val int) { if i <= 0 || i >= n-1 { return } if nums[i-1] < nums[i] && nums[i] > nums[i+1] { tree.update(i, val) } } for i := 1; i < n-1; i++ { update(i, 1) } for _, q := range queries { if q[0] == 1 { l, r := q[1]+1, q[2]-1 t := 0 if l <= r { t = tree.query(r) - tree.query(l-1) } ans = append(ans, t) } else { idx, val := q[1], q[2] for i := idx - 1; i <= idx+1; i++ { update(i, -1) } nums[idx] = val for i := idx - 1; i <= idx+1; i++ { update(i, 1) } } } return }
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
Java
class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } public int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } } class Solution { private BinaryIndexedTree tree; private int[] nums; public List<Integer> countOfPeaks(int[] nums, int[][] queries) { int n = nums.length; this.nums = nums; tree = new BinaryIndexedTree(n - 1); for (int i = 1; i < n - 1; ++i) { update(i, 1); } List<Integer> ans = new ArrayList<>(); for (var q : queries) { if (q[0] == 1) { int l = q[1] + 1, r = q[2] - 1; ans.add(l > r ? 0 : tree.query(r) - tree.query(l - 1)); } else { int idx = q[1], val = q[2]; for (int i = idx - 1; i <= idx + 1; ++i) { update(i, -1); } nums[idx] = val; for (int i = idx - 1; i <= idx + 1; ++i) { update(i, 1); } } } return ans; } private void update(int i, int val) { if (i <= 0 || i >= nums.length - 1) { return; } if (nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) { tree.update(i, val); } } }
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
JavaScript
class BinaryIndexedTree { constructor(n) { this.n = n; this.c = Array(n + 1).fill(0); } update(x, delta) { for (; x <= this.n; x += x & -x) { this.c[x] += delta; } } query(x) { let s = 0; for (; x > 0; x -= x & -x) { s += this.c[x]; } return s; } } /** * @param {number[]} nums * @param {number[][]} queries * @return {number[]} */ var countOfPeaks = function (nums, queries) { const n = nums.length; const tree = new BinaryIndexedTree(n - 1); const update = (i, val) => { if (i <= 0 || i >= n - 1) { return; } if (nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) { tree.update(i, val); } }; for (let i = 1; i < n - 1; ++i) { update(i, 1); } const ans = []; for (const q of queries) { if (q[0] === 1) { const l = q[1] + 1; const r = q[2] - 1; ans.push(l > r ? 0 : tree.query(r) - tree.query(l - 1)); } else { const idx = q[1]; const val = q[2]; for (let i = idx - 1; i <= idx + 1; ++i) { update(i, -1); } nums[idx] = val; for (let i = idx - 1; i <= idx + 1; ++i) { update(i, 1); } } } return ans; };
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
Python
class BinaryIndexedTree: __slots__ = "n", "c" def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, delta: int) -> None: while x <= self.n: self.c[x] += delta x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def countOfPeaks(self, nums: List[int], queries: List[List[int]]) -> List[int]: def update(i: int, val: int): if i <= 0 or i >= n - 1: return if nums[i - 1] < nums[i] and nums[i] > nums[i + 1]: tree.update(i, val) n = len(nums) tree = BinaryIndexedTree(n - 1) for i in range(1, n - 1): update(i, 1) ans = [] for q in queries: if q[0] == 1: l, r = q[1] + 1, q[2] - 1 ans.append(0 if l > r else tree.query(r) - tree.query(l - 1)) else: idx, val = q[1:] for i in range(idx - 1, idx + 2): update(i, -1) nums[idx] = val for i in range(idx - 1, idx + 2): update(i, 1) return ans
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
Rust
impl Solution { pub fn count_of_peaks(mut nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> { struct BinaryIndexedTree { n: usize, c: Vec<i32>, } impl BinaryIndexedTree { fn new(n: usize) -> Self { Self { n, c: vec![0; n + 1] } } fn update(&mut self, mut x: usize, delta: i32) { while x <= self.n { self.c[x] += delta; x += x & (!x + 1); } } fn query(&self, mut x: usize) -> i32 { let mut s = 0; while x > 0 { s += self.c[x]; x &= x - 1; } s } } let n = nums.len(); let mut tree = BinaryIndexedTree::new(n - 1); let mut update = |i: usize, val: i32, nums: &Vec<i32>, tree: &mut BinaryIndexedTree| { if i == 0 || i >= n - 1 { return; } if nums[i - 1] < nums[i] && nums[i] > nums[i + 1] { tree.update(i, val); } }; for i in 1..n - 1 { update(i, 1, &nums, &mut tree); } let mut ans = Vec::new(); for q in queries { if q[0] == 1 { let l = (q[1] + 1).max(1) as usize; let r = (q[2] - 1).max(0) as usize; if l > r { ans.push(0); } else { ans.push(tree.query(r) - tree.query(l - 1)); } } else { let idx = q[1] as usize; let val = q[2]; let left = if idx > 0 { idx - 1 } else { 0 }; let right = usize::min(idx + 1, n - 1); for i in left..=right { update(i, -1, &nums, &mut tree); } nums[idx] = val; for i in left..=right { update(i, 1, &nums, &mut tree); } } } ans } }
3,187
Peaks in Array
Hard
<p>A <strong>peak</strong> in an array <code>arr</code> is an element that is <strong>greater</strong> than its previous and next element in <code>arr</code>.</p> <p>You are given an integer array <code>nums</code> and a 2D integer array <code>queries</code>.</p> <p>You have to process queries of two types:</p> <ul> <li><code>queries[i] = [1, l<sub>i</sub>, r<sub>i</sub>]</code>, determine the count of <strong>peak</strong> elements in the <span data-keyword="subarray">subarray</span> <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.<!-- notionvc: 73b20b7c-e1ab-4dac-86d0-13761094a9ae --></li> <li><code>queries[i] = [2, index<sub>i</sub>, val<sub>i</sub>]</code>, change <code>nums[index<sub>i</sub>]</code> to <code><font face="monospace">val<sub>i</sub></font></code>.</li> </ul> <p>Return an array <code>answer</code> containing the results of the queries of the first type in order.<!-- notionvc: a9ccef22-4061-4b5a-b4cc-a2b2a0e12f30 --></p> <p><strong>Notes:</strong></p> <ul> <li>The <strong>first</strong> and the <strong>last</strong> element of an array or a subarray<!-- notionvc: fcffef72-deb5-47cb-8719-3a3790102f73 --> <strong>cannot</strong> be a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>First query: We change <code>nums[3]</code> to 4 and <code>nums</code> becomes <code>[3,1,4,4,5]</code>.</p> <p>Second query: The number of peaks in the <code>[3,1,4,4,5]</code> is 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>First query: <code>nums[2]</code> should become 4, but it is already set to 4.</p> <p>Second query: The number of peaks in the <code>[4,1,4]</code> is 0.</p> <p>Third query: The second 4 is a peak in the <code>[4,1,4,2,1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i][0] == 1</code> or <code>queries[i][0] == 2</code></li> <li>For all <code>i</code> that: <ul> <li><code>queries[i][0] == 1</code>: <code>0 &lt;= queries[i][1] &lt;= queries[i][2] &lt;= nums.length - 1</code></li> <li><code>queries[i][0] == 2</code>: <code>0 &lt;= queries[i][1] &lt;= nums.length - 1</code>, <code>1 &lt;= queries[i][2] &lt;= 10<sup>5</sup></code></li> </ul> </li> </ul>
Binary Indexed Tree; Segment Tree; Array
TypeScript
class BinaryIndexedTree { private n: number; private c: number[]; constructor(n: number) { this.n = n; this.c = Array(n + 1).fill(0); } update(x: number, delta: number): void { for (; x <= this.n; x += x & -x) { this.c[x] += delta; } } query(x: number): number { let s = 0; for (; x > 0; x -= x & -x) { s += this.c[x]; } return s; } } function countOfPeaks(nums: number[], queries: number[][]): number[] { const n = nums.length; const tree = new BinaryIndexedTree(n - 1); const update = (i: number, val: number): void => { if (i <= 0 || i >= n - 1) { return; } if (nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) { tree.update(i, val); } }; for (let i = 1; i < n - 1; ++i) { update(i, 1); } const ans: number[] = []; for (const q of queries) { if (q[0] === 1) { const [l, r] = [q[1] + 1, q[2] - 1]; ans.push(l > r ? 0 : tree.query(r) - tree.query(l - 1)); } else { const [idx, val] = [q[1], q[2]]; for (let i = idx - 1; i <= idx + 1; ++i) { update(i, -1); } nums[idx] = val; for (let i = idx - 1; i <= idx + 1; ++i) { update(i, 1); } } } return ans; }
3,188
Find Top Scoring Students II
Hard
<p>Table: <code>students</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | student_id | int | | name | varchar | | major | varchar | +-------------+----------+ student_id is the primary key for this table. Each row contains the student ID, student name, and their major. </pre> <p>Table: <code>courses</code></p> <pre> +-------------+-------------------+ | Column Name | Type | +-------------+-------------------+ | course_id | int | | name | varchar | | credits | int | | major | varchar | | mandatory | enum | +-------------+-------------------+ course_id is the primary key for this table. mandatory is an enum type of (&#39;Yes&#39;, &#39;No&#39;). Each row contains the course ID, course name, credits, major it belongs to, and whether the course is mandatory. </pre> <p>Table: <code>enrollments</code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | student_id | int | | course_id | int | | semester | varchar | | grade | varchar | | GPA | decimal | +-------------+----------+ (student_id, course_id, semester) is the primary key (combination of columns with unique values) for this table. Each row contains the student ID, course ID, semester, and grade received. </pre> <p>Write a solution to find the students who meet the following criteria:</p> <ul> <li>Have<strong> taken all mandatory courses</strong> and <strong>at least two</strong> elective courses offered in <strong>their major.</strong></li> <li>Achieved a grade of <strong>A</strong>&nbsp;in <strong>all mandatory courses</strong> and at least <strong>B</strong>&nbsp;in<strong> elective courses</strong>.</li> <li>Maintained an average <code>GPA</code> of at least&nbsp;<code>2.5</code> across all their courses (including those outside their major).</li> </ul> <p>Return <em>the result table ordered by</em> <code>student_id</code> <em>in <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>students table:</p> <pre class="example-io"> +------------+------------------+------------------+ | student_id | name | major | +------------+------------------+------------------+ | 1 | Alice | Computer Science | | 2 | Bob | Computer Science | | 3 | Charlie | Mathematics | | 4 | David | Mathematics | +------------+------------------+------------------+ </pre> <p>courses table:</p> <pre class="example-io"> +-----------+-------------------+---------+------------------+----------+ | course_id | name | credits | major | mandatory| +-----------+-------------------+---------+------------------+----------+ | 101 | Algorithms | 3 | Computer Science | yes | | 102 | Data Structures | 3 | Computer Science | yes | | 103 | Calculus | 4 | Mathematics | yes | | 104 | Linear Algebra | 4 | Mathematics | yes | | 105 | Machine Learning | 3 | Computer Science | no | | 106 | Probability | 3 | Mathematics | no | | 107 | Operating Systems | 3 | Computer Science | no | | 108 | Statistics | 3 | Mathematics | no | +-----------+-------------------+---------+------------------+----------+ </pre> <p>enrollments table:</p> <pre class="example-io"> +------------+-----------+-------------+-------+-----+ | student_id | course_id | semester | grade | GPA | +------------+-----------+-------------+-------+-----+ | 1 | 101 | Fall 2023 | A | 4.0 | | 1 | 102 | Spring 2023 | A | 4.0 | | 1 | 105 | Spring 2023 | A | 4.0 | | 1 | 107 | Fall 2023 | B | 3.5 | | 2 | 101 | Fall 2023 | A | 4.0 | | 2 | 102 | Spring 2023 | B | 3.0 | | 3 | 103 | Fall 2023 | A | 4.0 | | 3 | 104 | Spring 2023 | A | 4.0 | | 3 | 106 | Spring 2023 | A | 4.0 | | 3 | 108 | Fall 2023 | B | 3.5 | | 4 | 103 | Fall 2023 | B | 3.0 | | 4 | 104 | Spring 2023 | B | 3.0 | +------------+-----------+-------------+-------+-----+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+ | student_id | +------------+ | 1 | | 3 | +------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Alice (student_id 1) is a Computer Science major and has taken both Algorithms&nbsp;and Data Structures, receiving an A&nbsp;in both. She has also taken Machine Learning&nbsp;and Operating Systems&nbsp;as electives, receiving an A&nbsp;and B&nbsp;respectively.</li> <li>Bob (student_id 2) is a Computer Science major but did not receive an A&nbsp;in all required courses.</li> <li>Charlie (student_id 3) is a Mathematics major and has taken both Calculus&nbsp;and Linear Algebra, receiving an A&nbsp;in both. He has also taken Probability&nbsp;and Statistics&nbsp;as electives, receiving an A&nbsp;and B&nbsp;respectively.</li> <li>David (student_id 4) is a Mathematics major but did not receive an A&nbsp;in all required courses.</li> </ul> <p><strong>Note:</strong> Output table is ordered by student_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT student_id FROM enrollments GROUP BY 1 HAVING AVG(GPA) >= 2.5 ) SELECT student_id FROM T JOIN students USING (student_id) JOIN courses USING (major) LEFT JOIN enrollments USING (student_id, course_id) GROUP BY 1 HAVING SUM(mandatory = 'yes' AND grade = 'A') = SUM(mandatory = 'yes') AND SUM(mandatory = 'no' AND grade IS NOT NULL) = SUM(mandatory = 'no' AND grade IN ('A', 'B')) AND SUM(mandatory = 'no' AND grade IS NOT NULL) >= 2 ORDER BY 1;
3,189
Minimum Moves to Get a Peaceful Board
Medium
<p>Given a 2D array <code>rooks</code> of length <code>n</code>, where <code>rooks[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates the position of a rook on an <code>n x n</code> chess board. Your task is to move the rooks <strong>1 cell </strong>at a time vertically or horizontally (to an <em>adjacent</em> cell) such that the board becomes <strong>peaceful</strong>.</p> <p>A board is <strong>peaceful</strong> if there is <strong>exactly</strong> one rook in each row and each column.</p> <p>Return the <strong>minimum</strong> number of moves required to get a <em>peaceful board</em>.</p> <p><strong>Note</strong> that <strong>at no point</strong> can there be two rooks in the same cell.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[1,0],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex1-edited.gif" style="width: 150px; height: 150px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[0,1],[0,2],[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex2-edited.gif" style="width: 200px; height: 200px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == rooks.length &lt;= 500</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= n - 1</code></li> <li>The input is generated such that there are no 2 rooks in the same cell.</li> </ul>
Greedy; Array; Counting Sort; Sorting
C++
class Solution { public: int minMoves(vector<vector<int>>& rooks) { sort(rooks.begin(), rooks.end()); int ans = 0; int n = rooks.size(); for (int i = 0; i < n; ++i) { ans += abs(rooks[i][0] - i); } sort(rooks.begin(), rooks.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); for (int j = 0; j < n; ++j) { ans += abs(rooks[j][1] - j); } return ans; } };
3,189
Minimum Moves to Get a Peaceful Board
Medium
<p>Given a 2D array <code>rooks</code> of length <code>n</code>, where <code>rooks[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates the position of a rook on an <code>n x n</code> chess board. Your task is to move the rooks <strong>1 cell </strong>at a time vertically or horizontally (to an <em>adjacent</em> cell) such that the board becomes <strong>peaceful</strong>.</p> <p>A board is <strong>peaceful</strong> if there is <strong>exactly</strong> one rook in each row and each column.</p> <p>Return the <strong>minimum</strong> number of moves required to get a <em>peaceful board</em>.</p> <p><strong>Note</strong> that <strong>at no point</strong> can there be two rooks in the same cell.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[1,0],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex1-edited.gif" style="width: 150px; height: 150px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[0,1],[0,2],[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex2-edited.gif" style="width: 200px; height: 200px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == rooks.length &lt;= 500</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= n - 1</code></li> <li>The input is generated such that there are no 2 rooks in the same cell.</li> </ul>
Greedy; Array; Counting Sort; Sorting
Go
func minMoves(rooks [][]int) (ans int) { sort.Slice(rooks, func(i, j int) bool { return rooks[i][0] < rooks[j][0] }) for i, row := range rooks { ans += int(math.Abs(float64(row[0] - i))) } sort.Slice(rooks, func(i, j int) bool { return rooks[i][1] < rooks[j][1] }) for j, col := range rooks { ans += int(math.Abs(float64(col[1] - j))) } return }
3,189
Minimum Moves to Get a Peaceful Board
Medium
<p>Given a 2D array <code>rooks</code> of length <code>n</code>, where <code>rooks[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates the position of a rook on an <code>n x n</code> chess board. Your task is to move the rooks <strong>1 cell </strong>at a time vertically or horizontally (to an <em>adjacent</em> cell) such that the board becomes <strong>peaceful</strong>.</p> <p>A board is <strong>peaceful</strong> if there is <strong>exactly</strong> one rook in each row and each column.</p> <p>Return the <strong>minimum</strong> number of moves required to get a <em>peaceful board</em>.</p> <p><strong>Note</strong> that <strong>at no point</strong> can there be two rooks in the same cell.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[1,0],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex1-edited.gif" style="width: 150px; height: 150px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[0,1],[0,2],[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex2-edited.gif" style="width: 200px; height: 200px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == rooks.length &lt;= 500</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= n - 1</code></li> <li>The input is generated such that there are no 2 rooks in the same cell.</li> </ul>
Greedy; Array; Counting Sort; Sorting
Java
class Solution { public int minMoves(int[][] rooks) { Arrays.sort(rooks, (a, b) -> a[0] - b[0]); int ans = 0; int n = rooks.length; for (int i = 0; i < n; ++i) { ans += Math.abs(rooks[i][0] - i); } Arrays.sort(rooks, (a, b) -> a[1] - b[1]); for (int j = 0; j < n; ++j) { ans += Math.abs(rooks[j][1] - j); } return ans; } }
3,189
Minimum Moves to Get a Peaceful Board
Medium
<p>Given a 2D array <code>rooks</code> of length <code>n</code>, where <code>rooks[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates the position of a rook on an <code>n x n</code> chess board. Your task is to move the rooks <strong>1 cell </strong>at a time vertically or horizontally (to an <em>adjacent</em> cell) such that the board becomes <strong>peaceful</strong>.</p> <p>A board is <strong>peaceful</strong> if there is <strong>exactly</strong> one rook in each row and each column.</p> <p>Return the <strong>minimum</strong> number of moves required to get a <em>peaceful board</em>.</p> <p><strong>Note</strong> that <strong>at no point</strong> can there be two rooks in the same cell.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[1,0],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex1-edited.gif" style="width: 150px; height: 150px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[0,1],[0,2],[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex2-edited.gif" style="width: 200px; height: 200px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == rooks.length &lt;= 500</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= n - 1</code></li> <li>The input is generated such that there are no 2 rooks in the same cell.</li> </ul>
Greedy; Array; Counting Sort; Sorting
Python
class Solution: def minMoves(self, rooks: List[List[int]]) -> int: rooks.sort() ans = sum(abs(x - i) for i, (x, _) in enumerate(rooks)) rooks.sort(key=lambda x: x[1]) ans += sum(abs(y - j) for j, (_, y) in enumerate(rooks)) return ans
3,189
Minimum Moves to Get a Peaceful Board
Medium
<p>Given a 2D array <code>rooks</code> of length <code>n</code>, where <code>rooks[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates the position of a rook on an <code>n x n</code> chess board. Your task is to move the rooks <strong>1 cell </strong>at a time vertically or horizontally (to an <em>adjacent</em> cell) such that the board becomes <strong>peaceful</strong>.</p> <p>A board is <strong>peaceful</strong> if there is <strong>exactly</strong> one rook in each row and each column.</p> <p>Return the <strong>minimum</strong> number of moves required to get a <em>peaceful board</em>.</p> <p><strong>Note</strong> that <strong>at no point</strong> can there be two rooks in the same cell.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[1,0],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex1-edited.gif" style="width: 150px; height: 150px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">rooks = [[0,0],[0,1],[0,2],[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3189.Minimum%20Moves%20to%20Get%20a%20Peaceful%20Board/images/ex2-edited.gif" style="width: 200px; height: 200px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == rooks.length &lt;= 500</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= n - 1</code></li> <li>The input is generated such that there are no 2 rooks in the same cell.</li> </ul>
Greedy; Array; Counting Sort; Sorting
TypeScript
function minMoves(rooks: number[][]): number { rooks.sort((a, b) => a[0] - b[0]); let ans = rooks.reduce((sum, rook, i) => sum + Math.abs(rook[0] - i), 0); rooks.sort((a, b) => a[1] - b[1]); ans += rooks.reduce((sum, rook, j) => sum + Math.abs(rook[1] - j), 0); return ans; }
3,190
Find Minimum Operations to Make All Elements Divisible by Three
Easy
<p>You are given an integer array <code>nums</code>. In one operation, you can add or subtract 1 from <strong>any</strong> element of <code>nums</code>.</p> <p>Return the <strong>minimum</strong> number of operations to make all elements of <code>nums</code> divisible by 3.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">3</span></p> <p><strong>Explanation:</strong></p> <p>All array elements can be made divisible by 3 using 3 operations:</p> <ul> <li>Subtract 1 from 1.</li> <li>Add 1 to 2.</li> <li>Subtract 1 from 4.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,6,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Math
C++
class Solution { public: int minimumOperations(vector<int>& nums) { int ans = 0; for (int x : nums) { int mod = x % 3; if (mod) { ans += min(mod, 3 - mod); } } return ans; } };
3,190
Find Minimum Operations to Make All Elements Divisible by Three
Easy
<p>You are given an integer array <code>nums</code>. In one operation, you can add or subtract 1 from <strong>any</strong> element of <code>nums</code>.</p> <p>Return the <strong>minimum</strong> number of operations to make all elements of <code>nums</code> divisible by 3.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">3</span></p> <p><strong>Explanation:</strong></p> <p>All array elements can be made divisible by 3 using 3 operations:</p> <ul> <li>Subtract 1 from 1.</li> <li>Add 1 to 2.</li> <li>Subtract 1 from 4.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,6,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Math
Go
func minimumOperations(nums []int) (ans int) { for _, x := range nums { if mod := x % 3; mod > 0 { ans += min(mod, 3-mod) } } return }
3,190
Find Minimum Operations to Make All Elements Divisible by Three
Easy
<p>You are given an integer array <code>nums</code>. In one operation, you can add or subtract 1 from <strong>any</strong> element of <code>nums</code>.</p> <p>Return the <strong>minimum</strong> number of operations to make all elements of <code>nums</code> divisible by 3.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">3</span></p> <p><strong>Explanation:</strong></p> <p>All array elements can be made divisible by 3 using 3 operations:</p> <ul> <li>Subtract 1 from 1.</li> <li>Add 1 to 2.</li> <li>Subtract 1 from 4.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,6,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Math
Java
class Solution { public int minimumOperations(int[] nums) { int ans = 0; for (int x : nums) { int mod = x % 3; if (mod != 0) { ans += Math.min(mod, 3 - mod); } } return ans; } }
3,190
Find Minimum Operations to Make All Elements Divisible by Three
Easy
<p>You are given an integer array <code>nums</code>. In one operation, you can add or subtract 1 from <strong>any</strong> element of <code>nums</code>.</p> <p>Return the <strong>minimum</strong> number of operations to make all elements of <code>nums</code> divisible by 3.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">3</span></p> <p><strong>Explanation:</strong></p> <p>All array elements can be made divisible by 3 using 3 operations:</p> <ul> <li>Subtract 1 from 1.</li> <li>Add 1 to 2.</li> <li>Subtract 1 from 4.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,6,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Math
Python
class Solution: def minimumOperations(self, nums: List[int]) -> int: ans = 0 for x in nums: if mod := x % 3: ans += min(mod, 3 - mod) return ans
3,190
Find Minimum Operations to Make All Elements Divisible by Three
Easy
<p>You are given an integer array <code>nums</code>. In one operation, you can add or subtract 1 from <strong>any</strong> element of <code>nums</code>.</p> <p>Return the <strong>minimum</strong> number of operations to make all elements of <code>nums</code> divisible by 3.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">3</span></p> <p><strong>Explanation:</strong></p> <p>All array elements can be made divisible by 3 using 3 operations:</p> <ul> <li>Subtract 1 from 1.</li> <li>Add 1 to 2.</li> <li>Subtract 1 from 4.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,6,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Math
TypeScript
function minimumOperations(nums: number[]): number { let ans = 0; for (const x of nums) { const mod = x % 3; if (mod) { ans += Math.min(mod, 3 - mod); } } return ans; }
3,191
Minimum Operations to Make Binary Array Elements Equal to One I
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> 3 <strong>consecutive</strong> elements from the array and <strong>flip</strong> <strong>all</strong> of them.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1. If it is impossible, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the elements at indices 0, 1 and 2. The resulting array is <code>nums = [<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,1,0,0]</code>.</li> <li>Choose the elements at indices 1, 2 and 3. The resulting array is <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<strong><u>0</u></strong>,0,0]</code>.</li> <li>Choose the elements at indices 3, 4 and 5. The resulting array is <code>nums = [1,1,1,<strong><u>1</u></strong>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> It is impossible to make all elements equal to 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Bit Manipulation; Queue; Array; Prefix Sum; Sliding Window
C++
class Solution { public: int minOperations(vector<int>& nums) { int ans = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { if (nums[i] == 0) { if (i + 2 >= n) { return -1; } nums[i + 1] ^= 1; nums[i + 2] ^= 1; ++ans; } } return ans; } };
3,191
Minimum Operations to Make Binary Array Elements Equal to One I
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> 3 <strong>consecutive</strong> elements from the array and <strong>flip</strong> <strong>all</strong> of them.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1. If it is impossible, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the elements at indices 0, 1 and 2. The resulting array is <code>nums = [<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,1,0,0]</code>.</li> <li>Choose the elements at indices 1, 2 and 3. The resulting array is <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<strong><u>0</u></strong>,0,0]</code>.</li> <li>Choose the elements at indices 3, 4 and 5. The resulting array is <code>nums = [1,1,1,<strong><u>1</u></strong>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> It is impossible to make all elements equal to 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Bit Manipulation; Queue; Array; Prefix Sum; Sliding Window
Go
func minOperations(nums []int) (ans int) { for i, x := range nums { if x == 0 { if i+2 >= len(nums) { return -1 } nums[i+1] ^= 1 nums[i+2] ^= 1 ans++ } } return }
3,191
Minimum Operations to Make Binary Array Elements Equal to One I
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> 3 <strong>consecutive</strong> elements from the array and <strong>flip</strong> <strong>all</strong> of them.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1. If it is impossible, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the elements at indices 0, 1 and 2. The resulting array is <code>nums = [<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,1,0,0]</code>.</li> <li>Choose the elements at indices 1, 2 and 3. The resulting array is <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<strong><u>0</u></strong>,0,0]</code>.</li> <li>Choose the elements at indices 3, 4 and 5. The resulting array is <code>nums = [1,1,1,<strong><u>1</u></strong>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> It is impossible to make all elements equal to 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Bit Manipulation; Queue; Array; Prefix Sum; Sliding Window
Java
class Solution { public int minOperations(int[] nums) { int ans = 0; int n = nums.length; for (int i = 0; i < n; ++i) { if (nums[i] == 0) { if (i + 2 >= n) { return -1; } nums[i + 1] ^= 1; nums[i + 2] ^= 1; ++ans; } } return ans; } }
3,191
Minimum Operations to Make Binary Array Elements Equal to One I
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> 3 <strong>consecutive</strong> elements from the array and <strong>flip</strong> <strong>all</strong> of them.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1. If it is impossible, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the elements at indices 0, 1 and 2. The resulting array is <code>nums = [<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,1,0,0]</code>.</li> <li>Choose the elements at indices 1, 2 and 3. The resulting array is <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<strong><u>0</u></strong>,0,0]</code>.</li> <li>Choose the elements at indices 3, 4 and 5. The resulting array is <code>nums = [1,1,1,<strong><u>1</u></strong>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> It is impossible to make all elements equal to 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Bit Manipulation; Queue; Array; Prefix Sum; Sliding Window
Python
class Solution: def minOperations(self, nums: List[int]) -> int: ans = 0 for i, x in enumerate(nums): if x == 0: if i + 2 >= len(nums): return -1 nums[i + 1] ^= 1 nums[i + 2] ^= 1 ans += 1 return ans
3,191
Minimum Operations to Make Binary Array Elements Equal to One I
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> 3 <strong>consecutive</strong> elements from the array and <strong>flip</strong> <strong>all</strong> of them.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1. If it is impossible, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the elements at indices 0, 1 and 2. The resulting array is <code>nums = [<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>0</strong></u>,1,0,0]</code>.</li> <li>Choose the elements at indices 1, 2 and 3. The resulting array is <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<strong><u>0</u></strong>,0,0]</code>.</li> <li>Choose the elements at indices 3, 4 and 5. The resulting array is <code>nums = [1,1,1,<strong><u>1</u></strong>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> It is impossible to make all elements equal to 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Bit Manipulation; Queue; Array; Prefix Sum; Sliding Window
TypeScript
function minOperations(nums: number[]): number { const n = nums.length; let ans = 0; for (let i = 0; i < n; ++i) { if (nums[i] === 0) { if (i + 2 >= n) { return -1; } nums[i + 1] ^= 1; nums[i + 2] ^= 1; ++ans; } } return ans; }
3,192
Minimum Operations to Make Binary Array Elements Equal to One II
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> index <code>i</code> from the array and <strong>flip</strong> <strong>all</strong> the elements from index <code>i</code> to the end of the array.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [0,<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 0</code><span class="example-io">. The resulting array will be <code>nums = [<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 4</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,0,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 3</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></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,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong><br /> We can do the following operation:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Greedy; Array; Dynamic Programming
C++
class Solution { public: int minOperations(vector<int>& nums) { int ans = 0, v = 0; for (int x : nums) { x ^= v; if (x == 0) { v ^= 1; ++ans; } } return ans; } };
3,192
Minimum Operations to Make Binary Array Elements Equal to One II
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> index <code>i</code> from the array and <strong>flip</strong> <strong>all</strong> the elements from index <code>i</code> to the end of the array.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [0,<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 0</code><span class="example-io">. The resulting array will be <code>nums = [<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 4</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,0,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 3</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></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,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong><br /> We can do the following operation:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Greedy; Array; Dynamic Programming
Go
func minOperations(nums []int) (ans int) { v := 0 for _, x := range nums { x ^= v if x == 0 { v ^= 1 ans++ } } return }
3,192
Minimum Operations to Make Binary Array Elements Equal to One II
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> index <code>i</code> from the array and <strong>flip</strong> <strong>all</strong> the elements from index <code>i</code> to the end of the array.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [0,<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 0</code><span class="example-io">. The resulting array will be <code>nums = [<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 4</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,0,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 3</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></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,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong><br /> We can do the following operation:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Greedy; Array; Dynamic Programming
Java
class Solution { public int minOperations(int[] nums) { int ans = 0, v = 0; for (int x : nums) { x ^= v; if (x == 0) { v ^= 1; ++ans; } } return ans; } }
3,192
Minimum Operations to Make Binary Array Elements Equal to One II
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> index <code>i</code> from the array and <strong>flip</strong> <strong>all</strong> the elements from index <code>i</code> to the end of the array.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [0,<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 0</code><span class="example-io">. The resulting array will be <code>nums = [<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 4</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,0,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 3</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></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,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong><br /> We can do the following operation:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Greedy; Array; Dynamic Programming
Python
class Solution: def minOperations(self, nums: List[int]) -> int: ans = v = 0 for x in nums: x ^= v if x == 0: ans += 1 v ^= 1 return ans
3,192
Minimum Operations to Make Binary Array Elements Equal to One II
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times (possibly zero):</p> <ul> <li>Choose <strong>any</strong> index <code>i</code> from the array and <strong>flip</strong> <strong>all</strong> the elements from index <code>i</code> to the end of the array.</li> </ul> <p><strong>Flipping</strong> an element means changing its value from 0 to 1, and from 1 to 0.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>nums</code> equal to 1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> We can do the following operations:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [0,<u><strong>0</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 0</code><span class="example-io">. The resulting array will be <code>nums = [<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>0</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 4</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,0,<u><strong>0</strong></u>]</code>.</span></li> <li>Choose the index <code>i = 3</code><span class="example-io">. The resulting array will be <code>nums = [1,1,1,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></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,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong><br /> We can do the following operation:</p> <ul> <li>Choose the index <code>i = 1</code><span class="example-io">. The resulting array will be <code>nums = [1,<u><strong>1</strong></u>,<u><strong>1</strong></u>,<u><strong>1</strong></u>]</code>.</span></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> </ul>
Greedy; Array; Dynamic Programming
TypeScript
function minOperations(nums: number[]): number { let [ans, v] = [0, 0]; for (let x of nums) { x ^= v; if (x === 0) { v ^= 1; ++ans; } } return ans; }
3,193
Count the Number of Inversions
Hard
<p>You are given an integer <code>n</code> and a 2D array <code>requirements</code>, where <code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code> represents the end index and the <strong>inversion</strong> count of each requirement.</p> <p>A pair of indices <code>(i, j)</code> from an integer array <code>nums</code> is called an <strong>inversion</strong> if:</p> <ul> <li><code>i &lt; j</code> and <code>nums[i] &gt; nums[j]</code></li> </ul> <p>Return the number of <span data-keyword="permutation">permutations</span> <code>perm</code> of <code>[0, 1, 2, ..., n - 1]</code> such that for <strong>all</strong> <code>requirements[i]</code>, <code>perm[0..end<sub>i</sub>]</code> has exactly <code>cnt<sub>i</sub></code> inversions.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, requirements = [[2,2],[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The two permutations are:</p> <ul> <li><code>[2, 0, 1]</code> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </li> <li><code>[1, 2, 0]</code> <ul> <li>Prefix <code>[1, 2, 0]</code> has inversions <code>(0, 2)</code> and <code>(1, 2)</code>.</li> <li>Prefix <code>[1]</code> has 0 inversions.</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">n = 3, requirements = [[2,2],[1,1],[0,0]]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[2, 0, 1]</code>:</p> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2, 0]</code> has an inversion <code>(0, 1)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, requirements = [[0,0],[1,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[0, 1]</code>:</p> <ul> <li>Prefix <code>[0]</code> has 0 inversions.</li> <li>Prefix <code>[0, 1]</code> has an inversion <code>(0, 1)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= requirements.length &lt;= n</code></li> <li><code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code></li> <li><code>0 &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>0 &lt;= cnt<sub>i</sub> &lt;= 400</code></li> <li>The input is generated such that there is at least one <code>i</code> such that <code>end<sub>i</sub> == n - 1</code>.</li> <li>The input is generated such that all <code>end<sub>i</sub></code> are unique.</li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int numberOfPermutations(int n, vector<vector<int>>& requirements) { vector<int> req(n, -1); int m = 0; for (const auto& r : requirements) { req[r[0]] = r[1]; m = max(m, r[1]); } if (req[0] > 0) { return 0; } req[0] = 0; const int mod = 1e9 + 7; vector<vector<int>> f(n, vector<int>(m + 1, 0)); f[0][0] = 1; for (int i = 1; i < n; ++i) { int l = 0, r = m; if (req[i] >= 0) { l = r = req[i]; } for (int j = l; j <= r; ++j) { for (int k = 0; k <= min(i, j); ++k) { f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod; } } } return f[n - 1][req[n - 1]]; } };
3,193
Count the Number of Inversions
Hard
<p>You are given an integer <code>n</code> and a 2D array <code>requirements</code>, where <code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code> represents the end index and the <strong>inversion</strong> count of each requirement.</p> <p>A pair of indices <code>(i, j)</code> from an integer array <code>nums</code> is called an <strong>inversion</strong> if:</p> <ul> <li><code>i &lt; j</code> and <code>nums[i] &gt; nums[j]</code></li> </ul> <p>Return the number of <span data-keyword="permutation">permutations</span> <code>perm</code> of <code>[0, 1, 2, ..., n - 1]</code> such that for <strong>all</strong> <code>requirements[i]</code>, <code>perm[0..end<sub>i</sub>]</code> has exactly <code>cnt<sub>i</sub></code> inversions.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, requirements = [[2,2],[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The two permutations are:</p> <ul> <li><code>[2, 0, 1]</code> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </li> <li><code>[1, 2, 0]</code> <ul> <li>Prefix <code>[1, 2, 0]</code> has inversions <code>(0, 2)</code> and <code>(1, 2)</code>.</li> <li>Prefix <code>[1]</code> has 0 inversions.</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">n = 3, requirements = [[2,2],[1,1],[0,0]]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[2, 0, 1]</code>:</p> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2, 0]</code> has an inversion <code>(0, 1)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, requirements = [[0,0],[1,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[0, 1]</code>:</p> <ul> <li>Prefix <code>[0]</code> has 0 inversions.</li> <li>Prefix <code>[0, 1]</code> has an inversion <code>(0, 1)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= requirements.length &lt;= n</code></li> <li><code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code></li> <li><code>0 &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>0 &lt;= cnt<sub>i</sub> &lt;= 400</code></li> <li>The input is generated such that there is at least one <code>i</code> such that <code>end<sub>i</sub> == n - 1</code>.</li> <li>The input is generated such that all <code>end<sub>i</sub></code> are unique.</li> </ul>
Array; Dynamic Programming
Go
func numberOfPermutations(n int, requirements [][]int) int { req := make([]int, n) for i := range req { req[i] = -1 } for _, r := range requirements { req[r[0]] = r[1] } if req[0] > 0 { return 0 } req[0] = 0 m := slices.Max(req) const mod = int(1e9 + 7) f := make([][]int, n) for i := range f { f[i] = make([]int, m+1) } f[0][0] = 1 for i := 1; i < n; i++ { l, r := 0, m if req[i] >= 0 { l, r = req[i], req[i] } for j := l; j <= r; j++ { for k := 0; k <= min(i, j); k++ { f[i][j] = (f[i][j] + f[i-1][j-k]) % mod } } } return f[n-1][req[n-1]] }
3,193
Count the Number of Inversions
Hard
<p>You are given an integer <code>n</code> and a 2D array <code>requirements</code>, where <code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code> represents the end index and the <strong>inversion</strong> count of each requirement.</p> <p>A pair of indices <code>(i, j)</code> from an integer array <code>nums</code> is called an <strong>inversion</strong> if:</p> <ul> <li><code>i &lt; j</code> and <code>nums[i] &gt; nums[j]</code></li> </ul> <p>Return the number of <span data-keyword="permutation">permutations</span> <code>perm</code> of <code>[0, 1, 2, ..., n - 1]</code> such that for <strong>all</strong> <code>requirements[i]</code>, <code>perm[0..end<sub>i</sub>]</code> has exactly <code>cnt<sub>i</sub></code> inversions.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, requirements = [[2,2],[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The two permutations are:</p> <ul> <li><code>[2, 0, 1]</code> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </li> <li><code>[1, 2, 0]</code> <ul> <li>Prefix <code>[1, 2, 0]</code> has inversions <code>(0, 2)</code> and <code>(1, 2)</code>.</li> <li>Prefix <code>[1]</code> has 0 inversions.</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">n = 3, requirements = [[2,2],[1,1],[0,0]]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[2, 0, 1]</code>:</p> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2, 0]</code> has an inversion <code>(0, 1)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, requirements = [[0,0],[1,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[0, 1]</code>:</p> <ul> <li>Prefix <code>[0]</code> has 0 inversions.</li> <li>Prefix <code>[0, 1]</code> has an inversion <code>(0, 1)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= requirements.length &lt;= n</code></li> <li><code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code></li> <li><code>0 &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>0 &lt;= cnt<sub>i</sub> &lt;= 400</code></li> <li>The input is generated such that there is at least one <code>i</code> such that <code>end<sub>i</sub> == n - 1</code>.</li> <li>The input is generated such that all <code>end<sub>i</sub></code> are unique.</li> </ul>
Array; Dynamic Programming
Java
class Solution { public int numberOfPermutations(int n, int[][] requirements) { int[] req = new int[n]; Arrays.fill(req, -1); int m = 0; for (var r : requirements) { req[r[0]] = r[1]; m = Math.max(m, r[1]); } if (req[0] > 0) { return 0; } req[0] = 0; final int mod = (int) 1e9 + 7; int[][] f = new int[n][m + 1]; f[0][0] = 1; for (int i = 1; i < n; ++i) { int l = 0, r = m; if (req[i] >= 0) { l = r = req[i]; } for (int j = l; j <= r; ++j) { for (int k = 0; k <= Math.min(i, j); ++k) { f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod; } } } return f[n - 1][req[n - 1]]; } }
3,193
Count the Number of Inversions
Hard
<p>You are given an integer <code>n</code> and a 2D array <code>requirements</code>, where <code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code> represents the end index and the <strong>inversion</strong> count of each requirement.</p> <p>A pair of indices <code>(i, j)</code> from an integer array <code>nums</code> is called an <strong>inversion</strong> if:</p> <ul> <li><code>i &lt; j</code> and <code>nums[i] &gt; nums[j]</code></li> </ul> <p>Return the number of <span data-keyword="permutation">permutations</span> <code>perm</code> of <code>[0, 1, 2, ..., n - 1]</code> such that for <strong>all</strong> <code>requirements[i]</code>, <code>perm[0..end<sub>i</sub>]</code> has exactly <code>cnt<sub>i</sub></code> inversions.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, requirements = [[2,2],[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The two permutations are:</p> <ul> <li><code>[2, 0, 1]</code> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </li> <li><code>[1, 2, 0]</code> <ul> <li>Prefix <code>[1, 2, 0]</code> has inversions <code>(0, 2)</code> and <code>(1, 2)</code>.</li> <li>Prefix <code>[1]</code> has 0 inversions.</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">n = 3, requirements = [[2,2],[1,1],[0,0]]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[2, 0, 1]</code>:</p> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2, 0]</code> has an inversion <code>(0, 1)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, requirements = [[0,0],[1,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[0, 1]</code>:</p> <ul> <li>Prefix <code>[0]</code> has 0 inversions.</li> <li>Prefix <code>[0, 1]</code> has an inversion <code>(0, 1)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= requirements.length &lt;= n</code></li> <li><code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code></li> <li><code>0 &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>0 &lt;= cnt<sub>i</sub> &lt;= 400</code></li> <li>The input is generated such that there is at least one <code>i</code> such that <code>end<sub>i</sub> == n - 1</code>.</li> <li>The input is generated such that all <code>end<sub>i</sub></code> are unique.</li> </ul>
Array; Dynamic Programming
Python
class Solution: def numberOfPermutations(self, n: int, requirements: List[List[int]]) -> int: req = [-1] * n for end, cnt in requirements: req[end] = cnt if req[0] > 0: return 0 req[0] = 0 mod = 10**9 + 7 m = max(req) f = [[0] * (m + 1) for _ in range(n)] f[0][0] = 1 for i in range(1, n): l, r = 0, m if req[i] >= 0: l = r = req[i] for j in range(l, r + 1): for k in range(min(i, j) + 1): f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod return f[n - 1][req[n - 1]]
3,193
Count the Number of Inversions
Hard
<p>You are given an integer <code>n</code> and a 2D array <code>requirements</code>, where <code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code> represents the end index and the <strong>inversion</strong> count of each requirement.</p> <p>A pair of indices <code>(i, j)</code> from an integer array <code>nums</code> is called an <strong>inversion</strong> if:</p> <ul> <li><code>i &lt; j</code> and <code>nums[i] &gt; nums[j]</code></li> </ul> <p>Return the number of <span data-keyword="permutation">permutations</span> <code>perm</code> of <code>[0, 1, 2, ..., n - 1]</code> such that for <strong>all</strong> <code>requirements[i]</code>, <code>perm[0..end<sub>i</sub>]</code> has exactly <code>cnt<sub>i</sub></code> inversions.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, requirements = [[2,2],[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The two permutations are:</p> <ul> <li><code>[2, 0, 1]</code> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </li> <li><code>[1, 2, 0]</code> <ul> <li>Prefix <code>[1, 2, 0]</code> has inversions <code>(0, 2)</code> and <code>(1, 2)</code>.</li> <li>Prefix <code>[1]</code> has 0 inversions.</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">n = 3, requirements = [[2,2],[1,1],[0,0]]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[2, 0, 1]</code>:</p> <ul> <li>Prefix <code>[2, 0, 1]</code> has inversions <code>(0, 1)</code> and <code>(0, 2)</code>.</li> <li>Prefix <code>[2, 0]</code> has an inversion <code>(0, 1)</code>.</li> <li>Prefix <code>[2]</code> has 0 inversions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, requirements = [[0,0],[1,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only satisfying permutation is <code>[0, 1]</code>:</p> <ul> <li>Prefix <code>[0]</code> has 0 inversions.</li> <li>Prefix <code>[0, 1]</code> has an inversion <code>(0, 1)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= requirements.length &lt;= n</code></li> <li><code>requirements[i] = [end<sub>i</sub>, cnt<sub>i</sub>]</code></li> <li><code>0 &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>0 &lt;= cnt<sub>i</sub> &lt;= 400</code></li> <li>The input is generated such that there is at least one <code>i</code> such that <code>end<sub>i</sub> == n - 1</code>.</li> <li>The input is generated such that all <code>end<sub>i</sub></code> are unique.</li> </ul>
Array; Dynamic Programming
TypeScript
function numberOfPermutations(n: number, requirements: number[][]): number { const req: number[] = Array(n).fill(-1); for (const [end, cnt] of requirements) { req[end] = cnt; } if (req[0] > 0) { return 0; } req[0] = 0; const m = Math.max(...req); const mod = 1e9 + 7; const f = Array.from({ length: n }, () => Array(m + 1).fill(0)); f[0][0] = 1; for (let i = 1; i < n; ++i) { let [l, r] = [0, m]; if (req[i] >= 0) { l = r = req[i]; } for (let j = l; j <= r; ++j) { for (let k = 0; k <= Math.min(i, j); ++k) { f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod; } } } return f[n - 1][req[n - 1]]; }
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
C++
class Solution { public: double minimumAverage(vector<int>& nums) { sort(nums.begin(), nums.end()); int ans = 1 << 30, n = nums.size(); for (int i = 0; i < n; ++i) { ans = min(ans, nums[i] + nums[n - i - 1]); } return ans / 2.0; } };
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
Go
func minimumAverage(nums []int) float64 { sort.Ints(nums) n := len(nums) ans := 1 << 30 for i, x := range nums[:n/2] { ans = min(ans, x+nums[n-i-1]) } return float64(ans) / 2 }
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
Java
class Solution { public double minimumAverage(int[] nums) { Arrays.sort(nums); int n = nums.length; int ans = 1 << 30; for (int i = 0; i < n / 2; ++i) { ans = Math.min(ans, nums[i] + nums[n - i - 1]); } return ans / 2.0; } }
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
Python
class Solution: def minimumAverage(self, nums: List[int]) -> float: nums.sort() n = len(nums) return min(nums[i] + nums[-i - 1] for i in range(n // 2)) / 2
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
Rust
impl Solution { pub fn minimum_average(mut nums: Vec<i32>) -> f64 { nums.sort(); let n = nums.len(); let ans = (0..n / 2).map(|i| nums[i] + nums[n - i - 1]).min().unwrap(); ans as f64 / 2.0 } }
3,194
Minimum Average of Smallest and Largest Elements
Easy
<p>You have an array of floating point numbers <code>averages</code> which is initially empty. You are given an array <code>nums</code> of <code>n</code> integers where <code>n</code> is even.</p> <p>You repeat the following procedure <code>n / 2</code> times:</p> <ul> <li>Remove the <strong>smallest</strong> element, <code>minElement</code>, and the <strong>largest</strong> element <code>maxElement</code>,&nbsp;from <code>nums</code>.</li> <li>Add <code>(minElement + maxElement) / 2</code> to <code>averages</code>.</li> </ul> <p>Return the <strong>minimum</strong> element in <code>averages</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,8,3,4,15,13,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td>[7,8,3,4,15,13,4,1]</td> <td>[]</td> </tr> <tr> <td>1</td> <td>[7,8,3,4,13,4]</td> <td>[8]</td> </tr> <tr> <td>2</td> <td>[7,8,4,4]</td> <td>[8,8]</td> </tr> <tr> <td>3</td> <td>[7,4]</td> <td>[8,8,6]</td> </tr> <tr> <td>4</td> <td>[]</td> <td>[8,8,6,5.5]</td> </tr> </tbody> </table> The smallest element of averages, 5.5, is returned.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,9,8,3,10,5]</span></p> <p><strong>Output:</strong> <span class="example-io">5.5</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,9,8,3,10,5]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[9,8,3,5]</span></td> <td>[5.5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[8,5]</span></td> <td>[5.5,6]</td> </tr> <tr> <td>3</td> <td>[]</td> <td>[5.5,6,6.5]</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">5.0</span></p> <p><strong>Explanation:</strong></p> <table> <tbody> <tr> <th>step</th> <th>nums</th> <th>averages</th> </tr> <tr> <td>0</td> <td><span class="example-io">[1,2,3,7,8,9]</span></td> <td>[]</td> </tr> <tr> <td>1</td> <td><span class="example-io">[2,3,7,8]</span></td> <td>[5]</td> </tr> <tr> <td>2</td> <td><span class="example-io">[3,7]</span></td> <td>[5,5]</td> </tr> <tr> <td>3</td> <td><span class="example-io">[]</span></td> <td>[5,5,5]</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>n</code> is even.</li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Sorting
TypeScript
function minimumAverage(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; let ans = Infinity; for (let i = 0; i * 2 < n; ++i) { ans = Math.min(ans, nums[i] + nums[n - 1 - i]); } return ans / 2; }
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
C++
class Solution { public: int minimumArea(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int x1 = m, y1 = n; int x2 = 0, y2 = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 1) { x1 = min(x1, i); y1 = min(y1, j); x2 = max(x2, i); y2 = max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); } };
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
C#
public class Solution { public int MinimumArea(int[][] grid) { int m = grid.Length, n = grid[0].Length; int x1 = m, y1 = n; int x2 = 0, y2 = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 1) { x1 = Math.Min(x1, i); y1 = Math.Min(y1, j); x2 = Math.Max(x2, i); y2 = Math.Max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); } }
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
Go
func minimumArea(grid [][]int) int { x1, y1 := len(grid), len(grid[0]) x2, y2 := 0, 0 for i, row := range grid { for j, x := range row { if x == 1 { x1, y1 = min(x1, i), min(y1, j) x2, y2 = max(x2, i), max(y2, j) } } } return (x2 - x1 + 1) * (y2 - y1 + 1) }
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
Java
class Solution { public int minimumArea(int[][] grid) { int m = grid.length, n = grid[0].length; int x1 = m, y1 = n; int x2 = 0, y2 = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); } }
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
JavaScript
/** * @param {number[][]} grid * @return {number} */ var minimumArea = function (grid) { const [m, n] = [grid.length, grid[0].length]; let [x1, y1] = [m, n]; let [x2, y2] = [0, 0]; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (grid[i][j] === 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); };
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
Python
class Solution: def minimumArea(self, grid: List[List[int]]) -> int: x1 = y1 = inf x2 = y2 = -inf for i, row in enumerate(grid): for j, x in enumerate(row): if x == 1: x1 = min(x1, i) y1 = min(y1, j) x2 = max(x2, i) y2 = max(y2, j) return (x2 - x1 + 1) * (y2 - y1 + 1)
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
Rust
impl Solution { pub fn minimum_area(grid: Vec<Vec<i32>>) -> i32 { let m = grid.len(); let n = grid[0].len(); let mut x1 = m as i32; let mut y1 = n as i32; let mut x2 = 0i32; let mut y2 = 0i32; for i in 0..m { for j in 0..n { if grid[i][j] == 1 { x1 = x1.min(i as i32); y1 = y1.min(j as i32); x2 = x2.max(i as i32); y2 = y2.max(j as i32); } } } (x2 - x1 + 1) * (y2 - y1 + 1) } }
3,195
Find the Minimum Area to Cover All Ones I
Medium
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. Find a rectangle with horizontal and vertical sides with the<strong> smallest</strong> area, such that all the 1&#39;s in <code>grid</code> lie inside this rectangle.</p> <p>Return the <strong>minimum</strong> possible area of the rectangle.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,0],[1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect0.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 279px; height: 198px;" /></p> <p>The smallest rectangle has a height of 2 and a width of 3, so it has an area of <code>2 * 3 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0],[0,0]]</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/3100-3199/3195.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20I/images/examplerect1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 204px; height: 201px;" /></p> <p>The smallest rectangle has both height and width 1, so its area is <code>1 * 1 = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 1000</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there is at least one 1 in <code>grid</code>.</li> </ul>
Array; Matrix
TypeScript
function minimumArea(grid: number[][]): number { const [m, n] = [grid.length, grid[0].length]; let [x1, y1] = [m, n]; let [x2, y2] = [0, 0]; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (grid[i][j] === 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); }
3,196
Maximize Total Cost of Alternating Subarrays
Medium
<p>You are given an integer array <code>nums</code> with length <code>n</code>.</p> <p>The <strong>cost</strong> of a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[l..r]</code>, where <code>0 &lt;= l &lt;= r &lt; n</code>, is defined as:</p> <p><code>cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (&minus;1)<sup>r &minus; l</sup></code></p> <p>Your task is to <strong>split</strong> <code>nums</code> into subarrays such that the <strong>total</strong> <strong>cost</strong> of the subarrays is <strong>maximized</strong>, ensuring each element belongs to <strong>exactly one</strong> subarray.</p> <p>Formally, if <code>nums</code> is split into <code>k</code> subarrays, where <code>k &gt; 1</code>, at indices <code>i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>k &minus; 1</sub></code>, where <code>0 &lt;= i<sub>1</sub> &lt; i<sub>2</sub> &lt; ... &lt; i<sub>k - 1</sub> &lt; n - 1</code>, then the total cost will be:</p> <p><code>cost(0, i<sub>1</sub>) + cost(i<sub>1</sub> + 1, i<sub>2</sub>) + ... + cost(i<sub>k &minus; 1</sub> + 1, n &minus; 1)</code></p> <p>Return an integer denoting the <em>maximum total cost</em> of the subarrays after splitting the array optimally.</p> <p><strong>Note:</strong> If <code>nums</code> is not split into subarrays, i.e. <code>k = 1</code>, the total cost is simply <code>cost(0, n - 1)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">10</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -2, 3, 4]</code> into subarrays <code>[1, -2, 3]</code> and <code>[4]</code>. The total cost will be <code>(1 + 2 + 3) + 4 = 10</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -1, 1, -1]</code> into subarrays <code>[1, -1]</code> and <code>[1, -1]</code>. The total cost will be <code>(1 + 1) + (1 + 1) = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0]</span></p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>We cannot split the array further, so the answer is 0.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Selecting the whole array gives a total cost of <code>1 + 1 = 2</code>, which is the maximum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: long long maximumTotalCost(vector<int>& nums) { int n = nums.size(); long long f[n][2]; fill(f[0], f[n], LLONG_MIN); auto dfs = [&](this auto&& dfs, int i, int j) -> long long { if (i >= n) { return 0; } if (f[i][j] != LLONG_MIN) { return f[i][j]; } f[i][j] = nums[i] + dfs(i + 1, 1); if (j) { f[i][j] = max(f[i][j], -nums[i] + dfs(i + 1, 0)); } return f[i][j]; }; return dfs(0, 0); } };
3,196
Maximize Total Cost of Alternating Subarrays
Medium
<p>You are given an integer array <code>nums</code> with length <code>n</code>.</p> <p>The <strong>cost</strong> of a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[l..r]</code>, where <code>0 &lt;= l &lt;= r &lt; n</code>, is defined as:</p> <p><code>cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (&minus;1)<sup>r &minus; l</sup></code></p> <p>Your task is to <strong>split</strong> <code>nums</code> into subarrays such that the <strong>total</strong> <strong>cost</strong> of the subarrays is <strong>maximized</strong>, ensuring each element belongs to <strong>exactly one</strong> subarray.</p> <p>Formally, if <code>nums</code> is split into <code>k</code> subarrays, where <code>k &gt; 1</code>, at indices <code>i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>k &minus; 1</sub></code>, where <code>0 &lt;= i<sub>1</sub> &lt; i<sub>2</sub> &lt; ... &lt; i<sub>k - 1</sub> &lt; n - 1</code>, then the total cost will be:</p> <p><code>cost(0, i<sub>1</sub>) + cost(i<sub>1</sub> + 1, i<sub>2</sub>) + ... + cost(i<sub>k &minus; 1</sub> + 1, n &minus; 1)</code></p> <p>Return an integer denoting the <em>maximum total cost</em> of the subarrays after splitting the array optimally.</p> <p><strong>Note:</strong> If <code>nums</code> is not split into subarrays, i.e. <code>k = 1</code>, the total cost is simply <code>cost(0, n - 1)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">10</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -2, 3, 4]</code> into subarrays <code>[1, -2, 3]</code> and <code>[4]</code>. The total cost will be <code>(1 + 2 + 3) + 4 = 10</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -1, 1, -1]</code> into subarrays <code>[1, -1]</code> and <code>[1, -1]</code>. The total cost will be <code>(1 + 1) + (1 + 1) = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0]</span></p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>We cannot split the array further, so the answer is 0.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Selecting the whole array gives a total cost of <code>1 + 1 = 2</code>, which is the maximum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumTotalCost(nums []int) int64 { n := len(nums) f := make([][2]int64, n) for i := range f { f[i] = [2]int64{-1e18, -1e18} } var dfs func(int, int) int64 dfs = func(i, j int) int64 { if i >= n { return 0 } if f[i][j] != -1e18 { return f[i][j] } f[i][j] = int64(nums[i]) + dfs(i+1, 1) if j > 0 { f[i][j] = max(f[i][j], int64(-nums[i])+dfs(i+1, 0)) } return f[i][j] } return dfs(0, 0) }
3,196
Maximize Total Cost of Alternating Subarrays
Medium
<p>You are given an integer array <code>nums</code> with length <code>n</code>.</p> <p>The <strong>cost</strong> of a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[l..r]</code>, where <code>0 &lt;= l &lt;= r &lt; n</code>, is defined as:</p> <p><code>cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (&minus;1)<sup>r &minus; l</sup></code></p> <p>Your task is to <strong>split</strong> <code>nums</code> into subarrays such that the <strong>total</strong> <strong>cost</strong> of the subarrays is <strong>maximized</strong>, ensuring each element belongs to <strong>exactly one</strong> subarray.</p> <p>Formally, if <code>nums</code> is split into <code>k</code> subarrays, where <code>k &gt; 1</code>, at indices <code>i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>k &minus; 1</sub></code>, where <code>0 &lt;= i<sub>1</sub> &lt; i<sub>2</sub> &lt; ... &lt; i<sub>k - 1</sub> &lt; n - 1</code>, then the total cost will be:</p> <p><code>cost(0, i<sub>1</sub>) + cost(i<sub>1</sub> + 1, i<sub>2</sub>) + ... + cost(i<sub>k &minus; 1</sub> + 1, n &minus; 1)</code></p> <p>Return an integer denoting the <em>maximum total cost</em> of the subarrays after splitting the array optimally.</p> <p><strong>Note:</strong> If <code>nums</code> is not split into subarrays, i.e. <code>k = 1</code>, the total cost is simply <code>cost(0, n - 1)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">10</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -2, 3, 4]</code> into subarrays <code>[1, -2, 3]</code> and <code>[4]</code>. The total cost will be <code>(1 + 2 + 3) + 4 = 10</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -1, 1, -1]</code> into subarrays <code>[1, -1]</code> and <code>[1, -1]</code>. The total cost will be <code>(1 + 1) + (1 + 1) = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0]</span></p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>We cannot split the array further, so the answer is 0.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Selecting the whole array gives a total cost of <code>1 + 1 = 2</code>, which is the maximum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private Long[][] f; private int[] nums; private int n; public long maximumTotalCost(int[] nums) { n = nums.length; this.nums = nums; f = new Long[n][2]; return dfs(0, 0); } private long dfs(int i, int j) { if (i >= n) { return 0; } if (f[i][j] != null) { return f[i][j]; } f[i][j] = nums[i] + dfs(i + 1, 1); if (j == 1) { f[i][j] = Math.max(f[i][j], -nums[i] + dfs(i + 1, 0)); } return f[i][j]; } }
3,196
Maximize Total Cost of Alternating Subarrays
Medium
<p>You are given an integer array <code>nums</code> with length <code>n</code>.</p> <p>The <strong>cost</strong> of a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[l..r]</code>, where <code>0 &lt;= l &lt;= r &lt; n</code>, is defined as:</p> <p><code>cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (&minus;1)<sup>r &minus; l</sup></code></p> <p>Your task is to <strong>split</strong> <code>nums</code> into subarrays such that the <strong>total</strong> <strong>cost</strong> of the subarrays is <strong>maximized</strong>, ensuring each element belongs to <strong>exactly one</strong> subarray.</p> <p>Formally, if <code>nums</code> is split into <code>k</code> subarrays, where <code>k &gt; 1</code>, at indices <code>i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>k &minus; 1</sub></code>, where <code>0 &lt;= i<sub>1</sub> &lt; i<sub>2</sub> &lt; ... &lt; i<sub>k - 1</sub> &lt; n - 1</code>, then the total cost will be:</p> <p><code>cost(0, i<sub>1</sub>) + cost(i<sub>1</sub> + 1, i<sub>2</sub>) + ... + cost(i<sub>k &minus; 1</sub> + 1, n &minus; 1)</code></p> <p>Return an integer denoting the <em>maximum total cost</em> of the subarrays after splitting the array optimally.</p> <p><strong>Note:</strong> If <code>nums</code> is not split into subarrays, i.e. <code>k = 1</code>, the total cost is simply <code>cost(0, n - 1)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">10</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -2, 3, 4]</code> into subarrays <code>[1, -2, 3]</code> and <code>[4]</code>. The total cost will be <code>(1 + 2 + 3) + 4 = 10</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -1, 1, -1]</code> into subarrays <code>[1, -1]</code> and <code>[1, -1]</code>. The total cost will be <code>(1 + 1) + (1 + 1) = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0]</span></p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>We cannot split the array further, so the answer is 0.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Selecting the whole array gives a total cost of <code>1 + 1 = 2</code>, which is the maximum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumTotalCost(self, nums: List[int]) -> int: @cache def dfs(i: int, j: int) -> int: if i >= len(nums): return 0 ans = nums[i] + dfs(i + 1, 1) if j == 1: ans = max(ans, -nums[i] + dfs(i + 1, 0)) return ans return dfs(0, 0)
3,196
Maximize Total Cost of Alternating Subarrays
Medium
<p>You are given an integer array <code>nums</code> with length <code>n</code>.</p> <p>The <strong>cost</strong> of a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[l..r]</code>, where <code>0 &lt;= l &lt;= r &lt; n</code>, is defined as:</p> <p><code>cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (&minus;1)<sup>r &minus; l</sup></code></p> <p>Your task is to <strong>split</strong> <code>nums</code> into subarrays such that the <strong>total</strong> <strong>cost</strong> of the subarrays is <strong>maximized</strong>, ensuring each element belongs to <strong>exactly one</strong> subarray.</p> <p>Formally, if <code>nums</code> is split into <code>k</code> subarrays, where <code>k &gt; 1</code>, at indices <code>i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>k &minus; 1</sub></code>, where <code>0 &lt;= i<sub>1</sub> &lt; i<sub>2</sub> &lt; ... &lt; i<sub>k - 1</sub> &lt; n - 1</code>, then the total cost will be:</p> <p><code>cost(0, i<sub>1</sub>) + cost(i<sub>1</sub> + 1, i<sub>2</sub>) + ... + cost(i<sub>k &minus; 1</sub> + 1, n &minus; 1)</code></p> <p>Return an integer denoting the <em>maximum total cost</em> of the subarrays after splitting the array optimally.</p> <p><strong>Note:</strong> If <code>nums</code> is not split into subarrays, i.e. <code>k = 1</code>, the total cost is simply <code>cost(0, n - 1)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">10</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -2, 3, 4]</code> into subarrays <code>[1, -2, 3]</code> and <code>[4]</code>. The total cost will be <code>(1 + 2 + 3) + 4 = 10</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>One way to maximize the total cost is by splitting <code>[1, -1, 1, -1]</code> into subarrays <code>[1, -1]</code> and <code>[1, -1]</code>. The total cost will be <code>(1 + 1) + (1 + 1) = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0]</span></p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>We cannot split the array further, so the answer is 0.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Selecting the whole array gives a total cost of <code>1 + 1 = 2</code>, which is the maximum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumTotalCost(nums: number[]): number { const n = nums.length; const f: number[][] = Array.from({ length: n }, () => Array(2).fill(-Infinity)); const dfs = (i: number, j: number): number => { if (i >= n) { return 0; } if (f[i][j] !== -Infinity) { return f[i][j]; } f[i][j] = nums[i] + dfs(i + 1, 1); if (j) { f[i][j] = Math.max(f[i][j], -nums[i] + dfs(i + 1, 0)); } return f[i][j]; }; return dfs(0, 0); }
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
C++
class Solution { public: int minimumSum(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); int ans = m * n; int inf = INT_MAX / 4; auto f = [&](int i1, int j1, int i2, int j2) { int x1 = inf, y1 = inf; int x2 = -inf, y2 = -inf; for (int i = i1; i <= i2; i++) { for (int j = j1; j <= j2; j++) { if (grid[i][j] == 1) { x1 = min(x1, i); y1 = min(y1, j); x2 = max(x2, i); y2 = max(y2, j); } } } return x1 > x2 || y1 > y2 ? inf : (x2 - x1 + 1) * (y2 - y1 + 1); }; for (int i1 = 0; i1 < m - 1; i1++) { for (int i2 = i1 + 1; i2 < m - 1; i2++) { ans = min(ans, f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1)); } } for (int j1 = 0; j1 < n - 1; j1++) { for (int j2 = j1 + 1; j2 < n - 1; j2++) { ans = min(ans, f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1)); } } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n - 1; j++) { ans = min(ans, f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1)); ans = min(ans, f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1)); ans = min(ans, f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1)); ans = min(ans, f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1)); } } return ans; } };
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
C#
public class Solution { private const int INF = 1 << 30; private int[][] grid; public int MinimumSum(int[][] grid) { this.grid = grid; int m = grid.Length; int n = grid[0].Length; int ans = m * n; for (int i1 = 0; i1 < m - 1; i1++) { for (int i2 = i1 + 1; i2 < m - 1; i2++) { ans = Math.Min( ans, F(0, 0, i1, n - 1) + F(i1 + 1, 0, i2, n - 1) + F(i2 + 1, 0, m - 1, n - 1)); } } for (int j1 = 0; j1 < n - 1; j1++) { for (int j2 = j1 + 1; j2 < n - 1; j2++) { ans = Math.Min( ans, F(0, 0, m - 1, j1) + F(0, j1 + 1, m - 1, j2) + F(0, j2 + 1, m - 1, n - 1)); } } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n - 1; j++) { ans = Math.Min( ans, F(0, 0, i, j) + F(0, j + 1, i, n - 1) + F(i + 1, 0, m - 1, n - 1)); ans = Math.Min( ans, F(0, 0, i, n - 1) + F(i + 1, 0, m - 1, j) + F(i + 1, j + 1, m - 1, n - 1)); ans = Math.Min( ans, F(0, 0, i, j) + F(i + 1, 0, m - 1, j) + F(0, j + 1, m - 1, n - 1)); ans = Math.Min( ans, F(0, 0, m - 1, j) + F(0, j + 1, i, n - 1) + F(i + 1, j + 1, m - 1, n - 1)); } } return ans; } private int F(int i1, int j1, int i2, int j2) { int x1 = INF, y1 = INF; int x2 = -INF, y2 = -INF; for (int i = i1; i <= i2; i++) { for (int j = j1; j <= j2; j++) { if (grid[i][j] == 1) { x1 = Math.Min(x1, i); y1 = Math.Min(y1, j); x2 = Math.Max(x2, i); y2 = Math.Max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); } }
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
Go
func minimumSum(grid [][]int) int { m := len(grid) n := len(grid[0]) ans := m * n inf := math.MaxInt32 f := func(i1, j1, i2, j2 int) int { x1, y1 := inf, inf x2, y2 := -inf, -inf for i := i1; i <= i2; i++ { for j := j1; j <= j2; j++ { if grid[i][j] == 1 { x1 = min(x1, i) y1 = min(y1, j) x2 = max(x2, i) y2 = max(y2, j) } } } if x1 == inf { return 0 } return (x2 - x1 + 1) * (y2 - y1 + 1) } for i1 := 0; i1 < m-1; i1++ { for i2 := i1 + 1; i2 < m-1; i2++ { ans = min(ans, f(0, 0, i1, n-1)+f(i1+1, 0, i2, n-1)+f(i2+1, 0, m-1, n-1)) } } for j1 := 0; j1 < n-1; j1++ { for j2 := j1 + 1; j2 < n-1; j2++ { ans = min(ans, f(0, 0, m-1, j1)+f(0, j1+1, m-1, j2)+f(0, j2+1, m-1, n-1)) } } for i := 0; i < m-1; i++ { for j := 0; j < n-1; j++ { ans = min(ans, f(0, 0, i, j)+f(0, j+1, i, n-1)+f(i+1, 0, m-1, n-1)) ans = min(ans, f(0, 0, i, n-1)+f(i+1, 0, m-1, j)+f(i+1, j+1, m-1, n-1)) ans = min(ans, f(0, 0, i, j)+f(i+1, 0, m-1, j)+f(0, j+1, m-1, n-1)) ans = min(ans, f(0, 0, m-1, j)+f(0, j+1, i, n-1)+f(i+1, j+1, m-1, n-1)) } } return ans }
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
Java
class Solution { private final int inf = 1 << 30; private int[][] grid; public int minimumSum(int[][] grid) { this.grid = grid; int m = grid.length; int n = grid[0].length; int ans = m * n; for (int i1 = 0; i1 < m - 1; i1++) { for (int i2 = i1 + 1; i2 < m - 1; i2++) { ans = Math.min( ans, f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1)); } } for (int j1 = 0; j1 < n - 1; j1++) { for (int j2 = j1 + 1; j2 < n - 1; j2++) { ans = Math.min( ans, f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1)); } } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n - 1; j++) { ans = Math.min( ans, f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1)); } } return ans; } private int f(int i1, int j1, int i2, int j2) { int x1 = inf, y1 = inf; int x2 = -inf, y2 = -inf; for (int i = i1; i <= i2; i++) { for (int j = j1; j <= j2; j++) { if (grid[i][j] == 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return (x2 - x1 + 1) * (y2 - y1 + 1); } }
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
JavaScript
/** * @param {number[][]} grid * @return {number} */ var minimumSum = function (grid) { const m = grid.length; const n = grid[0].length; let ans = m * n; const inf = Number.MAX_SAFE_INTEGER; const f = (i1, j1, i2, j2) => { let [x1, y1] = [inf, inf]; let [x2, y2] = [-inf, -inf]; for (let i = i1; i <= i2; i++) { for (let j = j1; j <= j2; j++) { if (grid[i][j] === 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return x1 === inf ? 0 : (x2 - x1 + 1) * (y2 - y1 + 1); }; for (let i1 = 0; i1 < m - 1; i1++) { for (let i2 = i1 + 1; i2 < m - 1; i2++) { ans = Math.min( ans, f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1), ); } } for (let j1 = 0; j1 < n - 1; j1++) { for (let j2 = j1 + 1; j2 < n - 1; j2++) { ans = Math.min( ans, f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1), ); } } for (let i = 0; i < m - 1; i++) { for (let j = 0; j < n - 1; j++) { ans = Math.min(ans, f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1), ); ans = Math.min(ans, f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1), ); } } return ans; };
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
Python
class Solution: def minimumSum(self, grid: List[List[int]]) -> int: def f(i1: int, j1: int, i2: int, j2: int) -> int: x1 = y1 = inf x2 = y2 = -inf for i in range(i1, i2 + 1): for j in range(j1, j2 + 1): if grid[i][j] == 1: x1 = min(x1, i) y1 = min(y1, j) x2 = max(x2, i) y2 = max(y2, j) return (x2 - x1 + 1) * (y2 - y1 + 1) m, n = len(grid), len(grid[0]) ans = m * n for i1 in range(m - 1): for i2 in range(i1 + 1, m - 1): ans = min( ans, f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1), ) for j1 in range(n - 1): for j2 in range(j1 + 1, n - 1): ans = min( ans, f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1), ) for i in range(m - 1): for j in range(n - 1): ans = min( ans, f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1), ) ans = min( ans, f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1), ) ans = min( ans, f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1), ) ans = min( ans, f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1), ) return ans
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
Rust
impl Solution { pub fn minimum_sum(grid: Vec<Vec<i32>>) -> i32 { let m = grid.len(); let n = grid[0].len(); let mut ans = (m * n) as i32; let inf = i32::MAX / 4; let f = |i1: usize, j1: usize, i2: usize, j2: usize| -> i32 { let mut x1 = inf; let mut y1 = inf; let mut x2 = -inf; let mut y2 = -inf; for i in i1..=i2 { for j in j1..=j2 { if grid[i][j] == 1 { x1 = x1.min(i as i32); y1 = y1.min(j as i32); x2 = x2.max(i as i32); y2 = y2.max(j as i32); } } } if x1 > x2 || y1 > y2 { inf } else { (x2 - x1 + 1) * (y2 - y1 + 1) } }; for i1 in 0..m - 1 { for i2 in i1 + 1..m - 1 { ans = ans .min(f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1)); } } for j1 in 0..n - 1 { for j2 in j1 + 1..n - 1 { ans = ans .min(f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1)); } } for i in 0..m - 1 { for j in 0..n - 1 { ans = ans.min(f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1)); ans = ans .min(f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1)); ans = ans.min(f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1)); ans = ans .min(f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1)); } } ans } }
3,197
Find the Minimum Area to Cover All Ones II
Hard
<p>You are given a 2D <strong>binary</strong> array <code>grid</code>. You need to find 3 <strong>non-overlapping</strong> rectangles having <strong>non-zero</strong> areas with horizontal and vertical sides such that all the 1&#39;s in <code>grid</code> lie inside these rectangles.</p> <p>Return the <strong>minimum</strong> possible sum of the area of these rectangles.</p> <p><strong>Note</strong> that the rectangles are allowed to touch.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1],[1,1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example0rect21.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 280px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(1, 0)</code> are covered by a rectangle of area 2.</li> <li>The 1&#39;s at <code>(0, 2)</code> and <code>(1, 2)</code> are covered by a rectangle of area 2.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,1,0],[0,1,0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3197.Find%20the%20Minimum%20Area%20to%20Cover%20All%20Ones%20II/images/example1rect2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 356px; height: 198px;" /></p> <ul> <li>The 1&#39;s at <code>(0, 0)</code> and <code>(0, 2)</code> are covered by a rectangle of area 3.</li> <li>The 1 at <code>(1, 1)</code> is covered by a rectangle of area 1.</li> <li>The 1 at <code>(1, 3)</code> is covered by a rectangle of area 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= grid.length, grid[i].length &lt;= 30</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> <li>The input is generated such that there are at least three 1&#39;s in <code>grid</code>.</li> </ul>
Array; Enumeration; Matrix
TypeScript
function minimumSum(grid: number[][]): number { const m = grid.length; const n = grid[0].length; let ans = m * n; const inf = Number.MAX_SAFE_INTEGER; const f = (i1: number, j1: number, i2: number, j2: number): number => { let [x1, y1] = [inf, inf]; let [x2, y2] = [-inf, -inf]; for (let i = i1; i <= i2; i++) { for (let j = j1; j <= j2; j++) { if (grid[i][j] === 1) { x1 = Math.min(x1, i); y1 = Math.min(y1, j); x2 = Math.max(x2, i); y2 = Math.max(y2, j); } } } return x1 === inf ? 0 : (x2 - x1 + 1) * (y2 - y1 + 1); }; for (let i1 = 0; i1 < m - 1; i1++) { for (let i2 = i1 + 1; i2 < m - 1; i2++) { ans = Math.min( ans, f(0, 0, i1, n - 1) + f(i1 + 1, 0, i2, n - 1) + f(i2 + 1, 0, m - 1, n - 1), ); } } for (let j1 = 0; j1 < n - 1; j1++) { for (let j2 = j1 + 1; j2 < n - 1; j2++) { ans = Math.min( ans, f(0, 0, m - 1, j1) + f(0, j1 + 1, m - 1, j2) + f(0, j2 + 1, m - 1, n - 1), ); } } for (let i = 0; i < m - 1; i++) { for (let j = 0; j < n - 1; j++) { ans = Math.min(ans, f(0, 0, i, j) + f(0, j + 1, i, n - 1) + f(i + 1, 0, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, i, n - 1) + f(i + 1, 0, m - 1, j) + f(i + 1, j + 1, m - 1, n - 1), ); ans = Math.min(ans, f(0, 0, i, j) + f(i + 1, 0, m - 1, j) + f(0, j + 1, m - 1, n - 1)); ans = Math.min( ans, f(0, 0, m - 1, j) + f(0, j + 1, i, n - 1) + f(i + 1, j + 1, m - 1, n - 1), ); } } return ans; }
3,198
Find Cities in Each State
Easy
<p>Table: <code>cities</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | state | varchar | | city | varchar | +-------------+---------+ (state, city) is the primary key (combination of columns with unique values) for this table. Each row of this table contains the state name and the city name within that state. </pre> <p>Write a solution to find <strong>all the cities in each state</strong> and combine them into a <strong>single comma-separated</strong> string.</p> <p>Return <em>the result table ordered by</em> <code>state</code>&nbsp;<em>and</em> <code>city</code>&nbsp;<em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>cities table:</p> <pre class="example-io"> +-------------+---------------+ | state | city | +-------------+---------------+ | California | Los Angeles | | California | San Francisco | | California | San Diego | | Texas | Houston | | Texas | Austin | | Texas | Dallas | | New York | New York City | | New York | Buffalo | | New York | Rochester | +-------------+---------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------------------------------+ | state | cities | +-------------+---------------------------------------+ | California | Los Angeles, San Diego, San Francisco | | New York | Buffalo, New York City, Rochester | | Texas | Austin, Dallas, Houston | +-------------+---------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>California:</strong> All cities (&quot;Los Angeles&quot;, &quot;San Diego&quot;, &quot;San Francisco&quot;) are listed in a comma-separated string.</li> <li><strong>New York:</strong> All cities (&quot;Buffalo&quot;, &quot;New York City&quot;, &quot;Rochester&quot;) are listed in a comma-separated string.</li> <li><strong>Texas:</strong> All cities (&quot;Austin&quot;, &quot;Dallas&quot;, &quot;Houston&quot;) are listed in a comma-separated string.</li> </ul> <p><strong>Note:</strong> The output table is ordered by the state name in ascending order.</p> </div>
Database
Python
import pandas as pd def find_cities(cities: pd.DataFrame) -> pd.DataFrame: result = ( cities.groupby("state")["city"] .apply(lambda x: ", ".join(sorted(x))) .reset_index() ) result.columns = ["state", "cities"] return result
3,198
Find Cities in Each State
Easy
<p>Table: <code>cities</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | state | varchar | | city | varchar | +-------------+---------+ (state, city) is the primary key (combination of columns with unique values) for this table. Each row of this table contains the state name and the city name within that state. </pre> <p>Write a solution to find <strong>all the cities in each state</strong> and combine them into a <strong>single comma-separated</strong> string.</p> <p>Return <em>the result table ordered by</em> <code>state</code>&nbsp;<em>and</em> <code>city</code>&nbsp;<em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>cities table:</p> <pre class="example-io"> +-------------+---------------+ | state | city | +-------------+---------------+ | California | Los Angeles | | California | San Francisco | | California | San Diego | | Texas | Houston | | Texas | Austin | | Texas | Dallas | | New York | New York City | | New York | Buffalo | | New York | Rochester | +-------------+---------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------------------------------+ | state | cities | +-------------+---------------------------------------+ | California | Los Angeles, San Diego, San Francisco | | New York | Buffalo, New York City, Rochester | | Texas | Austin, Dallas, Houston | +-------------+---------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>California:</strong> All cities (&quot;Los Angeles&quot;, &quot;San Diego&quot;, &quot;San Francisco&quot;) are listed in a comma-separated string.</li> <li><strong>New York:</strong> All cities (&quot;Buffalo&quot;, &quot;New York City&quot;, &quot;Rochester&quot;) are listed in a comma-separated string.</li> <li><strong>Texas:</strong> All cities (&quot;Austin&quot;, &quot;Dallas&quot;, &quot;Houston&quot;) are listed in a comma-separated string.</li> </ul> <p><strong>Note:</strong> The output table is ordered by the state name in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT state, GROUP_CONCAT(city ORDER BY city SEPARATOR ', ') cities FROM cities GROUP BY 1 ORDER BY 1;
3,199
Count Triplets with Even XOR Set Bits I
Easy
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> of the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 100</code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: int tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) { int cnt1[2]{}; int cnt2[2]{}; int cnt3[2]{}; for (int x : a) { ++cnt1[__builtin_popcount(x) & 1]; } for (int x : b) { ++cnt2[__builtin_popcount(x) & 1]; } for (int x : c) { ++cnt3[__builtin_popcount(x) & 1]; } int ans = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { if ((i + j + k) % 2 == 0) { ans += cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } };
3,199
Count Triplets with Even XOR Set Bits I
Easy
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> of the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 100</code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Go
func tripletCount(a []int, b []int, c []int) (ans int) { cnt1 := [2]int{} cnt2 := [2]int{} cnt3 := [2]int{} for _, x := range a { cnt1[bits.OnesCount(uint(x))%2]++ } for _, x := range b { cnt2[bits.OnesCount(uint(x))%2]++ } for _, x := range c { cnt3[bits.OnesCount(uint(x))%2]++ } for i := 0; i < 2; i++ { for j := 0; j < 2; j++ { for k := 0; k < 2; k++ { if (i+j+k)%2 == 0 { ans += cnt1[i] * cnt2[j] * cnt3[k] } } } } return }
3,199
Count Triplets with Even XOR Set Bits I
Easy
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> of the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 100</code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Java
class Solution { public int tripletCount(int[] a, int[] b, int[] c) { int[] cnt1 = new int[2]; int[] cnt2 = new int[2]; int[] cnt3 = new int[2]; for (int x : a) { ++cnt1[Integer.bitCount(x) & 1]; } for (int x : b) { ++cnt2[Integer.bitCount(x) & 1]; } for (int x : c) { ++cnt3[Integer.bitCount(x) & 1]; } int ans = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { if ((i + j + k) % 2 == 0) { ans += cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } }
3,199
Count Triplets with Even XOR Set Bits I
Easy
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> of the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 100</code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Python
class Solution: def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int: cnt1 = Counter(x.bit_count() & 1 for x in a) cnt2 = Counter(x.bit_count() & 1 for x in b) cnt3 = Counter(x.bit_count() & 1 for x in c) ans = 0 for i in range(2): for j in range(2): for k in range(2): if (i + j + k) & 1 ^ 1: ans += cnt1[i] * cnt2[j] * cnt3[k] return ans
3,199
Count Triplets with Even XOR Set Bits I
Easy
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> of the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Consider these four triplets:</p> <ul> <li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li> <li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> <li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length, c.length &lt;= 100</code></li> <li><code>0 &lt;= a[i], b[i], c[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
TypeScript
function tripletCount(a: number[], b: number[], c: number[]): number { const cnt1: [number, number] = [0, 0]; const cnt2: [number, number] = [0, 0]; const cnt3: [number, number] = [0, 0]; for (const x of a) { ++cnt1[bitCount(x) & 1]; } for (const x of b) { ++cnt2[bitCount(x) & 1]; } for (const x of c) { ++cnt3[bitCount(x) & 1]; } let ans = 0; for (let i = 0; i < 2; ++i) { for (let j = 0; j < 2; ++j) { for (let k = 0; k < 2; ++k) { if ((i + j + k) % 2 === 0) { ans += cnt1[i] * cnt2[j] * cnt3[k]; } } } } return ans; } 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,200
Maximum Height of a Triangle
Easy
<p>You are given two integers <code>red</code> and <code>blue</code> representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1<sup>st</sup> row will have 1 ball, the 2<sup>nd</sup> row will have 2 balls, the 3<sup>rd</sup> row will have 3 balls, and so on.</p> <p>All the balls in a particular row should be the <strong>same</strong> color, and adjacent rows should have <strong>different</strong> colors.</p> <p>Return the <strong>maximum</strong><em> height of the triangle</em> that can be achieved.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 4</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/brb.png" style="width: 300px; height: 240px; padding: 10px;" /></p> <p>The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 1, blue = 1</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 10, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= red, blue &lt;= 100</code></li> </ul>
Array; Enumeration
C++
class Solution { public: int maxHeightOfTriangle(int red, int blue) { int ans = 0; for (int k = 0; k < 2; ++k) { int c[2] = {red, blue}; for (int i = 1, j = k; i <= c[j]; j ^= 1, ++i) { c[j] -= i; ans = max(ans, i); } } return ans; } };
3,200
Maximum Height of a Triangle
Easy
<p>You are given two integers <code>red</code> and <code>blue</code> representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1<sup>st</sup> row will have 1 ball, the 2<sup>nd</sup> row will have 2 balls, the 3<sup>rd</sup> row will have 3 balls, and so on.</p> <p>All the balls in a particular row should be the <strong>same</strong> color, and adjacent rows should have <strong>different</strong> colors.</p> <p>Return the <strong>maximum</strong><em> height of the triangle</em> that can be achieved.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 4</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/brb.png" style="width: 300px; height: 240px; padding: 10px;" /></p> <p>The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 1, blue = 1</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 10, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= red, blue &lt;= 100</code></li> </ul>
Array; Enumeration
Go
func maxHeightOfTriangle(red int, blue int) (ans int) { for k := 0; k < 2; k++ { c := [2]int{red, blue} for i, j := 1, k; i <= c[j]; i, j = i+1, j^1 { c[j] -= i ans = max(ans, i) } } return }
3,200
Maximum Height of a Triangle
Easy
<p>You are given two integers <code>red</code> and <code>blue</code> representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1<sup>st</sup> row will have 1 ball, the 2<sup>nd</sup> row will have 2 balls, the 3<sup>rd</sup> row will have 3 balls, and so on.</p> <p>All the balls in a particular row should be the <strong>same</strong> color, and adjacent rows should have <strong>different</strong> colors.</p> <p>Return the <strong>maximum</strong><em> height of the triangle</em> that can be achieved.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 4</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/brb.png" style="width: 300px; height: 240px; padding: 10px;" /></p> <p>The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 1, blue = 1</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 10, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= red, blue &lt;= 100</code></li> </ul>
Array; Enumeration
Java
class Solution { public int maxHeightOfTriangle(int red, int blue) { int ans = 0; for (int k = 0; k < 2; ++k) { int[] c = {red, blue}; for (int i = 1, j = k; i <= c[j]; j ^= 1, ++i) { c[j] -= i; ans = Math.max(ans, i); } } return ans; } }
3,200
Maximum Height of a Triangle
Easy
<p>You are given two integers <code>red</code> and <code>blue</code> representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1<sup>st</sup> row will have 1 ball, the 2<sup>nd</sup> row will have 2 balls, the 3<sup>rd</sup> row will have 3 balls, and so on.</p> <p>All the balls in a particular row should be the <strong>same</strong> color, and adjacent rows should have <strong>different</strong> colors.</p> <p>Return the <strong>maximum</strong><em> height of the triangle</em> that can be achieved.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 4</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/brb.png" style="width: 300px; height: 240px; padding: 10px;" /></p> <p>The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 1, blue = 1</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 10, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= red, blue &lt;= 100</code></li> </ul>
Array; Enumeration
Python
class Solution: def maxHeightOfTriangle(self, red: int, blue: int) -> int: ans = 0 for k in range(2): c = [red, blue] i, j = 1, k while i <= c[j]: c[j] -= i j ^= 1 ans = max(ans, i) i += 1 return ans
3,200
Maximum Height of a Triangle
Easy
<p>You are given two integers <code>red</code> and <code>blue</code> representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1<sup>st</sup> row will have 1 ball, the 2<sup>nd</sup> row will have 2 balls, the 3<sup>rd</sup> row will have 3 balls, and so on.</p> <p>All the balls in a particular row should be the <strong>same</strong> color, and adjacent rows should have <strong>different</strong> colors.</p> <p>Return the <strong>maximum</strong><em> height of the triangle</em> that can be achieved.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 4</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/brb.png" style="width: 300px; height: 240px; padding: 10px;" /></p> <p>The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 2, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 1, blue = 1</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">red = 10, blue = 1</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/3200-3299/3200.Maximum%20Height%20of%20a%20Triangle/images/br.png" style="width: 150px; height: 135px; padding: 10px;" /><br /> The only possible arrangement is shown above.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= red, blue &lt;= 100</code></li> </ul>
Array; Enumeration
TypeScript
function maxHeightOfTriangle(red: number, blue: number): number { let ans = 0; for (let k = 0; k < 2; ++k) { const c: [number, number] = [red, blue]; for (let i = 1, j = k; i <= c[j]; ++i, j ^= 1) { c[j] -= i; ans = Math.max(ans, i); } } return ans; }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maximumLength(vector<int>& nums) { int k = 2; int f[k][k]; memset(f, 0, sizeof(f)); int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = max(ans, f[x][y]); } } return ans; } };
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public int MaximumLength(int[] nums) { int k = 2; int[,] f = new int[k, k]; int ans = 0; foreach (int num in nums) { int x = num % k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x, y] = f[y, x] + 1; ans = Math.Max(ans, f[x, y]); } } return ans; } }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumLength(nums []int) (ans int) { k := 2 f := make([][]int, k) for i := range f { f[i] = make([]int, k) } for _, x := range nums { x %= k for j := 0; j < k; j++ { y := (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) } } return }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maximumLength(int[] nums) { int k = 2; int[][] f = new int[k][k]; int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; } }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumLength(self, nums: List[int]) -> int: k = 2 f = [[0] * k for _ in range(k)] ans = 0 for x in nums: x %= k for j in range(k): y = (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) return ans
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_length(nums: Vec<i32>) -> i32 { let mut f = [[0; 2]; 2]; let mut ans = 0; for x in nums { let x = (x % 2) as usize; for j in 0..2 { let y = ((j + 2 - x) % 2) as usize; f[x][y] = f[y][x] + 1; ans = ans.max(f[x][y]); } } ans } }
3,201
Find the Maximum Length of Valid Subsequence I
Medium
You are given an integer array <code>nums</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li> </ul> <p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</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">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</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,1,1,2,1,2]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 3]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumLength(nums: number[]): number { const k = 2; const f: number[][] = Array.from({ length: k }, () => Array(k).fill(0)); let ans: number = 0; for (let x of nums) { x %= k; for (let j = 0; j < k; ++j) { const y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maximumLength(vector<int>& nums, int k) { int f[k][k]; memset(f, 0, sizeof(f)); int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = max(ans, f[x][y]); } } return ans; } };
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
C#
public class Solution { public int MaximumLength(int[] nums, int k) { int[,] f = new int[k, k]; int ans = 0; foreach (int num in nums) { int x = num % k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x, y] = f[y, x] + 1; ans = Math.Max(ans, f[x, y]); } } return ans; } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumLength(nums []int, k int) (ans int) { f := make([][]int, k) for i := range f { f[i] = make([]int, k) } for _, x := range nums { x %= k for j := 0; j < k; j++ { y := (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) } } return }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maximumLength(int[] nums, int k) { int[][] f = new int[k][k]; int ans = 0; for (int x : nums) { x %= k; for (int j = 0; j < k; ++j) { int y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumLength(self, nums: List[int], k: int) -> int: f = [[0] * k for _ in range(k)] ans = 0 for x in nums: x %= k for j in range(k): y = (j - x + k) % k f[x][y] = f[y][x] + 1 ans = max(ans, f[x][y]) return ans
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_length(nums: Vec<i32>, k: i32) -> i32 { let k = k as usize; let mut f = vec![vec![0; k]; k]; let mut ans = 0; for x in nums { let x = (x % k as i32) as usize; for j in 0..k { let y = (j + k - x) % k; f[x][y] = f[y][x] + 1; ans = ans.max(f[x][y]); } } ans } }
3,202
Find the Maximum Length of Valid Subsequence II
Medium
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. <p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p> <ul> <li><code>(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li> </ul> Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumLength(nums: number[], k: number): number { const f: number[][] = Array.from({ length: k }, () => Array(k).fill(0)); let ans: number = 0; for (let x of nums) { x %= k; for (let j = 0; j < k; ++j) { const y = (j - x + k) % k; f[x][y] = f[y][x] + 1; ans = Math.max(ans, f[x][y]); } } return ans; }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
C++
class Solution { public: int minimumDiameterAfterMerge(vector<vector<int>>& edges1, vector<vector<int>>& edges2) { int d1 = treeDiameter(edges1); int d2 = treeDiameter(edges2); return max({d1, d2, (d1 + 1) / 2 + (d2 + 1) / 2 + 1}); } int treeDiameter(vector<vector<int>>& edges) { int n = edges.size() + 1; vector<int> g[n]; for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } int ans = 0, a = 0; auto dfs = [&](this auto&& dfs, int i, int fa, int t) -> void { for (int j : g[i]) { if (j != fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } }; dfs(0, -1, 0); dfs(a, -1, 0); return ans; } };
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
C#
public class Solution { private List<int>[] g; private int ans; private int a; public int MinimumDiameterAfterMerge(int[][] edges1, int[][] edges2) { int d1 = TreeDiameter(edges1); int d2 = TreeDiameter(edges2); return Math.Max(Math.Max(d1, d2), (d1 + 1) / 2 + (d2 + 1) / 2 + 1); } public int TreeDiameter(int[][] edges) { int n = edges.Length + 1; g = new List<int>[n]; for (int k = 0; k < n; ++k) { g[k] = new List<int>(); } ans = 0; a = 0; foreach (var e in edges) { int a = e[0], b = e[1]; g[a].Add(b); g[b].Add(a); } Dfs(0, -1, 0); Dfs(a, -1, 0); return ans; } private void Dfs(int i, int fa, int t) { foreach (int j in g[i]) { if (j != fa) { Dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
Go
func minimumDiameterAfterMerge(edges1 [][]int, edges2 [][]int) int { d1 := treeDiameter(edges1) d2 := treeDiameter(edges2) return max(d1, d2, (d1+1)/2+(d2+1)/2+1) } func treeDiameter(edges [][]int) (ans 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) } a := 0 var dfs func(i, fa, t int) dfs = func(i, fa, t int) { for _, j := range g[i] { if j != fa { dfs(j, i, t+1) } } if ans < t { ans = t a = i } } dfs(0, -1, 0) dfs(a, -1, 0) return }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
Java
class Solution { private List<Integer>[] g; private int ans; private int a; public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) { int d1 = treeDiameter(edges1); int d2 = treeDiameter(edges2); return Math.max(Math.max(d1, d2), (d1 + 1) / 2 + (d2 + 1) / 2 + 1); } public int treeDiameter(int[][] edges) { int n = edges.length + 1; g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); ans = 0; a = 0; for (var e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } dfs(0, -1, 0); dfs(a, -1, 0); return ans; } private void dfs(int i, int fa, int t) { for (int j : g[i]) { if (j != fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
Python
class Solution: def minimumDiameterAfterMerge( self, edges1: List[List[int]], edges2: List[List[int]] ) -> int: d1 = self.treeDiameter(edges1) d2 = self.treeDiameter(edges2) return max(d1, d2, (d1 + 1) // 2 + (d2 + 1) // 2 + 1) def treeDiameter(self, edges: List[List[int]]) -> int: def dfs(i: int, fa: int, t: int): for j in g[i]: if j != fa: dfs(j, i, t + 1) nonlocal ans, a if ans < t: ans = t a = i g = defaultdict(list) for a, b in edges: g[a].append(b) g[b].append(a) ans = a = 0 dfs(0, -1, 0) dfs(a, -1, 0) return ans
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
Rust
impl Solution { pub fn minimum_diameter_after_merge(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>) -> i32 { let d1 = Self::tree_diameter(&edges1); let d2 = Self::tree_diameter(&edges2); d1.max(d2).max((d1 + 1) / 2 + (d2 + 1) / 2 + 1) } fn tree_diameter(edges: &Vec<Vec<i32>>) -> 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); g[b].push(a); } let mut ans = 0; let mut a = 0; fn dfs(g: &Vec<Vec<usize>>, i: usize, fa: isize, t: i32, ans: &mut i32, a: &mut usize) { for &j in &g[i] { if j as isize != fa { dfs(g, j, i as isize, t + 1, ans, a); } } if *ans < t { *ans = t; *a = i; } } dfs(&g, 0, -1, 0, &mut ans, &mut a); dfs(&g, a, -1, 0, &mut ans, &mut a); ans } }
3,203
Find Minimum Diameter After Merging Two Trees
Hard
<p>There exist two <strong>undirected </strong>trees with <code>n</code> and <code>m</code> nodes, numbered from <code>0</code> to <code>n - 1</code> and from <code>0</code> to <code>m - 1</code>, respectively. 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>You must connect one node from the first tree with another node from the second tree with an edge.</p> <p>Return the <strong>minimum </strong>possible <strong>diameter </strong>of the resulting tree.</p> <p>The <strong>diameter</strong> of a tree is the length of the <em>longest</em> path between any two nodes in the tree.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example11-transformed.png" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3203.Find%20Minimum%20Diameter%20After%20Merging%20Two%20Trees/images/example211.png" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 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 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>edges2[i] = [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; 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; Graph
TypeScript
function minimumDiameterAfterMerge(edges1: number[][], edges2: number[][]): number { const d1 = treeDiameter(edges1); const d2 = treeDiameter(edges2); return Math.max(d1, d2, Math.ceil(d1 / 2) + Math.ceil(d2 / 2) + 1); } function treeDiameter(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); } let [ans, a] = [0, 0]; const dfs = (i: number, fa: number, t: number): void => { for (const j of g[i]) { if (j !== fa) { dfs(j, i, t + 1); } } if (ans < t) { ans = t; a = i; } }; dfs(0, -1, 0); dfs(a, -1, 0); return ans; }
3,204
Bitwise User Permissions Analysis
Medium
<p>Table: <code>user_permissions</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | permissions | int | +-------------+---------+ user_id is the primary key. Each row of this table contains the user ID and their permissions encoded as an integer. </pre> <p>Consider that each bit in the <code>permissions</code> integer represents a different access level or feature that a user has.</p> <p>Write a solution to calculate the following:</p> <ul> <li>common_perms: The access level granted to <strong>all users</strong>. This is computed using a <strong>bitwise AND</strong> operation on the <code>permissions</code> column.</li> <li>any_perms: The access level granted to <strong>any user</strong>. This is computed using a <strong>bitwise OR</strong> operation on the <code>permissions</code> column.</li> </ul> <p>Return <em>the result table in <strong>any</strong> order</em>.</p> <p>The result format is shown in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>user_permissions table:</p> <pre class="example-io"> +---------+-------------+ | user_id | permissions | +---------+-------------+ | 1 | 5 | | 2 | 12 | | 3 | 7 | | 4 | 3 | +---------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+--------------+ | common_perms | any_perms | +--------------+-------------+ | 0 | 15 | +--------------+-------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>common_perms:</strong> Represents the bitwise AND result of all permissions: <ul> <li>For user 1 (5): 5 (binary 0101)</li> <li>For user 2 (12): 12 (binary 1100)</li> <li>For user 3 (7): 7 (binary 0111)</li> <li>For user 4 (3): 3 (binary 0011)</li> <li>Bitwise AND: 5 &amp; 12 &amp; 7 &amp; 3 = 0 (binary 0000)</li> </ul> </li> <li><strong>any_perms:</strong> Represents the bitwise OR result of all permissions: <ul> <li>Bitwise OR: 5 | 12 | 7 | 3 = 15 (binary 1111)</li> </ul> </li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT BIT_AND(permissions) AS common_perms, BIT_OR(permissions) AS any_perms FROM user_permissions;