id
int64
1
3.64k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,452
Sum of Good Numbers
Easy
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p> <p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</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,3,2,1,5,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= floor(nums.length / 2)</code></li> </ul>
Array
Python
class Solution: def sumOfGoodNumbers(self, nums: List[int], k: int) -> int: ans = 0 for i, x in enumerate(nums): if i >= k and x <= nums[i - k]: continue if i + k < len(nums) and x <= nums[i + k]: continue ans += x return ans
3,452
Sum of Good Numbers
Easy
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p> <p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</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,3,2,1,5,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= floor(nums.length / 2)</code></li> </ul>
Array
TypeScript
function sumOfGoodNumbers(nums: number[], k: number): number { const n = nums.length; let ans = 0; for (let i = 0; i < n; ++i) { if (i >= k && nums[i] <= nums[i - k]) { continue; } if (i + k < n && nums[i] <= nums[i + k]) { continue; } ans += nums[i]; } return ans; }
3,456
Find Special Substring of Length K
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p> <ol> <li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>&quot;aaa&quot;</code> or <code>&quot;bbb&quot;</code>).</li> <li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li> <li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li> </ol> <p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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">s = &quot;aaabaaa&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substring <code>s[4..6] == &quot;aaa&quot;</code> satisfies the conditions.</p> <ul> <li>It has a length of 3.</li> <li>All characters are the same.</li> <li>The character before <code>&quot;aaa&quot;</code> is <code>&#39;b&#39;</code>, which is different from <code>&#39;a&#39;</code>.</li> <li>There is no character after <code>&quot;aaa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String
C++
class Solution { public: bool hasSpecialSubstring(string s, int k) { int n = s.length(); for (int l = 0, cnt = 0; l < n;) { int r = l + 1; while (r < n && s[r] == s[l]) { ++r; } if (r - l == k) { return true; } l = r; } return false; } };
3,456
Find Special Substring of Length K
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p> <ol> <li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>&quot;aaa&quot;</code> or <code>&quot;bbb&quot;</code>).</li> <li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li> <li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li> </ol> <p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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">s = &quot;aaabaaa&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substring <code>s[4..6] == &quot;aaa&quot;</code> satisfies the conditions.</p> <ul> <li>It has a length of 3.</li> <li>All characters are the same.</li> <li>The character before <code>&quot;aaa&quot;</code> is <code>&#39;b&#39;</code>, which is different from <code>&#39;a&#39;</code>.</li> <li>There is no character after <code>&quot;aaa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String
Go
func hasSpecialSubstring(s string, k int) bool { n := len(s) for l := 0; l < n; { r := l + 1 for r < n && s[r] == s[l] { r++ } if r-l == k { return true } l = r } return false }
3,456
Find Special Substring of Length K
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p> <ol> <li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>&quot;aaa&quot;</code> or <code>&quot;bbb&quot;</code>).</li> <li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li> <li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li> </ol> <p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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">s = &quot;aaabaaa&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substring <code>s[4..6] == &quot;aaa&quot;</code> satisfies the conditions.</p> <ul> <li>It has a length of 3.</li> <li>All characters are the same.</li> <li>The character before <code>&quot;aaa&quot;</code> is <code>&#39;b&#39;</code>, which is different from <code>&#39;a&#39;</code>.</li> <li>There is no character after <code>&quot;aaa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String
Java
class Solution { public boolean hasSpecialSubstring(String s, int k) { int n = s.length(); for (int l = 0, cnt = 0; l < n;) { int r = l + 1; while (r < n && s.charAt(r) == s.charAt(l)) { ++r; } if (r - l == k) { return true; } l = r; } return false; } }
3,456
Find Special Substring of Length K
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p> <ol> <li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>&quot;aaa&quot;</code> or <code>&quot;bbb&quot;</code>).</li> <li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li> <li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li> </ol> <p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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">s = &quot;aaabaaa&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substring <code>s[4..6] == &quot;aaa&quot;</code> satisfies the conditions.</p> <ul> <li>It has a length of 3.</li> <li>All characters are the same.</li> <li>The character before <code>&quot;aaa&quot;</code> is <code>&#39;b&#39;</code>, which is different from <code>&#39;a&#39;</code>.</li> <li>There is no character after <code>&quot;aaa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String
Python
class Solution: def hasSpecialSubstring(self, s: str, k: int) -> bool: l, n = 0, len(s) while l < n: r = l while r < n and s[r] == s[l]: r += 1 if r - l == k: return True l = r return False
3,456
Find Special Substring of Length K
Easy
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p> <ol> <li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>&quot;aaa&quot;</code> or <code>&quot;bbb&quot;</code>).</li> <li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li> <li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li> </ol> <p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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">s = &quot;aaabaaa&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substring <code>s[4..6] == &quot;aaa&quot;</code> satisfies the conditions.</p> <ul> <li>It has a length of 3.</li> <li>All characters are the same.</li> <li>The character before <code>&quot;aaa&quot;</code> is <code>&#39;b&#39;</code>, which is different from <code>&#39;a&#39;</code>.</li> <li>There is no character after <code>&quot;aaa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
String
TypeScript
function hasSpecialSubstring(s: string, k: number): boolean { const n = s.length; for (let l = 0; l < n; ) { let r = l + 1; while (r < n && s[r] === s[l]) { r++; } if (r - l === k) { return true; } l = r; } return false; }
3,457
Eat Pizzas!
Medium
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W &lt;= X &lt;= Y &lt;= Z</code>, you gain the weight of only 1 pizza!</p> <ul> <li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li> <li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li> </ul> <p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p> <p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li> <li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li> <li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= n == pizzas.length &lt;= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li> <li><code>1 &lt;= pizzas[i] &lt;= 10<sup>5</sup></code></li> <li><code>n</code> is a multiple of 4.</li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: long long maxWeight(vector<int>& pizzas) { int n = pizzas.size(); int days = pizzas.size() / 4; ranges::sort(pizzas); int odd = (days + 1) / 2; int even = days - odd; long long ans = accumulate(pizzas.begin() + n - odd, pizzas.end(), 0LL); for (int i = n - odd - 2; even; --even) { ans += pizzas[i]; i -= 2; } return ans; } };
3,457
Eat Pizzas!
Medium
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W &lt;= X &lt;= Y &lt;= Z</code>, you gain the weight of only 1 pizza!</p> <ul> <li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li> <li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li> </ul> <p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p> <p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li> <li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li> <li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= n == pizzas.length &lt;= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li> <li><code>1 &lt;= pizzas[i] &lt;= 10<sup>5</sup></code></li> <li><code>n</code> is a multiple of 4.</li> </ul>
Greedy; Array; Sorting
Go
func maxWeight(pizzas []int) (ans int64) { n := len(pizzas) days := n / 4 sort.Ints(pizzas) odd := (days + 1) / 2 even := days - odd for i := n - odd; i < n; i++ { ans += int64(pizzas[i]) } for i := n - odd - 2; even > 0; even-- { ans += int64(pizzas[i]) i -= 2 } return }
3,457
Eat Pizzas!
Medium
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W &lt;= X &lt;= Y &lt;= Z</code>, you gain the weight of only 1 pizza!</p> <ul> <li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li> <li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li> </ul> <p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p> <p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li> <li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li> <li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= n == pizzas.length &lt;= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li> <li><code>1 &lt;= pizzas[i] &lt;= 10<sup>5</sup></code></li> <li><code>n</code> is a multiple of 4.</li> </ul>
Greedy; Array; Sorting
Java
class Solution { public long maxWeight(int[] pizzas) { int n = pizzas.length; int days = n / 4; Arrays.sort(pizzas); int odd = (days + 1) / 2; int even = days / 2; long ans = 0; for (int i = n - odd; i < n; ++i) { ans += pizzas[i]; } for (int i = n - odd - 2; even > 0; --even) { ans += pizzas[i]; i -= 2; } return ans; } }
3,457
Eat Pizzas!
Medium
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W &lt;= X &lt;= Y &lt;= Z</code>, you gain the weight of only 1 pizza!</p> <ul> <li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li> <li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li> </ul> <p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p> <p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li> <li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li> <li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= n == pizzas.length &lt;= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li> <li><code>1 &lt;= pizzas[i] &lt;= 10<sup>5</sup></code></li> <li><code>n</code> is a multiple of 4.</li> </ul>
Greedy; Array; Sorting
Python
class Solution: def maxWeight(self, pizzas: List[int]) -> int: days = len(pizzas) // 4 pizzas.sort() odd = (days + 1) // 2 even = days - odd ans = sum(pizzas[-odd:]) i = len(pizzas) - odd - 2 for _ in range(even): ans += pizzas[i] i -= 2 return ans
3,457
Eat Pizzas!
Medium
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W &lt;= X &lt;= Y &lt;= Z</code>, you gain the weight of only 1 pizza!</p> <ul> <li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li> <li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li> </ul> <p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p> <p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li> <li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li> <li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li> </ul> <p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= n == pizzas.length &lt;= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li> <li><code>1 &lt;= pizzas[i] &lt;= 10<sup>5</sup></code></li> <li><code>n</code> is a multiple of 4.</li> </ul>
Greedy; Array; Sorting
TypeScript
function maxWeight(pizzas: number[]): number { const n = pizzas.length; const days = n >> 2; pizzas.sort((a, b) => a - b); const odd = (days + 1) >> 1; let even = days - odd; let ans = 0; for (let i = n - odd; i < n; ++i) { ans += pizzas[i]; } for (let i = n - odd - 2; even; --even) { ans += pizzas[i]; i -= 2; } return ans; }
3,459
Length of Longest V-Shaped Diagonal Segment
Hard
<p>You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, where each element is either <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>A <strong>V-shaped diagonal segment</strong> is defined as:</p> <ul> <li>The segment starts with <code>1</code>.</li> <li>The subsequent elements follow this infinite sequence: <code>2, 0, 2, 0, ...</code>.</li> <li>The segment: <ul> <li>Starts <strong>along</strong> a diagonal direction (top-left to bottom-right, bottom-right to top-left, top-right to bottom-left, or bottom-left to top-right).</li> <li>Continues the<strong> sequence</strong> in the same diagonal direction.</li> <li>Makes<strong> at most one clockwise 90-degree</strong><strong> turn</strong> to another diagonal direction while <strong>maintaining</strong> the sequence.</li> </ul> </li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/length_of_longest3.jpg" style="width: 481px; height: 202px;" /></p> <p>Return the <strong>length</strong> of the <strong>longest</strong> <strong>V-shaped diagonal segment</strong>. If no valid segment <em>exists</em>, return 0.</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 = [[2,2,1,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]</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/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_1-2.jpg" style="width: 201px; height: 192px;" /></p> <p>The longest V-shaped diagonal segment has a length of 5 and follows these coordinates: <code>(0,2) &rarr; (1,3) &rarr; (2,4)</code>, takes a <strong>90-degree clockwise turn</strong> at <code>(2,4)</code>, and continues as <code>(3,3) &rarr; (4,2)</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,2,2,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_2.jpg" style="width: 201px; height: 201px;" /></strong></p> <p>The longest V-shaped diagonal segment has a length of 4 and follows these coordinates: <code>(2,3) &rarr; (3,2)</code>, takes a <strong>90-degree clockwise turn</strong> at <code>(3,2)</code>, and continues as <code>(2,1) &rarr; (1,0)</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,2,2,2,2],[2,2,2,2,0],[2,0,0,0,0],[0,0,2,2,2],[2,0,0,2,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_3.jpg" style="width: 201px; height: 201px;" /></strong></p> <p>The longest V-shaped diagonal segment has a length of 5 and follows these coordinates: <code>(0,0) &rarr; (1,1) &rarr; (2,2) &rarr; (3,3) &rarr; (4,4)</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest V-shaped diagonal segment has a length of 1 and follows these coordinates: <code>(0,0)</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code> or <code>2</code>.</li> </ul>
Memoization; Array; Dynamic Programming; Matrix
Python
class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) next_digit = {1: 2, 2: 0, 0: 2} def within_bounds(i, j): return 0 <= i < m and 0 <= j < n @cache def f(i, j, di, dj, turned): result = 1 successor = next_digit[grid[i][j]] if within_bounds(i + di, j + dj) and grid[i + di][j + dj] == successor: result = 1 + f(i + di, j + dj, di, dj, turned) if not turned: di, dj = dj, -di if within_bounds(i + di, j + dj) and grid[i + di][j + dj] == successor: result = max(result, 1 + f(i + di, j + dj, di, dj, True)) return result directions = ((1, 1), (-1, 1), (1, -1), (-1, -1)) result = 0 for i in range(m): for j in range(n): if grid[i][j] != 1: continue for di, dj in directions: result = max(result, f(i, j, di, dj, False)) return result
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
C++
class Solution { public: int longestCommonPrefix(string s, string t) { int n = s.length(), m = t.length(); int i = 0, j = 0; bool rem = false; while (i < n && j < m) { if (s[i] != t[j]) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; } };
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Go
func longestCommonPrefix(s string, t string) int { n, m := len(s), len(t) i, j := 0, 0 rem := false for i < n && j < m { if s[i] != t[j] { if rem { break } rem = true } else { j++ } i++ } return j }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Java
class Solution { public int longestCommonPrefix(String s, String t) { int n = s.length(), m = t.length(); int i = 0, j = 0; boolean rem = false; while (i < n && j < m) { if (s.charAt(i) != t.charAt(j)) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; } }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
JavaScript
/** * @param {string} s * @param {string} t * @return {number} */ var longestCommonPrefix = function (s, t) { const [n, m] = [s.length, t.length]; let [i, j] = [0, 0]; let rem = false; while (i < n && j < m) { if (s[i] !== t[j]) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; };
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Python
class Solution: def longestCommonPrefix(self, s: str, t: str) -> int: n, m = len(s), len(t) i = j = 0 rem = False while i < n and j < m: if s[i] != t[j]: if rem: break rem = True else: j += 1 i += 1 return j
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn longest_common_prefix(s: String, t: String) -> i32 { let (n, m) = (s.len(), t.len()); let (mut i, mut j) = (0, 0); let mut rem = false; while i < n && j < m { if s.as_bytes()[i] != t.as_bytes()[j] { if rem { break; } rem = true; } else { j += 1; } i += 1; } j as i32 } }
3,460
Longest Common Prefix After at Most One Removal
Medium
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p> <p><strong>Note:</strong> <code>s</code> can be left without any removal.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;madxa&quot;, t = &quot;madam&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[3]</code> from <code>s</code> results in <code>&quot;mada&quot;</code>, which has a longest common prefix of length 4 with <code>t</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;, t = &quot;eetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>Removing <code>s[0]</code> from <code>s</code> results in <code>&quot;eetcode&quot;</code>, which matches <code>t</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;one&quot;, t = &quot;one&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No removal is needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;b&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>s</code> and <code>t</code> cannot have a common prefix.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> contain only lowercase English letters.</li> </ul>
Two Pointers; String
TypeScript
function longestCommonPrefix(s: string, t: string): number { const [n, m] = [s.length, t.length]; let [i, j] = [0, 0]; let rem: boolean = false; while (i < n && j < m) { if (s[i] !== t[j]) { if (rem) { break; } rem = true; } else { ++j; } ++i; } return j; }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
C++
class Solution { public: bool hasSameDigits(string s) { int n = s.size(); string t = s; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (t[i] - '0' + t[i + 1] - '0') % 10 + '0'; } } return t[0] == t[1]; } };
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Go
func hasSameDigits(s string) bool { t := []byte(s) n := len(t) for k := n - 1; k > 1; k-- { for i := 0; i < k; i++ { t[i] = (t[i]-'0'+t[i+1]-'0')%10 + '0' } } return t[0] == t[1] }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Java
class Solution { public boolean hasSameDigits(String s) { char[] t = s.toCharArray(); int n = t.length; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (char) ((t[i] - '0' + t[i + 1] - '0') % 10 + '0'); } } return t[0] == t[1]; } }
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
Python
class Solution: def hasSameDigits(self, s: str) -> bool: t = list(map(int, s)) n = len(t) for k in range(n - 1, 1, -1): for i in range(k): t[i] = (t[i] + t[i + 1]) % 10 return t[0] == t[1]
3,461
Check If Digits Are Equal in String After Operations I
Easy
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p> <ul> <li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li> <li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li> </ul> <p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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">s = &quot;3902&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;3902&quot;</code></li> <li>First operation: <ul> <li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li> <li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li> <li><code>s</code> becomes <code>&quot;292&quot;</code></li> </ul> </li> <li>Second operation: <ul> <li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li> <li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li> <li><code>s</code> becomes <code>&quot;11&quot;</code></li> </ul> </li> <li>Since the digits in <code>&quot;11&quot;</code> are the same, the output is <code>true</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;34789&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially, <code>s = &quot;34789&quot;</code>.</li> <li>After the first operation, <code>s = &quot;7157&quot;</code>.</li> <li>After the second operation, <code>s = &quot;862&quot;</code>.</li> <li>After the third operation, <code>s = &quot;48&quot;</code>.</li> <li>Since <code>&#39;4&#39; != &#39;8&#39;</code>, the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only digits.</li> </ul>
Math; String; Combinatorics; Number Theory; Simulation
TypeScript
function hasSameDigits(s: string): boolean { const t = s.split('').map(Number); const n = t.length; for (let k = n - 1; k > 1; --k) { for (let i = 0; i < k; ++i) { t[i] = (t[i] + t[i + 1]) % 10; } } return t[0] === t[1]; }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</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,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
C++
class Solution { public: long long maxSum(vector<vector<int>>& grid, vector<int>& limits, int k) { priority_queue<int, vector<int>, greater<int>> pq; int n = grid.size(); for (int i = 0; i < n; ++i) { vector<int> nums = grid[i]; int limit = limits[i]; ranges::sort(nums); for (int j = 0; j < limit; ++j) { pq.push(nums[nums.size() - j - 1]); if (pq.size() > k) { pq.pop(); } } } long long ans = 0; while (!pq.empty()) { ans += pq.top(); pq.pop(); } return ans; } };
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</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,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Go
type MinHeap []int func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] } func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(int)) } func (h *MinHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func maxSum(grid [][]int, limits []int, k int) int64 { pq := &MinHeap{} heap.Init(pq) n := len(grid) for i := 0; i < n; i++ { nums := make([]int, len(grid[i])) copy(nums, grid[i]) limit := limits[i] sort.Ints(nums) for j := 0; j < limit; j++ { heap.Push(pq, nums[len(nums)-j-1]) if pq.Len() > k { heap.Pop(pq) } } } var ans int64 = 0 for pq.Len() > 0 { ans += int64(heap.Pop(pq).(int)) } return ans }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</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,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Java
class Solution { public long maxSum(int[][] grid, int[] limits, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); int n = grid.length; for (int i = 0; i < n; ++i) { int[] nums = grid[i]; int limit = limits[i]; Arrays.sort(nums); for (int j = 0; j < limit; ++j) { pq.offer(nums[nums.length - j - 1]); if (pq.size() > k) { pq.poll(); } } } long ans = 0; for (int x : pq) { ans += x; } return ans; } }
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</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,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
Python
class Solution: def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int: pq = [] for nums, limit in zip(grid, limits): nums.sort() for _ in range(limit): heappush(pq, nums.pop()) if len(pq) > k: heappop(pq) return sum(pq)
3,462
Maximum Sum With at Most K Elements
Medium
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p> <ul data-spread="false"> <li> <p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p> </li> </ul> <p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</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,2],[3,4]], limits = [1,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li> <li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">21</span></p> <p><strong>Explanation:</strong></p> <ul> <li>From the first row, we can take at most 2 elements. The element taken is 7.</li> <li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li> <li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == grid.length == limits.length</code></li> <li><code>m == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= limits[i] &lt;= m</code></li> <li><code>0 &lt;= k &lt;= min(n * m, sum(limits))</code></li> </ul>
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
TypeScript
function maxSum(grid: number[][], limits: number[], k: number): number { const pq = new MinPriorityQueue(); const n = grid.length; for (let i = 0; i < n; i++) { const nums = grid[i]; const limit = limits[i]; nums.sort((a, b) => a - b); for (let j = 0; j < limit; j++) { pq.enqueue(nums[nums.length - j - 1]); if (pq.size() > k) { pq.dequeue(); } } } let ans = 0; while (!pq.isEmpty()) { ans += pq.dequeue() as number; } return ans; }
3,465
Find Products with Valid Serial Numbers
Easy
<p>Table: <code>products</code></p> <pre> +--------------+------------+ | Column Name | Type | +--------------+------------+ | product_id | int | | product_name | varchar | | description | varchar | +--------------+------------+ (product_id) is the unique key for this table. Each row in the table represents a product with its unique ID, name, and description. </pre> <p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p> <ul> <li>It starts with the letters <strong>SN</strong>&nbsp;(case-sensitive).</li> <li>Followed by exactly <code>4</code> digits.</li> <li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li> <li>The serial number must be within the description (it may not necessarily start at the beginning).</li> </ul> <p>Return <em>the result table&nbsp;ordered by</em> <code>product_id</code> <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>products table:</p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 3 | Widget C | Product SN1234-56789 is available now | | 4 | Widget D | No serial number here | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Product 1:</strong> Valid serial number SN1234-5678</li> <li><strong>Product 2:</strong> Valid serial number SN9876-1234</li> <li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li> <li><strong>Product 4:</strong> No serial number in the description</li> <li><strong>Product 5:</strong> Valid serial number SN4321-8765</li> </ul> <p>The result table is ordered by product_id in ascending order.</p> </div>
Database
Python
import pandas as pd def find_valid_serial_products(products: pd.DataFrame) -> pd.DataFrame: valid_pattern = r"\bSN[0-9]{4}-[0-9]{4}\b" valid_products = products[ products["description"].str.contains(valid_pattern, regex=True) ] valid_products = valid_products.sort_values(by="product_id") return valid_products
3,465
Find Products with Valid Serial Numbers
Easy
<p>Table: <code>products</code></p> <pre> +--------------+------------+ | Column Name | Type | +--------------+------------+ | product_id | int | | product_name | varchar | | description | varchar | +--------------+------------+ (product_id) is the unique key for this table. Each row in the table represents a product with its unique ID, name, and description. </pre> <p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p> <ul> <li>It starts with the letters <strong>SN</strong>&nbsp;(case-sensitive).</li> <li>Followed by exactly <code>4</code> digits.</li> <li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li> <li>The serial number must be within the description (it may not necessarily start at the beginning).</li> </ul> <p>Return <em>the result table&nbsp;ordered by</em> <code>product_id</code> <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>products table:</p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 3 | Widget C | Product SN1234-56789 is available now | | 4 | Widget D | No serial number here | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+------------------------------------------------------+ | product_id | product_name | description | +------------+--------------+------------------------------------------------------+ | 1 | Widget A | This is a sample product with SN1234-5678 | | 2 | Widget B | A product with serial SN9876-1234 in the description | | 5 | Widget E | Check out SN4321-8765 in this description | +------------+--------------+------------------------------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Product 1:</strong> Valid serial number SN1234-5678</li> <li><strong>Product 2:</strong> Valid serial number SN9876-1234</li> <li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li> <li><strong>Product 4:</strong> No serial number in the description</li> <li><strong>Product 5:</strong> Valid serial number SN4321-8765</li> </ul> <p>The result table is ordered by product_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT product_id, product_name, description FROM products WHERE description REGEXP '\\bSN[0-9]{4}-[0-9]{4}\\b' ORDER BY 1;
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: long long maxCoins(vector<int>& lane1, vector<int>& lane2) { int n = lane1.size(); long long ans = -1e18; vector<vector<vector<long long>>> f(n, vector<vector<long long>>(2, vector<long long>(3, -1e18))); auto dfs = [&](this auto&& dfs, int i, int j, int k) -> long long { if (i >= n) { return 0LL; } if (f[i][j][k] != -1e18) { return f[i][j][k]; } int x = j == 0 ? lane1[i] : lane2[i]; long long ans = max((long long) x, dfs(i + 1, j, k) + x); if (k > 0) { ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x); ans = max(ans, dfs(i, j ^ 1, k - 1)); } return f[i][j][k] = ans; }; for (int i = 0; i < n; ++i) { ans = max(ans, dfs(i, 0, 2)); } return ans; } };
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxCoins(lane1 []int, lane2 []int) int64 { n := len(lane1) f := make([][2][3]int64, n) for i := range f { for j := range f[i] { for k := range f[i][j] { f[i][j][k] = -1 } } } var dfs func(int, int, int) int64 dfs = func(i, j, k int) int64 { if i >= n { return 0 } if f[i][j][k] != -1 { return f[i][j][k] } x := int64(lane1[i]) if j == 1 { x = int64(lane2[i]) } ans := max(x, dfs(i+1, j, k)+x) if k > 0 { ans = max(ans, dfs(i+1, j^1, k-1)+x) ans = max(ans, dfs(i, j^1, k-1)) } f[i][j][k] = ans return ans } ans := int64(-1e18) for i := range lane1 { ans = max(ans, dfs(i, 0, 2)) } return ans }
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private int n; private int[] lane1; private int[] lane2; private Long[][][] f; public long maxCoins(int[] lane1, int[] lane2) { n = lane1.length; this.lane1 = lane1; this.lane2 = lane2; f = new Long[n][2][3]; long ans = Long.MIN_VALUE; for (int i = 0; i < n; ++i) { ans = Math.max(ans, dfs(i, 0, 2)); } return ans; } private long dfs(int i, int j, int k) { if (i >= n) { return 0; } if (f[i][j][k] != null) { return f[i][j][k]; } int x = j == 0 ? lane1[i] : lane2[i]; long ans = Math.max(x, dfs(i + 1, j, k) + x); if (k > 0) { ans = Math.max(ans, dfs(i + 1, j ^ 1, k - 1) + x); ans = Math.max(ans, dfs(i, j ^ 1, k - 1)); } return f[i][j][k] = ans; } }
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxCoins(self, lane1: List[int], lane2: List[int]) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i >= n: return 0 x = lane1[i] if j == 0 else lane2[i] ans = max(x, dfs(i + 1, j, k) + x) if k > 0: ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x) ans = max(ans, dfs(i, j ^ 1, k - 1)) return ans n = len(lane1) ans = -inf for i in range(n): ans = max(ans, dfs(i, 0, 2)) return ans
3,466
Maximum Coin Collection
Medium
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p> <ul> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &gt; 0</code>, Mario gains <code>lane1[i]</code> coins.</li> <li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] &lt; 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li> <li>The same rules apply for <code>lane2</code>.</li> </ul> <p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p> <p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p> <p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p> <p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario drives the first mile on lane 1.</li> <li>He then changes to lane 2 and drives for two miles.</li> <li>He changes back to lane 1 for the last mile.</li> </ul> <p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at mile 0 in lane 1 and drives one mile.</li> <li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li> </ul> <p>He collects <code>1 + 3 + 4 = 8</code> coins.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li> </ul> <p>He collects a total of <code>2 + 3 = 5</code> coins.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p> <p><strong>Output:</strong> 11</p> <p><strong>Explanation:</strong></p> <ul> <li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li> </ul> <p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p> <p><strong>Output:</strong> <span class="example-io">-2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li> </ul> <p>He collects a total of -2 coins.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= lane1.length == lane2.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= lane1[i], lane2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxCoins(lane1: number[], lane2: number[]): number { const n = lane1.length; const NEG_INF = -1e18; const f: number[][][] = Array.from({ length: n }, () => Array.from({ length: 2 }, () => Array(3).fill(NEG_INF)), ); const dfs = (dfs: Function, i: number, j: number, k: number): number => { if (i >= n) { return 0; } if (f[i][j][k] !== NEG_INF) { return f[i][j][k]; } const x = j === 0 ? lane1[i] : lane2[i]; let ans = Math.max(x, dfs(dfs, i + 1, j, k) + x); if (k > 0) { ans = Math.max(ans, dfs(dfs, i + 1, j ^ 1, k - 1) + x); ans = Math.max(ans, dfs(dfs, i, j ^ 1, k - 1)); } f[i][j][k] = ans; return ans; }; let ans = NEG_INF; for (let i = 0; i < n; ++i) { ans = Math.max(ans, dfs(dfs, i, 0, 2)); } return ans; }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</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 = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</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 = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
C++
class Solution { public: vector<int> transformArray(vector<int>& nums) { int even = 0; for (int x : nums) { even += (x & 1 ^ 1); } for (int i = 0; i < even; ++i) { nums[i] = 0; } for (int i = even; i < nums.size(); ++i) { nums[i] = 1; } return nums; } };
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</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 = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</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 = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Go
func transformArray(nums []int) []int { even := 0 for _, x := range nums { even += x&1 ^ 1 } for i := 0; i < even; i++ { nums[i] = 0 } for i := even; i < len(nums); i++ { nums[i] = 1 } return nums }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</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 = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</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 = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Java
class Solution { public int[] transformArray(int[] nums) { int even = 0; for (int x : nums) { even += (x & 1 ^ 1); } for (int i = 0; i < even; ++i) { nums[i] = 0; } for (int i = even; i < nums.length; ++i) { nums[i] = 1; } return nums; } }
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</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 = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</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 = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
Python
class Solution: def transformArray(self, nums: List[int]) -> List[int]: even = sum(x % 2 == 0 for x in nums) for i in range(even): nums[i] = 0 for i in range(even, len(nums)): nums[i] = 1 return nums
3,467
Transform Array by Parity
Easy
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p> <ol> <li>Replace each even number with 0.</li> <li>Replace each odd numbers with 1.</li> <li>Sort the modified array in <strong>non-decreasing</strong> order.</li> </ol> <p>Return the resulting array after performing these operations.</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 = [4,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</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 = [1,5,1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li> <li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Counting; Sorting
TypeScript
function transformArray(nums: number[]): number[] { const even = nums.filter(x => x % 2 === 0).length; for (let i = 0; i < even; ++i) { nums[i] = 0; } for (let i = even; i < nums.length; ++i) { nums[i] = 1; } return nums; }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <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,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</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,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int largestInteger(vector<int>& nums, int k) { if (k == 1) { unordered_map<int, int> cnt; for (int x : nums) { ++cnt[x]; } int ans = -1; for (auto& [x, v] : cnt) { if (v == 1) { ans = max(ans, x); } } return ans; } int n = nums.size(); if (k == n) { return ranges::max(nums); } auto f = [&](int k) -> int { for (int i = 0; i < n; ++i) { if (i != k && nums[i] == nums[k]) { return -1; } } return nums[k]; }; return max(f(0), f(n - 1)); } };
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <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,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</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,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Go
func largestInteger(nums []int, k int) int { if k == 1 { cnt := make(map[int]int) for _, x := range nums { cnt[x]++ } ans := -1 for x, v := range cnt { if v == 1 { ans = max(ans, x) } } return ans } n := len(nums) if k == n { return slices.Max(nums) } f := func(k int) int { for i, x := range nums { if i != k && x == nums[k] { return -1 } } return nums[k] } return max(f(0), f(n-1)) }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <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,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</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,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Java
class Solution { private int[] nums; public int largestInteger(int[] nums, int k) { this.nums = nums; if (k == 1) { Map<Integer, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); } int ans = -1; for (var e : cnt.entrySet()) { if (e.getValue() == 1) { ans = Math.max(ans, e.getKey()); } } return ans; } if (k == nums.length) { return Arrays.stream(nums).max().getAsInt(); } return Math.max(f(0), f(nums.length - 1)); } private int f(int k) { for (int i = 0; i < nums.length; ++i) { if (i != k && nums[i] == nums[k]) { return -1; } } return nums[k]; } }
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <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,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</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,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
Python
class Solution: def largestInteger(self, nums: List[int], k: int) -> int: def f(k: int) -> int: for i, x in enumerate(nums): if i != k and x == nums[k]: return -1 return nums[k] if k == 1: cnt = Counter(nums) return max((x for x, v in cnt.items() if v == 1), default=-1) if k == len(nums): return max(nums) return max(f(0), f(len(nums) - 1))
3,471
Find the Largest Almost Missing Integer
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p> <p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p> A <strong>subarray</strong> is a contiguous sequence of elements within an array. <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,9,2,1,7], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li> <li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li> <li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li> <li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li> </ul> <p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li> <li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li> <li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li> </ul> <p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</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,0], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no integer that appears in only one subarray of size 1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table
TypeScript
function largestInteger(nums: number[], k: number): number { if (k === 1) { const cnt = new Map<number, number>(); for (const x of nums) { cnt.set(x, (cnt.get(x) || 0) + 1); } let ans = -1; for (const [x, v] of cnt.entries()) { if (v === 1 && x > ans) { ans = x; } } return ans; } const n = nums.length; if (k === n) { return Math.max(...nums); } const f = (k: number): number => { for (let i = 0; i < n; i++) { if (i !== k && nums[i] === nums[k]) { return -1; } } return nums[k]; }; return Math.max(f(0), f(n - 1)); }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int longestPalindromicSubsequence(string s, int k) { int n = s.size(); vector f(n, vector(n, vector<int>(k + 1, -1))); auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (i > j) { return 0; } if (i == j) { return 1; } if (f[i][j][k] != -1) { return f[i][j][k]; } int res = max(dfs(i + 1, j, k), dfs(i, j - 1, k)); int d = abs(s[i] - s[j]); int t = min(d, 26 - d); if (t <= k) { res = max(res, 2 + dfs(i + 1, j - 1, k - t)); } return f[i][j][k] = res; }; return dfs(0, n - 1, k); } };
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Go
func longestPalindromicSubsequence(s string, k int) int { n := len(s) f := make([][][]int, n) for i := range f { f[i] = make([][]int, n) for j := range f[i] { f[i][j] = make([]int, k+1) for l := range f[i][j] { f[i][j][l] = -1 } } } var dfs func(int, int, int) int dfs = func(i, j, k int) int { if i > j { return 0 } if i == j { return 1 } if f[i][j][k] != -1 { return f[i][j][k] } res := max(dfs(i+1, j, k), dfs(i, j-1, k)) d := abs(int(s[i]) - int(s[j])) t := min(d, 26-d) if t <= k { res = max(res, 2+dfs(i+1, j-1, k-t)) } f[i][j][k] = res return res } return dfs(0, n-1, k) } func abs(x int) int { if x < 0 { return -x } return x }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Java
class Solution { private char[] s; private Integer[][][] f; public int longestPalindromicSubsequence(String s, int k) { this.s = s.toCharArray(); int n = s.length(); f = new Integer[n][n][k + 1]; return dfs(0, n - 1, k); } private int dfs(int i, int j, int k) { if (i > j) { return 0; } if (i == j) { return 1; } if (f[i][j][k] != null) { return f[i][j][k]; } int res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k)); int d = Math.abs(s[i] - s[j]); int t = Math.min(d, 26 - d); if (t <= k) { res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t)); } f[i][j][k] = res; return res; } }
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
Python
class Solution: def longestPalindromicSubsequence(self, s: str, k: int) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i > j: return 0 if i == j: return 1 res = max(dfs(i + 1, j, k), dfs(i, j - 1, k)) d = abs(s[i] - s[j]) t = min(d, 26 - d) if t <= k: res = max(res, dfs(i + 1, j - 1, k - t) + 2) return res s = list(map(ord, s)) n = len(s) ans = dfs(0, n - 1, k) dfs.cache_clear() return ans
3,472
Longest Palindromic Subsequence After at Most K Operations
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>&#39;a&#39;</code> is after <code>&#39;z&#39;</code>). For example, replacing <code>&#39;a&#39;</code> with the next letter results in <code>&#39;b&#39;</code>, and replacing <code>&#39;a&#39;</code> with the previous letter results in <code>&#39;z&#39;</code>. Similarly, replacing <code>&#39;z&#39;</code> with the next letter results in <code>&#39;a&#39;</code>, and replacing <code>&#39;z&#39;</code> with the previous letter results in <code>&#39;y&#39;</code>.</p> <p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abced&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>&quot;acced&quot;</code>.</li> <li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>&quot;accec&quot;</code>.</li> </ul> <p>The subsequence <code>&quot;ccc&quot;</code> forms a palindrome of length 3, which is the maximum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;</span>aaazzz<span class="example-io">&quot;, k = 4</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <ul> <li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>&quot;zaazzz&quot;</code>.</li> <li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaazaz&quot;</code>.</li> <li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>&quot;zaaaaz&quot;</code>.</li> </ul> <p>The entire string forms a palindrome of length 6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 200</code></li> <li><code>1 &lt;= k &lt;= 200</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
String; Dynamic Programming
TypeScript
function longestPalindromicSubsequence(s: string, k: number): number { const n = s.length; const sCodes = s.split('').map(c => c.charCodeAt(0)); const f: number[][][] = Array.from({ length: n }, () => Array.from({ length: n }, () => Array(k + 1).fill(-1)), ); function dfs(i: number, j: number, k: number): number { if (i > j) { return 0; } if (i === j) { return 1; } if (f[i][j][k] !== -1) { return f[i][j][k]; } let res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k)); const d = Math.abs(sCodes[i] - sCodes[j]); const t = Math.min(d, 26 - d); if (t <= k) { res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t)); } return (f[i][j][k] = res); } return dfs(0, n - 1, k); }
3,475
DNA Pattern Recognition
Medium
<p>Table: <code>Samples</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | sample_id | int | | dna_sequence | varchar | | species | varchar | +----------------+---------+ sample_id is the unique key for this table. Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from. </pre> <p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p> <ul> <li>Sequences that <strong>start</strong> with <strong>ATG</strong>&nbsp;(a common <strong>start codon</strong>)</li> <li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong>&nbsp;(<strong>stop codons</strong>)</li> <li>Sequences containing the motif <strong>ATAT</strong>&nbsp;(a simple repeated pattern)</li> <li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong>&nbsp;(like <strong>GGG</strong>&nbsp;or <strong>GGGG</strong>)</li> </ul> <p>Return <em>the result table ordered by&nbsp;</em><em>sample_id 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>Samples table:</p> <pre class="example-io"> +-----------+------------------+-----------+ | sample_id | dna_sequence | species | +-----------+------------------+-----------+ | 1 | ATGCTAGCTAGCTAA | Human | | 2 | GGGTCAATCATC | Human | | 3 | ATATATCGTAGCTA | Human | | 4 | ATGGGGTCATCATAA | Mouse | | 5 | TCAGTCAGTCAG | Mouse | | 6 | ATATCGCGCTAG | Zebrafish | | 7 | CGTATGCGTCGTA | Zebrafish | +-----------+------------------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+------------------+-------------+-------------+------------+------------+------------+ | sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg | +-----------+------------------+-------------+-------------+------------+------------+------------+ | 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 | | 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 | | 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 | | 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 | | 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 | | 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 | | 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 | +-----------+------------------+-------------+-------------+------------+------------+------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Sample 1 (ATGCTAGCTAGCTAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 2 (GGGTCAATCATC): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 3 (ATATATCGTAGCTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Contains ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 4 (ATGGGGTCATCATAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 5 (TCAGTCAGTCAG): <ul> <li>Does not match any patterns (all fields = 0)</li> </ul> </li> <li>Sample 6 (ATATCGCGCTAG): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Ends with TAG&nbsp;(has_stop = 1)</li> <li>Starts with ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 7 (CGTATGCGTCGTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, &quot;TAG&quot;, or &quot;TGA&quot; (has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered by sample_id in ascending order</li> <li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li> </ul> </div>
Database
Python
import pandas as pd def analyze_dna_patterns(samples: pd.DataFrame) -> pd.DataFrame: samples["has_start"] = samples["dna_sequence"].str.startswith("ATG").astype(int) samples["has_stop"] = ( samples["dna_sequence"].str.endswith(("TAA", "TAG", "TGA")).astype(int) ) samples["has_atat"] = samples["dna_sequence"].str.contains("ATAT").astype(int) samples["has_ggg"] = samples["dna_sequence"].str.contains("GGG+").astype(int) return samples.sort_values(by="sample_id").reset_index(drop=True)
3,475
DNA Pattern Recognition
Medium
<p>Table: <code>Samples</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | sample_id | int | | dna_sequence | varchar | | species | varchar | +----------------+---------+ sample_id is the unique key for this table. Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from. </pre> <p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p> <ul> <li>Sequences that <strong>start</strong> with <strong>ATG</strong>&nbsp;(a common <strong>start codon</strong>)</li> <li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong>&nbsp;(<strong>stop codons</strong>)</li> <li>Sequences containing the motif <strong>ATAT</strong>&nbsp;(a simple repeated pattern)</li> <li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong>&nbsp;(like <strong>GGG</strong>&nbsp;or <strong>GGGG</strong>)</li> </ul> <p>Return <em>the result table ordered by&nbsp;</em><em>sample_id 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>Samples table:</p> <pre class="example-io"> +-----------+------------------+-----------+ | sample_id | dna_sequence | species | +-----------+------------------+-----------+ | 1 | ATGCTAGCTAGCTAA | Human | | 2 | GGGTCAATCATC | Human | | 3 | ATATATCGTAGCTA | Human | | 4 | ATGGGGTCATCATAA | Mouse | | 5 | TCAGTCAGTCAG | Mouse | | 6 | ATATCGCGCTAG | Zebrafish | | 7 | CGTATGCGTCGTA | Zebrafish | +-----------+------------------+-----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+------------------+-------------+-------------+------------+------------+------------+ | sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg | +-----------+------------------+-------------+-------------+------------+------------+------------+ | 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 | | 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 | | 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 | | 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 | | 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 | | 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 | | 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 | +-----------+------------------+-------------+-------------+------------+------------+------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Sample 1 (ATGCTAGCTAGCTAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 2 (GGGTCAATCATC): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 3 (ATATATCGTAGCTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, TAG, or TGA&nbsp;(has_stop = 0)</li> <li>Contains ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 4 (ATGGGGTCATCATAA): <ul> <li>Starts with ATG&nbsp;(has_start = 1)</li> <li>Ends with TAA&nbsp;(has_stop = 1)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Contains GGGG&nbsp;(has_ggg = 1)</li> </ul> </li> <li>Sample 5 (TCAGTCAGTCAG): <ul> <li>Does not match any patterns (all fields = 0)</li> </ul> </li> <li>Sample 6 (ATATCGCGCTAG): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Ends with TAG&nbsp;(has_stop = 1)</li> <li>Starts with ATAT&nbsp;(has_atat = 1)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> <li>Sample 7 (CGTATGCGTCGTA): <ul> <li>Does not start with ATG&nbsp;(has_start = 0)</li> <li>Does not end with TAA, &quot;TAG&quot;, or &quot;TGA&quot; (has_stop = 0)</li> <li>Does not contain ATAT&nbsp;(has_atat = 0)</li> <li>Does not contain at least 3 consecutive &#39;G&#39;s (has_ggg = 0)</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered by sample_id in ascending order</li> <li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT sample_id, dna_sequence, species, dna_sequence LIKE 'ATG%' AS has_start, dna_sequence REGEXP 'TAA$|TAG$|TGA$' AS has_stop, dna_sequence LIKE '%ATAT%' AS has_atat, dna_sequence REGEXP 'GGG+' AS has_ggg FROM Samples ORDER BY 1;
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: long long maxProfit(vector<int>& workers, vector<vector<int>>& tasks) { unordered_map<int, priority_queue<int>> d; for (const auto& t : tasks) { d[t[0]].push(t[1]); } long long ans = 0; for (int skill : workers) { if (d.contains(skill)) { auto& pq = d[skill]; ans += pq.top(); pq.pop(); if (pq.empty()) { d.erase(skill); } } } int mx = 0; for (const auto& [_, pq] : d) { mx = max(mx, pq.top()); } ans += mx; return ans; } };
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func maxProfit(workers []int, tasks [][]int) (ans int64) { d := make(map[int]*hp) for _, t := range tasks { skill, profit := t[0], t[1] if _, ok := d[skill]; !ok { d[skill] = &hp{} } d[skill].push(profit) } for _, skill := range workers { if _, ok := d[skill]; !ok { continue } ans += int64(d[skill].pop()) if d[skill].Len() == 0 { delete(d, skill) } } mx := 0 for _, pq := range d { for pq.Len() > 0 { mx = max(mx, pq.pop()) } } ans += int64(mx) return } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v } func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) }
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public long maxProfit(int[] workers, int[][] tasks) { Map<Integer, PriorityQueue<Integer>> d = new HashMap<>(); for (var t : tasks) { int skill = t[0], profit = t[1]; d.computeIfAbsent(skill, k -> new PriorityQueue<>((a, b) -> b - a)).offer(profit); } long ans = 0; for (int skill : workers) { if (d.containsKey(skill)) { var pq = d.get(skill); ans += pq.poll(); if (pq.isEmpty()) { d.remove(skill); } } } int mx = 0; for (var pq : d.values()) { mx = Math.max(mx, pq.peek()); } ans += mx; return ans; } }
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def maxProfit(self, workers: List[int], tasks: List[List[int]]) -> int: d = defaultdict(SortedList) for skill, profit in tasks: d[skill].add(profit) ans = 0 for skill in workers: if not d[skill]: continue ans += d[skill].pop() mx = 0 for ls in d.values(): if ls: mx = max(mx, ls[-1]) ans += mx return ans
3,476
Maximize Profit from Task Assignment
Medium
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p> <ul> <li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li> <li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li> </ul> <p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task&#39;s skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p> <p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p> <p><strong>Output:</strong> <span class="example-io">1000</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 completes task 0.</li> <li>Worker 1 completes task 1.</li> <li>Worker 2 completes task 3.</li> <li>The additional worker completes task 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= workers.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workers[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>tasks[i].length == 2</code></li> <li><code>1 &lt;= tasks[i][0], tasks[i][1] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
TypeScript
function maxProfit(workers: number[], tasks: number[][]): number { const d = new Map(); for (const [skill, profit] of tasks) { if (!d.has(skill)) { d.set(skill, new MaxPriorityQueue()); } d.get(skill).enqueue(profit); } let ans = 0; for (const skill of workers) { const pq = d.get(skill); if (pq) { ans += pq.dequeue(); if (pq.size() === 0) { d.delete(skill); } } } let mx = 0; for (const pq of d.values()) { mx = Math.max(mx, pq.front()); } ans += mx; return ans; }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
C++
class Solution { public: int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) { int n = fruits.size(); vector<bool> vis(n); int ans = n; for (int x : fruits) { for (int i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; } };
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Go
func numOfUnplacedFruits(fruits []int, baskets []int) int { n := len(fruits) ans := n vis := make([]bool, n) for _, x := range fruits { for i, y := range baskets { if y >= x && !vis[i] { vis[i] = true ans-- break } } } return ans }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Java
class Solution { public int numOfUnplacedFruits(int[] fruits, int[] baskets) { int n = fruits.length; boolean[] vis = new boolean[n]; int ans = n; for (int x : fruits) { for (int i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; } }
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
Python
class Solution: def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int: n = len(fruits) vis = [False] * n ans = n for x in fruits: for i, y in enumerate(baskets): if y >= x and not vis[i]: vis[i] = True ans -= 1 break return ans
3,477
Fruits Into Baskets II
Easy
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 1000</code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set; Simulation
TypeScript
function numOfUnplacedFruits(fruits: number[], baskets: number[]): number { const n = fruits.length; const vis: boolean[] = Array(n).fill(false); let ans = n; for (const x of fruits) { for (let i = 0; i < n; ++i) { if (baskets[i] >= x && !vis[i]) { vis[i] = true; --ans; break; } } } return ans; }
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</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">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: vector<long long> findMaxSum(vector<int>& nums1, vector<int>& nums2, int k) { int n = nums1.size(); vector<pair<int, int>> arr(n); for (int i = 0; i < n; ++i) { arr[i] = {nums1[i], i}; } ranges::sort(arr); priority_queue<int, vector<int>, greater<int>> pq; long long s = 0; int j = 0; vector<long long> ans(n); for (int h = 0; h < n; ++h) { auto [x, i] = arr[h]; while (j < h && arr[j].first < x) { int y = nums2[arr[j].second]; pq.push(y); s += y; if (pq.size() > k) { s -= pq.top(); pq.pop(); } ++j; } ans[i] = s; } return ans; } };
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</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">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Go
func findMaxSum(nums1 []int, nums2 []int, k int) []int64 { n := len(nums1) arr := make([][2]int, n) for i, x := range nums1 { arr[i] = [2]int{x, i} } ans := make([]int64, n) sort.Slice(arr, func(i, j int) bool { return arr[i][0] < arr[j][0] }) pq := hp{} var s int64 j := 0 for h, e := range arr { x, i := e[0], e[1] for j < h && arr[j][0] < x { y := nums2[arr[j][1]] heap.Push(&pq, y) s += int64(y) if pq.Len() > k { s -= int64(heap.Pop(&pq).(int)) } j++ } ans[i] = s } return ans } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v }
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</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">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Java
class Solution { public long[] findMaxSum(int[] nums1, int[] nums2, int k) { int n = nums1.length; int[][] arr = new int[n][0]; for (int i = 0; i < n; ++i) { arr[i] = new int[] {nums1[i], i}; } Arrays.sort(arr, (a, b) -> a[0] - b[0]); PriorityQueue<Integer> pq = new PriorityQueue<>(); long s = 0; long[] ans = new long[n]; int j = 0; for (int h = 0; h < n; ++h) { int x = arr[h][0], i = arr[h][1]; while (j < h && arr[j][0] < x) { int y = nums2[arr[j][1]]; pq.offer(y); s += y; if (pq.size() > k) { s -= pq.poll(); } ++j; } ans[i] = s; } return ans; } }
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</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">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
Python
class Solution: def findMaxSum(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: arr = [(x, i) for i, x in enumerate(nums1)] arr.sort() pq = [] s = j = 0 n = len(arr) ans = [0] * n for h, (x, i) in enumerate(arr): while j < h and arr[j][0] < x: y = nums2[arr[j][1]] heappush(pq, y) s += y if len(pq) > k: s -= heappop(pq) j += 1 ans[i] = s return ans
3,478
Choose K Elements With Maximum Sum
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p> <p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p> <ul> <li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li> <li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li> </ul> <p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</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">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] &lt; nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] &lt; nums1[1]</code>, resulting in 30.</li> <li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] &lt; nums1[2]</code>, resulting in 0.</li> <li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] &lt; nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li> <li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] &lt; nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p> <p><strong>Explanation:</strong></p> <p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] &lt; nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length == nums2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Sorting; Heap (Priority Queue)
TypeScript
function findMaxSum(nums1: number[], nums2: number[], k: number): number[] { const n = nums1.length; const arr = nums1.map((x, i) => [x, i]).sort((a, b) => a[0] - b[0]); const pq = new MinPriorityQueue(); let [s, j] = [0, 0]; const ans: number[] = Array(k).fill(0); for (let h = 0; h < n; ++h) { const [x, i] = arr[h]; while (j < h && arr[j][0] < x) { const y = nums2[arr[j++][1]]; pq.enqueue(y); s += y; if (pq.size() > k) { s -= pq.dequeue(); } } ans[i] = s; } return ans; }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
C++
class SegmentTree { public: vector<int> nums, tr; SegmentTree(vector<int>& nums) { this->nums = nums; int n = nums.size(); tr.resize(n * 4); build(1, 1, n); } void build(int u, int l, int r) { if (l == r) { tr[u] = nums[l - 1]; return; } int mid = (l + r) >> 1; build(u * 2, l, mid); build(u * 2 + 1, mid + 1, r); pushup(u); } void modify(int u, int l, int r, int i, int v) { if (l == r) { tr[u] = v; return; } int mid = (l + r) >> 1; if (i <= mid) { modify(u * 2, l, mid, i, v); } else { modify(u * 2 + 1, mid + 1, r, i, v); } pushup(u); } int query(int u, int l, int r, int v) { if (tr[u] < v) { return -1; } if (l == r) { return l; } int mid = (l + r) >> 1; if (tr[u * 2] >= v) { return query(u * 2, l, mid, v); } return query(u * 2 + 1, mid + 1, r, v); } void pushup(int u) { tr[u] = max(tr[u * 2], tr[u * 2 + 1]); } }; class Solution { public: int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) { SegmentTree tree(baskets); int n = baskets.size(); int ans = 0; for (int x : fruits) { int i = tree.query(1, 1, n, x); if (i < 0) { ans++; } else { tree.modify(1, 1, n, i, 0); } } return ans; } };
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
C#
public class SegmentTree { int[] nums; int[] tr; public SegmentTree(int[] nums) { this.nums = nums; int n = nums.Length; this.tr = new int[n << 2]; Build(1, 1, n); } public void Build(int u, int l, int r) { if (l == r) { tr[u] = nums[l - 1]; return; } int mid = (l + r) >> 1; Build(u << 1, l, mid); Build(u << 1 | 1, mid + 1, r); Pushup(u); } public void Modify(int u, int l, int r, int i, int v) { if (l == r) { tr[u] = v; return; } int mid = (l + r) >> 1; if (i <= mid) { Modify(u << 1, l, mid, i, v); } else { Modify(u << 1 | 1, mid + 1, r, i, v); } Pushup(u); } public int Query(int u, int l, int r, int v) { if (tr[u] < v) { return -1; } if (l == r) { return l; } int mid = (l + r) >> 1; if (tr[u << 1] >= v) { return Query(u << 1, l, mid, v); } return Query(u << 1 | 1, mid + 1, r, v); } public void Pushup(int u) { tr[u] = Math.Max(tr[u << 1], tr[u << 1 | 1]); } } public class Solution { public int NumOfUnplacedFruits(int[] fruits, int[] baskets) { SegmentTree tree = new SegmentTree(baskets); int n = baskets.Length; int ans = 0; foreach (var x in fruits) { int i = tree.Query(1, 1, n, x); if (i < 0) { ans++; } else { tree.Modify(1, 1, n, i, 0); } } return ans; } }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
Go
type SegmentTree struct { nums, tr []int } func NewSegmentTree(nums []int) *SegmentTree { n := len(nums) tree := &SegmentTree{ nums: nums, tr: make([]int, n*4), } tree.build(1, 1, n) return tree } func (st *SegmentTree) build(u, l, r int) { if l == r { st.tr[u] = st.nums[l-1] return } mid := (l + r) >> 1 st.build(u*2, l, mid) st.build(u*2+1, mid+1, r) st.pushup(u) } func (st *SegmentTree) modify(u, l, r, i, v int) { if l == r { st.tr[u] = v return } mid := (l + r) >> 1 if i <= mid { st.modify(u*2, l, mid, i, v) } else { st.modify(u*2+1, mid+1, r, i, v) } st.pushup(u) } func (st *SegmentTree) query(u, l, r, v int) int { if st.tr[u] < v { return -1 } if l == r { return l } mid := (l + r) >> 1 if st.tr[u*2] >= v { return st.query(u*2, l, mid, v) } return st.query(u*2+1, mid+1, r, v) } func (st *SegmentTree) pushup(u int) { st.tr[u] = max(st.tr[u*2], st.tr[u*2+1]) } func numOfUnplacedFruits(fruits []int, baskets []int) (ans int) { tree := NewSegmentTree(baskets) n := len(baskets) for _, x := range fruits { i := tree.query(1, 1, n, x) if i < 0 { ans++ } else { tree.modify(1, 1, n, i, 0) } } return }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
Java
class SegmentTree { int[] nums; int[] tr; public SegmentTree(int[] nums) { this.nums = nums; int n = nums.length; this.tr = new int[n << 2]; build(1, 1, n); } public void build(int u, int l, int r) { if (l == r) { tr[u] = nums[l - 1]; return; } int mid = (l + r) >> 1; build(u << 1, l, mid); build(u << 1 | 1, mid + 1, r); pushup(u); } public void modify(int u, int l, int r, int i, int v) { if (l == r) { tr[u] = v; return; } int mid = (l + r) >> 1; if (i <= mid) { modify(u << 1, l, mid, i, v); } else { modify(u << 1 | 1, mid + 1, r, i, v); } pushup(u); } public int query(int u, int l, int r, int v) { if (tr[u] < v) { return -1; } if (l == r) { return l; } int mid = (l + r) >> 1; if (tr[u << 1] >= v) { return query(u << 1, l, mid, v); } return query(u << 1 | 1, mid + 1, r, v); } public void pushup(int u) { tr[u] = Math.max(tr[u << 1], tr[u << 1 | 1]); } } class Solution { public int numOfUnplacedFruits(int[] fruits, int[] baskets) { SegmentTree tree = new SegmentTree(baskets); int n = baskets.length; int ans = 0; for (int x : fruits) { int i = tree.query(1, 1, n, x); if (i < 0) { ans++; } else { tree.modify(1, 1, n, i, 0); } } return ans; } }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
Python
class SegmentTree: __slots__ = ["nums", "tr"] def __init__(self, nums): self.nums = nums n = len(nums) self.tr = [0] * (n << 2) self.build(1, 1, n) def build(self, u, l, r): if l == r: self.tr[u] = self.nums[l - 1] return mid = (l + r) >> 1 self.build(u << 1, l, mid) self.build(u << 1 | 1, mid + 1, r) self.pushup(u) def modify(self, u, l, r, i, v): if l == r: self.tr[u] = v return mid = (l + r) >> 1 if i <= mid: self.modify(u << 1, l, mid, i, v) else: self.modify(u << 1 | 1, mid + 1, r, i, v) self.pushup(u) def query(self, u, l, r, v): if self.tr[u] < v: return -1 if l == r: return l mid = (l + r) >> 1 if self.tr[u << 1] >= v: return self.query(u << 1, l, mid, v) return self.query(u << 1 | 1, mid + 1, r, v) def pushup(self, u): self.tr[u] = max(self.tr[u << 1], self.tr[u << 1 | 1]) class Solution: def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int: tree = SegmentTree(baskets) n = len(baskets) ans = 0 for x in fruits: i = tree.query(1, 1, n, x) if i < 0: ans += 1 else: tree.modify(1, 1, n, i, 0) return ans
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
Rust
struct SegmentTree<'a> { nums: &'a [i32], tr: Vec<i32>, } impl<'a> SegmentTree<'a> { fn new(nums: &'a [i32]) -> Self { let n = nums.len(); let mut tree = SegmentTree { nums, tr: vec![0; n * 4], }; tree.build(1, 1, n); tree } fn build(&mut self, u: usize, l: usize, r: usize) { if l == r { self.tr[u] = self.nums[l - 1]; return; } let mid = (l + r) >> 1; self.build(u * 2, l, mid); self.build(u * 2 + 1, mid + 1, r); self.pushup(u); } fn modify(&mut self, u: usize, l: usize, r: usize, i: usize, v: i32) { if l == r { self.tr[u] = v; return; } let mid = (l + r) >> 1; if i <= mid { self.modify(u * 2, l, mid, i, v); } else { self.modify(u * 2 + 1, mid + 1, r, i, v); } self.pushup(u); } fn query(&self, u: usize, l: usize, r: usize, v: i32) -> i32 { if self.tr[u] < v { return -1; } if l == r { return l as i32; } let mid = (l + r) >> 1; if self.tr[u * 2] >= v { return self.query(u * 2, l, mid, v); } self.query(u * 2 + 1, mid + 1, r, v) } fn pushup(&mut self, u: usize) { self.tr[u] = self.tr[u * 2].max(self.tr[u * 2 + 1]); } } impl Solution { pub fn num_of_unplaced_fruits(fruits: Vec<i32>, baskets: Vec<i32>) -> i32 { let mut tree = SegmentTree::new(&baskets); let n = baskets.len(); let mut ans = 0; for &x in fruits.iter() { let i = tree.query(1, 1, n, x); if i < 0 { ans += 1; } else { tree.modify(1, 1, n, i as usize, 0); } } ans } }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
Swift
class SegmentTree { var nums: [Int] var tr: [Int] init(_ nums: [Int]) { self.nums = nums let n = nums.count self.tr = [Int](repeating: 0, count: n << 2) build(1, 1, n) } func build(_ u: Int, _ l: Int, _ r: Int) { if l == r { tr[u] = nums[l - 1] return } let mid = (l + r) >> 1 build(u << 1, l, mid) build(u << 1 | 1, mid + 1, r) pushup(u) } func modify(_ u: Int, _ l: Int, _ r: Int, _ i: Int, _ v: Int) { if l == r { tr[u] = v return } let mid = (l + r) >> 1 if i <= mid { modify(u << 1, l, mid, i, v) } else { modify(u << 1 | 1, mid + 1, r, i, v) } pushup(u) } func query(_ u: Int, _ l: Int, _ r: Int, _ v: Int) -> Int { if tr[u] < v { return -1 } if l == r { return l } let mid = (l + r) >> 1 if tr[u << 1] >= v { return query(u << 1, l, mid, v) } return query(u << 1 | 1, mid + 1, r, v) } func pushup(_ u: Int) { tr[u] = max(tr[u << 1], tr[u << 1 | 1]) } } class Solution { func numOfUnplacedFruits(_ fruits: [Int], _ baskets: [Int]) -> Int { let tree = SegmentTree(baskets) let n = baskets.count var ans = 0 for x in fruits { let i = tree.query(1, 1, n, x) if i < 0 { ans += 1 } else { tree.modify(1, 1, n, i, 0) } } return ans } }
3,479
Fruits Into Baskets III
Medium
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p> <p>From left to right, place the fruits according to these rules:</p> <ul> <li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li> <li>Each basket can hold <b>only one</b> type of fruit.</li> <li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li> </ul> <p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li> <li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li> <li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li> </ul> <p>Since one fruit type remains unplaced, we return 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li> <li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li> <li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li> </ul> <p>Since all fruits are successfully placed, we return 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == fruits.length == baskets.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= fruits[i], baskets[i] &lt;= 10<sup>9</sup></code></li> </ul>
Segment Tree; Array; Binary Search; Ordered Set
TypeScript
class SegmentTree { nums: number[]; tr: number[]; constructor(nums: number[]) { this.nums = nums; const n = nums.length; this.tr = Array(n * 4).fill(0); this.build(1, 1, n); } build(u: number, l: number, r: number): void { if (l === r) { this.tr[u] = this.nums[l - 1]; return; } const mid = (l + r) >> 1; this.build(u * 2, l, mid); this.build(u * 2 + 1, mid + 1, r); this.pushup(u); } modify(u: number, l: number, r: number, i: number, v: number): void { if (l === r) { this.tr[u] = v; return; } const mid = (l + r) >> 1; if (i <= mid) { this.modify(u * 2, l, mid, i, v); } else { this.modify(u * 2 + 1, mid + 1, r, i, v); } this.pushup(u); } query(u: number, l: number, r: number, v: number): number { if (this.tr[u] < v) { return -1; } if (l === r) { return l; } const mid = (l + r) >> 1; if (this.tr[u * 2] >= v) { return this.query(u * 2, l, mid, v); } return this.query(u * 2 + 1, mid + 1, r, v); } pushup(u: number): void { this.tr[u] = Math.max(this.tr[u * 2], this.tr[u * 2 + 1]); } } function numOfUnplacedFruits(fruits: number[], baskets: number[]): number { const tree = new SegmentTree(baskets); const n = baskets.length; let ans = 0; for (const x of fruits) { const i = tree.query(1, 1, n, x); if (i < 0) { ans++; } else { tree.modify(1, 1, n, i, 0); } } return ans; }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
C++
class Solution { public: long long maxSubarrays(int n, vector<vector<int>>& conflictingPairs) { vector<vector<int>> g(n + 1); for (auto& pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { swap(a, b); } g[a].push_back(b); } vector<long long> cnt(n + 2, 0); long long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = max(add, cnt[b1]); } ans += add; return ans; } };
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Go
func maxSubarrays(n int, conflictingPairs [][]int) (ans int64) { g := make([][]int, n+1) for _, pair := range conflictingPairs { a, b := pair[0], pair[1] if a > b { a, b = b, a } g[a] = append(g[a], b) } cnt := make([]int64, n+2) var add int64 b1, b2 := n+1, n+1 for a := n; a > 0; a-- { for _, b := range g[a] { if b < b1 { b2 = b1 b1 = b } else if b < b2 { b2 = b } } ans += int64(b1 - a) cnt[b1] += int64(b2 - b1) if cnt[b1] > add { add = cnt[b1] } } ans += add return ans }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Java
class Solution { public long maxSubarrays(int n, int[][] conflictingPairs) { List<Integer>[] g = new List[n + 1]; Arrays.setAll(g, k -> new ArrayList<>()); for (int[] pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { int c = a; a = b; b = c; } g[a].add(b); } long[] cnt = new long[n + 2]; long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Python
class Solution: def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int: g = [[] for _ in range(n + 1)] for a, b in conflictingPairs: if a > b: a, b = b, a g[a].append(b) cnt = [0] * (n + 2) ans = add = 0 b1 = b2 = n + 1 for a in range(n, 0, -1): for b in g[a]: if b < b1: b2, b1 = b1, b elif b < b2: b2 = b ans += b1 - a cnt[b1] += b2 - b1 add = max(add, cnt[b1]) ans += add return ans
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Rust
impl Solution { pub fn max_subarrays(n: i32, conflicting_pairs: Vec<Vec<i32>>) -> i64 { let mut g: Vec<Vec<i32>> = vec![vec![]; (n + 1) as usize]; for pair in conflicting_pairs { let mut a = pair[0]; let mut b = pair[1]; if a > b { std::mem::swap(&mut a, &mut b); } g[a as usize].push(b); } let mut cnt: Vec<i64> = vec![0; (n + 2) as usize]; let mut ans = 0i64; let mut add = 0i64; let mut b1 = n + 1; let mut b2 = n + 1; for a in (1..=n).rev() { for &b in &g[a as usize] { if b < b1 { b2 = b1; b1 = b; } else if b < b2 { b2 = b; } } ans += (b1 - a) as i64; cnt[b1 as usize] += (b2 - b1) as i64; add = std::cmp::max(add, cnt[b1 as usize]); } ans += add; ans } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</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 = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
TypeScript
function maxSubarrays(n: number, conflictingPairs: number[][]): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); for (let [a, b] of conflictingPairs) { if (a > b) { [a, b] = [b, a]; } g[a].push(b); } const cnt: number[] = Array(n + 2).fill(0); let ans = 0, add = 0; let b1 = n + 1, b2 = n + 1; for (let a = n; a > 0; a--) { for (const b of g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
C++
class Solution { public: string applySubstitutions(vector<vector<string>>& replacements, string text) { unordered_map<string, string> d; for (const auto& e : replacements) { d[e[0]] = e[1]; } auto dfs = [&](this auto&& dfs, const string& s) -> string { size_t i = s.find('%'); if (i == string::npos) { return s; } size_t j = s.find('%', i + 1); if (j == string::npos) { return s; } string key = s.substr(i + 1, j - i - 1); string replacement = dfs(d[key]); return s.substr(0, i) + replacement + dfs(s.substr(j + 1)); }; return dfs(text); } };
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Go
func applySubstitutions(replacements [][]string, text string) string { d := make(map[string]string) for _, e := range replacements { d[e[0]] = e[1] } var dfs func(string) string dfs = func(s string) string { i := strings.Index(s, "%") if i == -1 { return s } j := strings.Index(s[i+1:], "%") if j == -1 { return s } j += i + 1 key := s[i+1 : j] replacement := dfs(d[key]) return s[:i] + replacement + dfs(s[j+1:]) } return dfs(text) }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Java
class Solution { private final Map<String, String> d = new HashMap<>(); public String applySubstitutions(List<List<String>> replacements, String text) { for (List<String> e : replacements) { d.put(e.get(0), e.get(1)); } return dfs(text); } private String dfs(String s) { int i = s.indexOf("%"); if (i == -1) { return s; } int j = s.indexOf("%", i + 1); if (j == -1) { return s; } String key = s.substring(i + 1, j); String replacement = dfs(d.getOrDefault(key, "")); return s.substring(0, i) + replacement + dfs(s.substring(j + 1)); } }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Python
class Solution: def applySubstitutions(self, replacements: List[List[str]], text: str) -> str: def dfs(s: str) -> str: i = s.find("%") if i == -1: return s j = s.find("%", i + 1) if j == -1: return s key = s[i + 1 : j] replacement = dfs(d[key]) return s[:i] + replacement + dfs(s[j + 1 :]) d = {s: t for s, t in replacements} return dfs(text)
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
TypeScript
function applySubstitutions(replacements: string[][], text: string): string { const d: Record<string, string> = {}; for (const [key, value] of replacements) { d[key] = value; } const dfs = (s: string): string => { const i = s.indexOf('%'); if (i === -1) { return s; } const j = s.indexOf('%', i + 1); if (j === -1) { return s; } const key = s.slice(i + 1, j); const replacement = dfs(d[key] ?? ''); return s.slice(0, i) + replacement + dfs(s.slice(j + 1)); }; return dfs(text); }
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
Python
import pandas as pd def analyze_organization_hierarchy(employees: pd.DataFrame) -> pd.DataFrame: # Copy the input DataFrame to avoid modifying the original employees = employees.copy() employees["level"] = None # Identify the CEO (level 1) ceo_id = employees.loc[employees["manager_id"].isna(), "employee_id"].values[0] employees.loc[employees["employee_id"] == ceo_id, "level"] = 1 # Recursively compute employee levels def compute_levels(emp_df, level): next_level_ids = emp_df[emp_df["level"] == level]["employee_id"].tolist() if not next_level_ids: return emp_df.loc[emp_df["manager_id"].isin(next_level_ids), "level"] = level + 1 compute_levels(emp_df, level + 1) compute_levels(employees, 1) # Initialize team size and budget dictionaries team_size = {eid: 0 for eid in employees["employee_id"]} budget = { eid: salary for eid, salary in zip(employees["employee_id"], employees["salary"]) } # Compute team size and budget for each employee for eid in sorted(employees["employee_id"], reverse=True): manager_id = employees.loc[ employees["employee_id"] == eid, "manager_id" ].values[0] if pd.notna(manager_id): team_size[manager_id] += team_size[eid] + 1 budget[manager_id] += budget[eid] # Map computed team size and budget to employees DataFrame employees["team_size"] = employees["employee_id"].map(team_size) employees["budget"] = employees["employee_id"].map(budget) # Sort the final result by level (ascending), budget (descending), and employee name (ascending) employees = employees.sort_values( by=["level", "budget", "employee_name"], ascending=[True, False, True] ) return employees[["employee_id", "employee_name", "level", "team_size", "budget"]]
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below WITH RECURSIVE level_cte AS ( SELECT employee_id, manager_id, 1 AS level, salary FROM Employees UNION ALL SELECT a.employee_id, b.manager_id, level + 1, a.salary FROM level_cte a JOIN Employees b ON b.employee_id = a.manager_id ), employee_with_level AS ( SELECT a.employee_id, a.employee_name, a.salary, b.level FROM Employees a, (SELECT employee_id, level FROM level_cte WHERE manager_id IS NULL) b WHERE a.employee_id = b.employee_id ) SELECT a.employee_id, a.employee_name, a.level, COALESCE(b.team_size, 0) AS team_size, a.salary + COALESCE(b.budget, 0) AS budget FROM employee_with_level a LEFT JOIN ( SELECT manager_id AS employee_id, COUNT(*) AS team_size, SUM(salary) AS budget FROM level_cte WHERE manager_id IS NOT NULL GROUP BY manager_id ) b ON a.employee_id = b.employee_id ORDER BY level, budget DESC, employee_name;
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
C++
class Solution { public: int totalNumbers(vector<int>& digits) { unordered_set<int> s; int n = digits.size(); for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.insert(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } };
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Go
func totalNumbers(digits []int) int { s := make(map[int]struct{}) for i, a := range digits { if a%2 == 1 { continue } for j, b := range digits { if i == j { continue } for k, c := range digits { if c == 0 || k == i || k == j { continue } s[c*100+b*10+a] = struct{}{} } } } return len(s) }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Java
class Solution { public int totalNumbers(int[] digits) { Set<Integer> s = new HashSet<>(); int n = digits.length; for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Python
class Solution: def totalNumbers(self, digits: List[int]) -> int: s = set() for i, a in enumerate(digits): if a & 1: continue for j, b in enumerate(digits): if i == j: continue for k, c in enumerate(digits): if c == 0 or k in (i, j): continue s.add(c * 100 + b * 10 + a) return len(s)
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
TypeScript
function totalNumbers(digits: number[]): number { const s = new Set<number>(); const n = digits.length; for (let i = 0; i < n; ++i) { if (digits[i] % 2 === 1) { continue; } for (let j = 0; j < n; ++j) { if (i === j) { continue; } for (let k = 0; k < n; ++k) { if (digits[k] === 0 || k === i || k === j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size; }
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
C++
class Spreadsheet { private: unordered_map<string, int> d; public: Spreadsheet(int rows) {} void setCell(string cell, int value) { d[cell] = value; } void resetCell(string cell) { d.erase(cell); } int getValue(string formula) { int ans = 0; stringstream ss(formula.substr(1)); string cell; while (getline(ss, cell, '+')) { if (isdigit(cell[0])) { ans += stoi(cell); } else { ans += d.count(cell) ? d[cell] : 0; } } return ans; } }; /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet* obj = new Spreadsheet(rows); * obj->setCell(cell,value); * obj->resetCell(cell); * int param_3 = obj->getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Go
type Spreadsheet struct { d map[string]int } func Constructor(rows int) Spreadsheet { return Spreadsheet{d: make(map[string]int)} } func (this *Spreadsheet) SetCell(cell string, value int) { this.d[cell] = value } func (this *Spreadsheet) ResetCell(cell string) { delete(this.d, cell) } func (this *Spreadsheet) GetValue(formula string) int { ans := 0 cells := strings.Split(formula[1:], "+") for _, cell := range cells { if val, err := strconv.Atoi(cell); err == nil { ans += val } else { ans += this.d[cell] } } return ans } /** * Your Spreadsheet object will be instantiated and called as such: * obj := Constructor(rows); * obj.SetCell(cell,value); * obj.ResetCell(cell); * param_3 := obj.GetValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Java
class Spreadsheet { private Map<String, Integer> d = new HashMap<>(); public Spreadsheet(int rows) { } public void setCell(String cell, int value) { d.put(cell, value); } public void resetCell(String cell) { d.remove(cell); } public int getValue(String formula) { int ans = 0; for (String cell : formula.substring(1).split("\\+")) { ans += Character.isDigit(cell.charAt(0)) ? Integer.parseInt(cell) : d.getOrDefault(cell, 0); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet obj = new Spreadsheet(rows); * obj.setCell(cell,value); * obj.resetCell(cell); * int param_3 = obj.getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Python
class Spreadsheet: def __init__(self, rows: int): self.d = {} def setCell(self, cell: str, value: int) -> None: self.d[cell] = value def resetCell(self, cell: str) -> None: self.d.pop(cell, None) def getValue(self, formula: str) -> int: ans = 0 for cell in formula[1:].split("+"): ans += int(cell) if cell[0].isdigit() else self.d.get(cell, 0) return ans # Your Spreadsheet object will be instantiated and called as such: # obj = Spreadsheet(rows) # obj.setCell(cell,value) # obj.resetCell(cell) # param_3 = obj.getValue(formula)
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
TypeScript
class Spreadsheet { private d: Map<string, number>; constructor(rows: number) { this.d = new Map<string, number>(); } setCell(cell: string, value: number): void { this.d.set(cell, value); } resetCell(cell: string): void { this.d.delete(cell); } getValue(formula: string): number { let ans = 0; const cells = formula.slice(1).split('+'); for (const cell of cells) { ans += isNaN(Number(cell)) ? this.d.get(cell) || 0 : Number(cell); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * var obj = new Spreadsheet(rows) * obj.setCell(cell,value) * obj.resetCell(cell) * var param_3 = obj.getValue(formula) */