id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,344
Maximum Sized Array
Medium
<p>Given a positive integer <code>s</code>, let <code>A</code> be a 3D array of dimensions<!-- notionvc: f8069282-c5f5-4da1-91b8-fa0c1c168ea1 --> <code>n &times; n &times; n</code>, where each element <code>A[i][j][k]</code> is defined as:</p> <ul> <li><code>A[i][j][k] = i * (j OR k)</code>, where <code>0 &lt;= i, j, k &lt; n</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible value of <code>n</code> such that the <strong>sum</strong> of all elements in array <code>A</code> does not exceed <code>s</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 = 10</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 2</code><strong>:</strong> <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> <li><code>A[0][0][1] = 0 * (0 OR 1) = 0</code></li> <li><code>A[0][1][0] = 0 * (1 OR 0) = 0</code></li> <li><code>A[0][1][1] = 0 * (1 OR 1) = 0</code></li> <li><code>A[1][0][0] = 1 * (0 OR 0) = 0</code></li> <li><code>A[1][0][1] = 1 * (0 OR 1) = 1</code></li> <li><code>A[1][1][0] = 1 * (1 OR 0) = 1</code></li> <li><code>A[1][1][1] = 1 * (1 OR 1) = 1</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 3, which does not exceed 10, so the maximum possible value of <code>n</code> is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 1</code>: <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 0, which does not exceed 0, so the maximum possible value of <code>n</code> is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s &lt;= 10<sup>15</sup></code></li> </ul>
Bit Manipulation; Binary Search
Java
class Solution { private static final int MX = 1330; private static final long[] f = new long[MX]; static { for (int i = 1; i < MX; ++i) { f[i] = f[i - 1] + i; for (int j = 0; j < i; ++j) { f[i] += 2 * (i | j); } } } public int maxSizedArray(long s) { int l = 1, r = MX; while (l < r) { int m = (l + r + 1) >> 1; if (f[m - 1] * (m - 1) * m / 2 <= s) { l = m; } else { r = m - 1; } } return l; } }
3,344
Maximum Sized Array
Medium
<p>Given a positive integer <code>s</code>, let <code>A</code> be a 3D array of dimensions<!-- notionvc: f8069282-c5f5-4da1-91b8-fa0c1c168ea1 --> <code>n &times; n &times; n</code>, where each element <code>A[i][j][k]</code> is defined as:</p> <ul> <li><code>A[i][j][k] = i * (j OR k)</code>, where <code>0 &lt;= i, j, k &lt; n</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible value of <code>n</code> such that the <strong>sum</strong> of all elements in array <code>A</code> does not exceed <code>s</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 = 10</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 2</code><strong>:</strong> <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> <li><code>A[0][0][1] = 0 * (0 OR 1) = 0</code></li> <li><code>A[0][1][0] = 0 * (1 OR 0) = 0</code></li> <li><code>A[0][1][1] = 0 * (1 OR 1) = 0</code></li> <li><code>A[1][0][0] = 1 * (0 OR 0) = 0</code></li> <li><code>A[1][0][1] = 1 * (0 OR 1) = 1</code></li> <li><code>A[1][1][0] = 1 * (1 OR 0) = 1</code></li> <li><code>A[1][1][1] = 1 * (1 OR 1) = 1</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 3, which does not exceed 10, so the maximum possible value of <code>n</code> is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 1</code>: <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 0, which does not exceed 0, so the maximum possible value of <code>n</code> is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s &lt;= 10<sup>15</sup></code></li> </ul>
Bit Manipulation; Binary Search
Python
mx = 1330 f = [0] * mx for i in range(1, mx): f[i] = f[i - 1] + i for j in range(i): f[i] += 2 * (i | j) class Solution: def maxSizedArray(self, s: int) -> int: l, r = 1, mx while l < r: m = (l + r + 1) >> 1 if f[m - 1] * (m - 1) * m // 2 <= s: l = m else: r = m - 1 return l
3,344
Maximum Sized Array
Medium
<p>Given a positive integer <code>s</code>, let <code>A</code> be a 3D array of dimensions<!-- notionvc: f8069282-c5f5-4da1-91b8-fa0c1c168ea1 --> <code>n &times; n &times; n</code>, where each element <code>A[i][j][k]</code> is defined as:</p> <ul> <li><code>A[i][j][k] = i * (j OR k)</code>, where <code>0 &lt;= i, j, k &lt; n</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible value of <code>n</code> such that the <strong>sum</strong> of all elements in array <code>A</code> does not exceed <code>s</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 = 10</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 2</code><strong>:</strong> <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> <li><code>A[0][0][1] = 0 * (0 OR 1) = 0</code></li> <li><code>A[0][1][0] = 0 * (1 OR 0) = 0</code></li> <li><code>A[0][1][1] = 0 * (1 OR 1) = 0</code></li> <li><code>A[1][0][0] = 1 * (0 OR 0) = 0</code></li> <li><code>A[1][0][1] = 1 * (0 OR 1) = 1</code></li> <li><code>A[1][1][0] = 1 * (1 OR 0) = 1</code></li> <li><code>A[1][1][1] = 1 * (1 OR 1) = 1</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 3, which does not exceed 10, so the maximum possible value of <code>n</code> is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Elements of the array <code>A</code> for <code>n = 1</code>: <ul> <li><code>A[0][0][0] = 0 * (0 OR 0) = 0</code></li> </ul> </li> <li>The total sum of the elements in array <code>A</code> is 0, which does not exceed 0, so the maximum possible value of <code>n</code> is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s &lt;= 10<sup>15</sup></code></li> </ul>
Bit Manipulation; Binary Search
TypeScript
const MX = 1330; const f: bigint[] = Array(MX).fill(0n); (() => { f[0] = 0n; for (let i = 1; i < MX; i++) { f[i] = f[i - 1] + BigInt(i); for (let j = 0; j < i; j++) { f[i] += BigInt(2) * BigInt(i | j); } } })(); function maxSizedArray(s: number): number { let l = 1, r = MX; const target = BigInt(s); while (l < r) { const m = (l + r + 1) >> 1; if ((f[m - 1] * BigInt(m - 1) * BigInt(m)) / BigInt(2) <= target) { l = m; } else { r = m - 1; } } return l; }
3,345
Smallest Divisible Digit Product I
Easy
<p>You are given two integers <code>n</code> and <code>t</code>. Return the <strong>smallest</strong> number greater than or equal to <code>n</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 10, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 15, t = 3</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= t &lt;= 10</code></li> </ul>
Math; Enumeration
C++
class Solution { public: int smallestNumber(int n, int t) { for (int i = n;; ++i) { int p = 1; for (int x = i; x > 0; x /= 10) { p *= (x % 10); } if (p % t == 0) { return i; } } } };
3,345
Smallest Divisible Digit Product I
Easy
<p>You are given two integers <code>n</code> and <code>t</code>. Return the <strong>smallest</strong> number greater than or equal to <code>n</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 10, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 15, t = 3</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= t &lt;= 10</code></li> </ul>
Math; Enumeration
Go
func smallestNumber(n int, t int) int { for i := n; ; i++ { p := 1 for x := i; x > 0; x /= 10 { p *= x % 10 } if p%t == 0 { return i } } }
3,345
Smallest Divisible Digit Product I
Easy
<p>You are given two integers <code>n</code> and <code>t</code>. Return the <strong>smallest</strong> number greater than or equal to <code>n</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 10, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 15, t = 3</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= t &lt;= 10</code></li> </ul>
Math; Enumeration
Java
class Solution { public int smallestNumber(int n, int t) { for (int i = n;; ++i) { int p = 1; for (int x = i; x > 0; x /= 10) { p *= (x % 10); } if (p % t == 0) { return i; } } } }
3,345
Smallest Divisible Digit Product I
Easy
<p>You are given two integers <code>n</code> and <code>t</code>. Return the <strong>smallest</strong> number greater than or equal to <code>n</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 10, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 15, t = 3</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= t &lt;= 10</code></li> </ul>
Math; Enumeration
Python
class Solution: def smallestNumber(self, n: int, t: int) -> int: for i in count(n): p = 1 x = i while x: p *= x % 10 x //= 10 if p % t == 0: return i
3,345
Smallest Divisible Digit Product I
Easy
<p>You are given two integers <code>n</code> and <code>t</code>. Return the <strong>smallest</strong> number greater than or equal to <code>n</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 10, t = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 15, t = 3</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= t &lt;= 10</code></li> </ul>
Math; Enumeration
TypeScript
function smallestNumber(n: number, t: number): number { for (let i = n; ; ++i) { let p = 1; for (let x = i; x; x = Math.floor(x / 10)) { p *= x % 10; } if (p % t === 0) { return i; } } }
3,346
Maximum Frequency of an Element After Performing Operations I
Medium
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>. <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>. <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
C++
class Solution { public: int maxFrequency(vector<int>& nums, int k, int numOperations) { unordered_map<int, int> cnt; map<int, int> d; for (int x : nums) { cnt[x]++; d[x]; d[x - k]++; d[x + k + 1]--; } int ans = 0, s = 0; for (const auto& [x, t] : d) { s += t; ans = max(ans, min(s, cnt[x] + numOperations)); } return ans; } };
3,346
Maximum Frequency of an Element After Performing Operations I
Medium
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>. <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>. <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Go
func maxFrequency(nums []int, k int, numOperations int) (ans int) { cnt := make(map[int]int) d := make(map[int]int) for _, x := range nums { cnt[x]++ d[x] = d[x] d[x-k]++ d[x+k+1]-- } s := 0 keys := make([]int, 0, len(d)) for key := range d { keys = append(keys, key) } sort.Ints(keys) for _, x := range keys { s += d[x] ans = max(ans, min(s, cnt[x]+numOperations)) } return }
3,346
Maximum Frequency of an Element After Performing Operations I
Medium
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>. <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>. <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Java
class Solution { public int maxFrequency(int[] nums, int k, int numOperations) { Map<Integer, Integer> cnt = new HashMap<>(); TreeMap<Integer, Integer> d = new TreeMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); d.putIfAbsent(x, 0); d.merge(x - k, 1, Integer::sum); d.merge(x + k + 1, -1, Integer::sum); } int ans = 0, s = 0; for (var e : d.entrySet()) { int x = e.getKey(), t = e.getValue(); s += t; ans = Math.max(ans, Math.min(s, cnt.getOrDefault(x, 0) + numOperations)); } return ans; } }
3,346
Maximum Frequency of an Element After Performing Operations I
Medium
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>. <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>. <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Python
class Solution: def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int: cnt = defaultdict(int) d = defaultdict(int) for x in nums: cnt[x] += 1 d[x] += 0 d[x - k] += 1 d[x + k + 1] -= 1 ans = s = 0 for x, t in sorted(d.items()): s += t ans = max(ans, min(s, cnt[x] + numOperations)) return ans
3,346
Maximum Frequency of an Element After Performing Operations I
Medium
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>. <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>. <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
TypeScript
function maxFrequency(nums: number[], k: number, numOperations: number): number { const cnt: Record<number, number> = {}; const d: Record<number, number> = {}; for (const x of nums) { cnt[x] = (cnt[x] || 0) + 1; d[x] = d[x] || 0; d[x - k] = (d[x - k] || 0) + 1; d[x + k + 1] = (d[x + k + 1] || 0) - 1; } let [ans, s] = [0, 0]; const keys = Object.keys(d) .map(Number) .sort((a, b) => a - b); for (const x of keys) { s += d[x]; ans = Math.max(ans, Math.min(s, (cnt[x] || 0) + numOperations)); } return ans; }
3,347
Maximum Frequency of an Element After Performing Operations II
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>, after which <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>, after which <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
C++
class Solution { public: int maxFrequency(vector<int>& nums, int k, int numOperations) { unordered_map<int, int> cnt; map<int, int> d; for (int x : nums) { cnt[x]++; d[x]; d[x - k]++; d[x + k + 1]--; } int ans = 0, s = 0; for (const auto& [x, t] : d) { s += t; ans = max(ans, min(s, cnt[x] + numOperations)); } return ans; } };
3,347
Maximum Frequency of an Element After Performing Operations II
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>, after which <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>, after which <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Go
func maxFrequency(nums []int, k int, numOperations int) (ans int) { cnt := make(map[int]int) d := make(map[int]int) for _, x := range nums { cnt[x]++ d[x] = d[x] d[x-k]++ d[x+k+1]-- } s := 0 keys := make([]int, 0, len(d)) for key := range d { keys = append(keys, key) } sort.Ints(keys) for _, x := range keys { s += d[x] ans = max(ans, min(s, cnt[x]+numOperations)) } return }
3,347
Maximum Frequency of an Element After Performing Operations II
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>, after which <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>, after which <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Java
class Solution { public int maxFrequency(int[] nums, int k, int numOperations) { Map<Integer, Integer> cnt = new HashMap<>(); TreeMap<Integer, Integer> d = new TreeMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); d.putIfAbsent(x, 0); d.merge(x - k, 1, Integer::sum); d.merge(x + k + 1, -1, Integer::sum); } int ans = 0, s = 0; for (var e : d.entrySet()) { int x = e.getKey(), t = e.getValue(); s += t; ans = Math.max(ans, Math.min(s, cnt.getOrDefault(x, 0) + numOperations)); } return ans; } }
3,347
Maximum Frequency of an Element After Performing Operations II
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>, after which <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>, after which <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Python
class Solution: def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int: cnt = defaultdict(int) d = defaultdict(int) for x in nums: cnt[x] += 1 d[x] += 0 d[x - k] += 1 d[x + k + 1] -= 1 ans = s = 0 for x, t in sorted(d.items()): s += t ans = max(ans, min(s, cnt[x] + numOperations)) return ans
3,347
Maximum Frequency of an Element After Performing Operations II
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>k</code> and <code>numOperations</code>.</p> <p>You must perform an <strong>operation</strong> <code>numOperations</code> times on <code>nums</code>, where in each operation you:</p> <ul> <li>Select an index <code>i</code> that was <strong>not</strong> selected in any previous operations.</li> <li>Add an integer in the range <code>[-k, k]</code> to <code>nums[i]</code>.</li> </ul> <p>Return the <strong>maximum</strong> possible <span data-keyword="frequency-array">frequency</span> of any element in <code>nums</code> after performing the <strong>operations</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">nums = [1,4,5], k = 1, numOperations = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>, after which <code>nums</code> becomes <code>[1, 4, 5]</code>.</li> <li>Adding -1 to <code>nums[2]</code>, after which <code>nums</code> becomes <code>[1, 4, 4]</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 = [5,11,20,20], k = 5, numOperations = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can achieve a maximum frequency of two by:</p> <ul> <li>Adding 0 to <code>nums[1]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= numOperations &lt;= nums.length</code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
TypeScript
function maxFrequency(nums: number[], k: number, numOperations: number): number { const cnt: Record<number, number> = {}; const d: Record<number, number> = {}; for (const x of nums) { cnt[x] = (cnt[x] || 0) + 1; d[x] = d[x] || 0; d[x - k] = (d[x - k] || 0) + 1; d[x + k + 1] = (d[x + k + 1] || 0) - 1; } let [ans, s] = [0, 0]; const keys = Object.keys(d) .map(Number) .sort((a, b) => a - b); for (const x of keys) { s += d[x]; ans = Math.max(ans, Math.min(s, (cnt[x] || 0) + numOperations)); } return ans; }
3,348
Smallest Divisible Digit Product II
Hard
<p>You are given a string <code>num</code> which represents a <strong>positive</strong> integer, and an integer <code>t</code>.</p> <p>A number is called <strong>zero-free</strong> if <em>none</em> of its digits are 0.</p> <p>Return a string representing the <strong>smallest</strong> <strong>zero-free</strong> number greater than or equal to <code>num</code> such that the <strong>product of its digits</strong> is divisible by <code>t</code>. If no such number exists, return <code>&quot;-1&quot;</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">num = &quot;1234&quot;, t = 256</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1488&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The smallest zero-free number that is greater than 1234 and has the product of its digits divisible by 256 is 1488, with the product of its digits equal to 256.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = &quot;12355&quot;, t = 50</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;12355&quot;</span></p> <p><strong>Explanation:</strong></p> <p>12355 is already zero-free and has the product of its digits divisible by 50, with the product of its digits equal to 150.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = &quot;11111&quot;, t = 26</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>No number greater than 11111 has the product of its digits divisible by 26.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= num.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>num</code> consists only of digits in the range <code>[&#39;0&#39;, &#39;9&#39;]</code>.</li> <li><code>num</code> does not contain leading zeros.</li> <li><code>1 &lt;= t &lt;= 10<sup>14</sup></code></li> </ul>
Greedy; Math; String; Backtracking; Number Theory
Go
func smallestNumber(num string, t int64) string { primeCount, isDivisible := getPrimeCount(t) if !isDivisible { return "-1" } factorCount := getFactorCount(primeCount) if sumValues(factorCount) > len(num) { return construct(factorCount) } primeCountPrefix := getPrimeCountFromString(num) firstZeroIndex := strings.Index(num, "0") if firstZeroIndex == -1 { firstZeroIndex = len(num) if isSubset(primeCount, primeCountPrefix) { return num } } for i := len(num) - 1; i >= 0; i-- { d := int(num[i] - '0') primeCountPrefix = subtract(primeCountPrefix, kFactorCounts[d]) spaceAfterThisDigit := len(num) - 1 - i if i > firstZeroIndex { continue } for biggerDigit := d + 1; biggerDigit < 10; biggerDigit++ { factorsAfterReplacement := getFactorCount( subtract(subtract(primeCount, primeCountPrefix), kFactorCounts[biggerDigit]), ) if sumValues(factorsAfterReplacement) <= spaceAfterThisDigit { fillOnes := spaceAfterThisDigit - sumValues(factorsAfterReplacement) return num[:i] + strconv.Itoa(biggerDigit) + strings.Repeat("1", fillOnes) + construct(factorsAfterReplacement) } } } factorsAfterExtension := getFactorCount(primeCount) return strings.Repeat("1", len(num)+1-sumValues(factorsAfterExtension)) + construct(factorsAfterExtension) } var kFactorCounts = map[int]map[int]int{ 0: {}, 1: {}, 2: {2: 1}, 3: {3: 1}, 4: {2: 2}, 5: {5: 1}, 6: {2: 1, 3: 1}, 7: {7: 1}, 8: {2: 3}, 9: {3: 2}, } func getPrimeCount(t int64) (map[int]int, bool) { count := map[int]int{2: 0, 3: 0, 5: 0, 7: 0} for _, prime := range []int{2, 3, 5, 7} { for t%int64(prime) == 0 { t /= int64(prime) count[prime]++ } } return count, t == 1 } func getPrimeCountFromString(num string) map[int]int { count := map[int]int{2: 0, 3: 0, 5: 0, 7: 0} for _, d := range num { for prime, freq := range kFactorCounts[int(d-'0')] { count[prime] += freq } } return count } func getFactorCount(count map[int]int) map[int]int { res := map[int]int{} count8 := count[2] / 3 remaining2 := count[2] % 3 count9 := count[3] / 2 count3 := count[3] % 2 count4 := remaining2 / 2 count2 := remaining2 % 2 count6 := 0 if count2 == 1 && count3 == 1 { count2, count3 = 0, 0 count6 = 1 } if count3 == 1 && count4 == 1 { count2 = 1 count6 = 1 count3, count4 = 0, 0 } res[2] = count2 res[3] = count3 res[4] = count4 res[5] = count[5] res[6] = count6 res[7] = count[7] res[8] = count8 res[9] = count9 return res } func construct(factors map[int]int) string { var res strings.Builder for digit := 2; digit < 10; digit++ { res.WriteString(strings.Repeat(strconv.Itoa(digit), factors[digit])) } return res.String() } func isSubset(a, b map[int]int) bool { for key, value := range a { if b[key] < value { return false } } return true } func subtract(a, b map[int]int) map[int]int { res := make(map[int]int, len(a)) for k, v := range a { res[k] = v } for k, v := range b { res[k] = max(0, res[k]-v) } return res } func sumValues(count map[int]int) int { sum := 0 for _, v := range count { sum += v } return sum }
3,349
Adjacent Increasing Subarrays Detection I
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers and an integer <code>k</code>, determine whether there exist <strong>two</strong> <strong>adjacent</strong> <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return <code>true</code> if it is <em>possible</em> to find <strong>two </strong>such subarrays, and <code>false</code> otherwise.</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 = [2,5,7,8,9,2,3,4,3,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index <code>2</code> is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index <code>5</code> is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, so the result 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">nums = [1,2,3,4,4,4,4,5,6,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></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; 2 * k &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array
C++
class Solution { public: bool hasIncreasingSubarrays(vector<int>& nums, int k) { int mx = 0, pre = 0, cur = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { ++cur; if (i == n - 1 || nums[i] >= nums[i + 1]) { mx = max({mx, cur / 2, min(pre, cur)}); pre = cur; cur = 0; } } return mx >= k; } };
3,349
Adjacent Increasing Subarrays Detection I
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers and an integer <code>k</code>, determine whether there exist <strong>two</strong> <strong>adjacent</strong> <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return <code>true</code> if it is <em>possible</em> to find <strong>two </strong>such subarrays, and <code>false</code> otherwise.</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 = [2,5,7,8,9,2,3,4,3,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index <code>2</code> is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index <code>5</code> is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, so the result 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">nums = [1,2,3,4,4,4,4,5,6,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></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; 2 * k &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array
Go
func hasIncreasingSubarrays(nums []int, k int) bool { mx, pre, cur := 0, 0, 0 for i, x := range nums { cur++ if i == len(nums)-1 || x >= nums[i+1] { mx = max(mx, max(cur/2, min(pre, cur))) pre, cur = cur, 0 } } return mx >= k }
3,349
Adjacent Increasing Subarrays Detection I
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers and an integer <code>k</code>, determine whether there exist <strong>two</strong> <strong>adjacent</strong> <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return <code>true</code> if it is <em>possible</em> to find <strong>two </strong>such subarrays, and <code>false</code> otherwise.</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 = [2,5,7,8,9,2,3,4,3,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index <code>2</code> is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index <code>5</code> is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, so the result 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">nums = [1,2,3,4,4,4,4,5,6,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></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; 2 * k &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array
Java
class Solution { public boolean hasIncreasingSubarrays(List<Integer> nums, int k) { int mx = 0, pre = 0, cur = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { ++cur; if (i == n - 1 || nums.get(i) >= nums.get(i + 1)) { mx = Math.max(mx, Math.max(cur / 2, Math.min(pre, cur))); pre = cur; cur = 0; } } return mx >= k; } }
3,349
Adjacent Increasing Subarrays Detection I
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers and an integer <code>k</code>, determine whether there exist <strong>two</strong> <strong>adjacent</strong> <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return <code>true</code> if it is <em>possible</em> to find <strong>two </strong>such subarrays, and <code>false</code> otherwise.</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 = [2,5,7,8,9,2,3,4,3,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index <code>2</code> is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index <code>5</code> is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, so the result 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">nums = [1,2,3,4,4,4,4,5,6,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></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; 2 * k &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array
Python
class Solution: def hasIncreasingSubarrays(self, nums: List[int], k: int) -> bool: mx = pre = cur = 0 for i, x in enumerate(nums): cur += 1 if i == len(nums) - 1 or x >= nums[i + 1]: mx = max(mx, cur // 2, min(pre, cur)) pre, cur = cur, 0 return mx >= k
3,349
Adjacent Increasing Subarrays Detection I
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers and an integer <code>k</code>, determine whether there exist <strong>two</strong> <strong>adjacent</strong> <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return <code>true</code> if it is <em>possible</em> to find <strong>two </strong>such subarrays, and <code>false</code> otherwise.</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 = [2,5,7,8,9,2,3,4,3,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index <code>2</code> is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index <code>5</code> is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, so the result 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">nums = [1,2,3,4,4,4,4,5,6,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></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; 2 * k &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array
TypeScript
function hasIncreasingSubarrays(nums: number[], k: number): boolean { let [mx, pre, cur] = [0, 0, 0]; const n = nums.length; for (let i = 0; i < n; ++i) { ++cur; if (i === n - 1 || nums[i] >= nums[i + 1]) { mx = Math.max(mx, (cur / 2) | 0, Math.min(pre, cur)); [pre, cur] = [cur, 0]; } } return mx >= k; }
3,350
Adjacent Increasing Subarrays Detection II
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, your task is to find the <strong>maximum</strong> value of <code>k</code> for which there exist <strong>two</strong> adjacent <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> each, such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays of length <code>k</code> starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return the <strong>maximum</strong> <em>possible</em> value of <code>k</code>.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [2,5,7,8,9,2,3,4,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 2 is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index 5 is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 3 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</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,2,3,4,4,4,4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 0 is <code>[1, 2]</code>, which is strictly increasing.</li> <li>The subarray starting at index 2 is <code>[3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 2 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: int maxIncreasingSubarrays(vector<int>& nums) { int ans = 0, pre = 0, cur = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { ++cur; if (i == n - 1 || nums[i] >= nums[i + 1]) { ans = max({ans, cur / 2, min(pre, cur)}); pre = cur; cur = 0; } } return ans; } };
3,350
Adjacent Increasing Subarrays Detection II
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, your task is to find the <strong>maximum</strong> value of <code>k</code> for which there exist <strong>two</strong> adjacent <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> each, such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays of length <code>k</code> starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return the <strong>maximum</strong> <em>possible</em> value of <code>k</code>.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [2,5,7,8,9,2,3,4,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 2 is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index 5 is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 3 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</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,2,3,4,4,4,4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 0 is <code>[1, 2]</code>, which is strictly increasing.</li> <li>The subarray starting at index 2 is <code>[3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 2 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Go
func maxIncreasingSubarrays(nums []int) (ans int) { pre, cur := 0, 0 for i, x := range nums { cur++ if i == len(nums)-1 || x >= nums[i+1] { ans = max(ans, max(cur/2, min(pre, cur))) pre, cur = cur, 0 } } return }
3,350
Adjacent Increasing Subarrays Detection II
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, your task is to find the <strong>maximum</strong> value of <code>k</code> for which there exist <strong>two</strong> adjacent <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> each, such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays of length <code>k</code> starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return the <strong>maximum</strong> <em>possible</em> value of <code>k</code>.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [2,5,7,8,9,2,3,4,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 2 is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index 5 is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 3 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</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,2,3,4,4,4,4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 0 is <code>[1, 2]</code>, which is strictly increasing.</li> <li>The subarray starting at index 2 is <code>[3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 2 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { public int maxIncreasingSubarrays(List<Integer> nums) { int ans = 0, pre = 0, cur = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { ++cur; if (i == n - 1 || nums.get(i) >= nums.get(i + 1)) { ans = Math.max(ans, Math.max(cur / 2, Math.min(pre, cur))); pre = cur; cur = 0; } } return ans; } }
3,350
Adjacent Increasing Subarrays Detection II
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, your task is to find the <strong>maximum</strong> value of <code>k</code> for which there exist <strong>two</strong> adjacent <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> each, such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays of length <code>k</code> starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return the <strong>maximum</strong> <em>possible</em> value of <code>k</code>.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [2,5,7,8,9,2,3,4,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 2 is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index 5 is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 3 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</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,2,3,4,4,4,4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 0 is <code>[1, 2]</code>, which is strictly increasing.</li> <li>The subarray starting at index 2 is <code>[3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 2 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def maxIncreasingSubarrays(self, nums: List[int]) -> int: ans = pre = cur = 0 for i, x in enumerate(nums): cur += 1 if i == len(nums) - 1 or x >= nums[i + 1]: ans = max(ans, cur // 2, min(pre, cur)) pre, cur = cur, 0 return ans
3,350
Adjacent Increasing Subarrays Detection II
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, your task is to find the <strong>maximum</strong> value of <code>k</code> for which there exist <strong>two</strong> adjacent <span data-keyword="subarray-nonempty">subarrays</span> of length <code>k</code> each, such that both subarrays are <strong>strictly</strong> <strong>increasing</strong>. Specifically, check if there are <strong>two</strong> subarrays of length <code>k</code> starting at indices <code>a</code> and <code>b</code> (<code>a &lt; b</code>), where:</p> <ul> <li>Both subarrays <code>nums[a..a + k - 1]</code> and <code>nums[b..b + k - 1]</code> are <strong>strictly increasing</strong>.</li> <li>The subarrays must be <strong>adjacent</strong>, meaning <code>b = a + k</code>.</li> </ul> <p>Return the <strong>maximum</strong> <em>possible</em> value of <code>k</code>.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [2,5,7,8,9,2,3,4,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 2 is <code>[7, 8, 9]</code>, which is strictly increasing.</li> <li>The subarray starting at index 5 is <code>[2, 3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 3 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</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,2,3,4,4,4,4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray starting at index 0 is <code>[1, 2]</code>, which is strictly increasing.</li> <li>The subarray starting at index 2 is <code>[3, 4]</code>, which is also strictly increasing.</li> <li>These two subarrays are adjacent, and 2 is the <strong>maximum</strong> possible value of <code>k</code> for which two such adjacent strictly increasing subarrays exist.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
TypeScript
function maxIncreasingSubarrays(nums: number[]): number { let [ans, pre, cur] = [0, 0, 0]; const n = nums.length; for (let i = 0; i < n; ++i) { ++cur; if (i === n - 1 || nums[i] >= nums[i + 1]) { ans = Math.max(ans, (cur / 2) | 0, Math.min(pre, cur)); [pre, cur] = [cur, 0]; } } return ans; }
3,351
Sum of Good Subsequences
Hard
<p>You are given an integer array <code>nums</code>. A <strong>good </strong><span data-keyword="subsequence-array">subsequence</span> is defined as a subsequence of <code>nums</code> where the absolute difference between any <strong>two</strong> consecutive elements in the subsequence is <strong>exactly</strong> 1.</p> <p>Return the <strong>sum</strong> of all <em>possible</em> <strong>good subsequences</strong> of <code>nums</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p><strong>Note </strong>that a subsequence of size 1 is considered good by definition.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[1]</code>, <code>[1,2]</code>, <code>[2,1]</code>, <code>[1,2,1]</code>.</li> <li>The sum of elements in these subsequences is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[3]</code>, <code>[4]</code>, <code>[5]</code>, <code>[3,4]</code>, <code>[4,5]</code>, <code>[3,4,5]</code>.</li> <li>The sum of elements in these subsequences is 40.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
C++
class Solution { public: int sumOfGoodSubsequences(vector<int>& nums) { const int mod = 1e9 + 7; int mx = ranges::max(nums); vector<long long> f(mx + 1), g(mx + 1); for (int x : nums) { f[x] += x; g[x] += 1; if (x > 0) { f[x] = (f[x] + f[x - 1] + g[x - 1] * x % mod) % mod; g[x] = (g[x] + g[x - 1]) % mod; } if (x + 1 <= mx) { f[x] = (f[x] + f[x + 1] + g[x + 1] * x % mod) % mod; g[x] = (g[x] + g[x + 1]) % mod; } } return accumulate(f.begin(), f.end(), 0LL) % mod; } };
3,351
Sum of Good Subsequences
Hard
<p>You are given an integer array <code>nums</code>. A <strong>good </strong><span data-keyword="subsequence-array">subsequence</span> is defined as a subsequence of <code>nums</code> where the absolute difference between any <strong>two</strong> consecutive elements in the subsequence is <strong>exactly</strong> 1.</p> <p>Return the <strong>sum</strong> of all <em>possible</em> <strong>good subsequences</strong> of <code>nums</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p><strong>Note </strong>that a subsequence of size 1 is considered good by definition.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[1]</code>, <code>[1,2]</code>, <code>[2,1]</code>, <code>[1,2,1]</code>.</li> <li>The sum of elements in these subsequences is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[3]</code>, <code>[4]</code>, <code>[5]</code>, <code>[3,4]</code>, <code>[4,5]</code>, <code>[3,4,5]</code>.</li> <li>The sum of elements in these subsequences is 40.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Go
func sumOfGoodSubsequences(nums []int) (ans int) { mod := int(1e9 + 7) mx := slices.Max(nums) f := make([]int, mx+1) g := make([]int, mx+1) for _, x := range nums { f[x] += x g[x] += 1 if x > 0 { f[x] = (f[x] + f[x-1] + g[x-1]*x%mod) % mod g[x] = (g[x] + g[x-1]) % mod } if x+1 <= mx { f[x] = (f[x] + f[x+1] + g[x+1]*x%mod) % mod g[x] = (g[x] + g[x+1]) % mod } } for _, x := range f { ans = (ans + x) % mod } return }
3,351
Sum of Good Subsequences
Hard
<p>You are given an integer array <code>nums</code>. A <strong>good </strong><span data-keyword="subsequence-array">subsequence</span> is defined as a subsequence of <code>nums</code> where the absolute difference between any <strong>two</strong> consecutive elements in the subsequence is <strong>exactly</strong> 1.</p> <p>Return the <strong>sum</strong> of all <em>possible</em> <strong>good subsequences</strong> of <code>nums</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p><strong>Note </strong>that a subsequence of size 1 is considered good by definition.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[1]</code>, <code>[1,2]</code>, <code>[2,1]</code>, <code>[1,2,1]</code>.</li> <li>The sum of elements in these subsequences is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[3]</code>, <code>[4]</code>, <code>[5]</code>, <code>[3,4]</code>, <code>[4,5]</code>, <code>[3,4,5]</code>.</li> <li>The sum of elements in these subsequences is 40.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Java
class Solution { public int sumOfGoodSubsequences(int[] nums) { final int mod = (int) 1e9 + 7; int mx = 0; for (int x : nums) { mx = Math.max(mx, x); } long[] f = new long[mx + 1]; long[] g = new long[mx + 1]; for (int x : nums) { f[x] += x; g[x] += 1; if (x > 0) { f[x] = (f[x] + f[x - 1] + g[x - 1] * x % mod) % mod; g[x] = (g[x] + g[x - 1]) % mod; } if (x + 1 <= mx) { f[x] = (f[x] + f[x + 1] + g[x + 1] * x % mod) % mod; g[x] = (g[x] + g[x + 1]) % mod; } } long ans = 0; for (long x : f) { ans = (ans + x) % mod; } return (int) ans; } }
3,351
Sum of Good Subsequences
Hard
<p>You are given an integer array <code>nums</code>. A <strong>good </strong><span data-keyword="subsequence-array">subsequence</span> is defined as a subsequence of <code>nums</code> where the absolute difference between any <strong>two</strong> consecutive elements in the subsequence is <strong>exactly</strong> 1.</p> <p>Return the <strong>sum</strong> of all <em>possible</em> <strong>good subsequences</strong> of <code>nums</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p><strong>Note </strong>that a subsequence of size 1 is considered good by definition.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[1]</code>, <code>[1,2]</code>, <code>[2,1]</code>, <code>[1,2,1]</code>.</li> <li>The sum of elements in these subsequences is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[3]</code>, <code>[4]</code>, <code>[5]</code>, <code>[3,4]</code>, <code>[4,5]</code>, <code>[3,4,5]</code>.</li> <li>The sum of elements in these subsequences is 40.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Python
class Solution: def sumOfGoodSubsequences(self, nums: List[int]) -> int: mod = 10**9 + 7 f = defaultdict(int) g = defaultdict(int) for x in nums: f[x] += x g[x] += 1 f[x] += f[x - 1] + g[x - 1] * x g[x] += g[x - 1] f[x] += f[x + 1] + g[x + 1] * x g[x] += g[x + 1] return sum(f.values()) % mod
3,351
Sum of Good Subsequences
Hard
<p>You are given an integer array <code>nums</code>. A <strong>good </strong><span data-keyword="subsequence-array">subsequence</span> is defined as a subsequence of <code>nums</code> where the absolute difference between any <strong>two</strong> consecutive elements in the subsequence is <strong>exactly</strong> 1.</p> <p>Return the <strong>sum</strong> of all <em>possible</em> <strong>good subsequences</strong> of <code>nums</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p><strong>Note </strong>that a subsequence of size 1 is considered good by definition.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[1]</code>, <code>[1,2]</code>, <code>[2,1]</code>, <code>[1,2,1]</code>.</li> <li>The sum of elements in these subsequences is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Good subsequences are: <code>[3]</code>, <code>[4]</code>, <code>[5]</code>, <code>[3,4]</code>, <code>[4,5]</code>, <code>[3,4,5]</code>.</li> <li>The sum of elements in these subsequences is 40.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
TypeScript
function sumOfGoodSubsequences(nums: number[]): number { const mod = 10 ** 9 + 7; const mx = Math.max(...nums); const f: number[] = Array(mx + 1).fill(0); const g: number[] = Array(mx + 1).fill(0); for (const x of nums) { f[x] += x; g[x] += 1; if (x > 0) { f[x] = (f[x] + f[x - 1] + ((g[x - 1] * x) % mod)) % mod; g[x] = (g[x] + g[x - 1]) % mod; } if (x + 1 <= mx) { f[x] = (f[x] + f[x + 1] + ((g[x + 1] * x) % mod)) % mod; g[x] = (g[x] + g[x + 1]) % mod; } } return f.reduce((acc, cur) => (acc + cur) % mod, 0); }
3,353
Minimum Total Operations
Easy
<p>Given an array of integers <code><font face="monospace">nums</font></code>, you can perform <em>any</em> number of operations on this array.</p> <p>In each <strong>operation</strong>, you can:</p> <ul> <li>Choose a <strong>prefix</strong> of the array.</li> <li>Choose an integer <code><font face="monospace">k</font></code><font face="monospace"> </font>(which can be negative) and add <code><font face="monospace">k</font></code> to each element in the chosen prefix.</li> </ul> <p>A <strong>prefix</strong> of an array is a subarray that starts from the beginning of the array and extends to any point within it.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>arr</code> equal.</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,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>Operation 1</strong>: Choose the prefix <code>[1, 4]</code> of length 2 and add -2 to each element of the prefix. The array becomes <code>[-1, 2, 2]</code>.</li> <li><strong>Operation 2</strong>: Choose the prefix <code>[-1]</code> of length 1 and add 3 to it. The array becomes <code>[2, 2, 2]</code>.</li> <li>Thus, the minimum number of required operations is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [10,10,10]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>All elements are already equal, so no operations are needed.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
C++
class Solution { public: int minOperations(vector<int>& nums) { int ans = 0; for (int i = 1; i < nums.size(); ++i) { ans += nums[i] != nums[i - 1]; } return ans; } };
3,353
Minimum Total Operations
Easy
<p>Given an array of integers <code><font face="monospace">nums</font></code>, you can perform <em>any</em> number of operations on this array.</p> <p>In each <strong>operation</strong>, you can:</p> <ul> <li>Choose a <strong>prefix</strong> of the array.</li> <li>Choose an integer <code><font face="monospace">k</font></code><font face="monospace"> </font>(which can be negative) and add <code><font face="monospace">k</font></code> to each element in the chosen prefix.</li> </ul> <p>A <strong>prefix</strong> of an array is a subarray that starts from the beginning of the array and extends to any point within it.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>arr</code> equal.</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,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>Operation 1</strong>: Choose the prefix <code>[1, 4]</code> of length 2 and add -2 to each element of the prefix. The array becomes <code>[-1, 2, 2]</code>.</li> <li><strong>Operation 2</strong>: Choose the prefix <code>[-1]</code> of length 1 and add 3 to it. The array becomes <code>[2, 2, 2]</code>.</li> <li>Thus, the minimum number of required operations is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [10,10,10]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>All elements are already equal, so no operations are needed.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Go
func minOperations(nums []int) (ans int) { for i, x := range nums[1:] { if x != nums[i] { ans++ } } return }
3,353
Minimum Total Operations
Easy
<p>Given an array of integers <code><font face="monospace">nums</font></code>, you can perform <em>any</em> number of operations on this array.</p> <p>In each <strong>operation</strong>, you can:</p> <ul> <li>Choose a <strong>prefix</strong> of the array.</li> <li>Choose an integer <code><font face="monospace">k</font></code><font face="monospace"> </font>(which can be negative) and add <code><font face="monospace">k</font></code> to each element in the chosen prefix.</li> </ul> <p>A <strong>prefix</strong> of an array is a subarray that starts from the beginning of the array and extends to any point within it.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>arr</code> equal.</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,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>Operation 1</strong>: Choose the prefix <code>[1, 4]</code> of length 2 and add -2 to each element of the prefix. The array becomes <code>[-1, 2, 2]</code>.</li> <li><strong>Operation 2</strong>: Choose the prefix <code>[-1]</code> of length 1 and add 3 to it. The array becomes <code>[2, 2, 2]</code>.</li> <li>Thus, the minimum number of required operations is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [10,10,10]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>All elements are already equal, so no operations are needed.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Java
class Solution { public int minOperations(int[] nums) { int ans = 0; for (int i = 1; i < nums.length; ++i) { ans += nums[i] != nums[i - 1] ? 1 : 0; } return ans; } }
3,353
Minimum Total Operations
Easy
<p>Given an array of integers <code><font face="monospace">nums</font></code>, you can perform <em>any</em> number of operations on this array.</p> <p>In each <strong>operation</strong>, you can:</p> <ul> <li>Choose a <strong>prefix</strong> of the array.</li> <li>Choose an integer <code><font face="monospace">k</font></code><font face="monospace"> </font>(which can be negative) and add <code><font face="monospace">k</font></code> to each element in the chosen prefix.</li> </ul> <p>A <strong>prefix</strong> of an array is a subarray that starts from the beginning of the array and extends to any point within it.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>arr</code> equal.</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,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>Operation 1</strong>: Choose the prefix <code>[1, 4]</code> of length 2 and add -2 to each element of the prefix. The array becomes <code>[-1, 2, 2]</code>.</li> <li><strong>Operation 2</strong>: Choose the prefix <code>[-1]</code> of length 1 and add 3 to it. The array becomes <code>[2, 2, 2]</code>.</li> <li>Thus, the minimum number of required operations is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [10,10,10]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>All elements are already equal, so no operations are needed.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
Python
class Solution: def minOperations(self, nums: List[int]) -> int: return sum(x != y for x, y in pairwise(nums))
3,353
Minimum Total Operations
Easy
<p>Given an array of integers <code><font face="monospace">nums</font></code>, you can perform <em>any</em> number of operations on this array.</p> <p>In each <strong>operation</strong>, you can:</p> <ul> <li>Choose a <strong>prefix</strong> of the array.</li> <li>Choose an integer <code><font face="monospace">k</font></code><font face="monospace"> </font>(which can be negative) and add <code><font face="monospace">k</font></code> to each element in the chosen prefix.</li> </ul> <p>A <strong>prefix</strong> of an array is a subarray that starts from the beginning of the array and extends to any point within it.</p> <p>Return the <strong>minimum</strong> number of operations required to make all elements in <code>arr</code> equal.</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,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>Operation 1</strong>: Choose the prefix <code>[1, 4]</code> of length 2 and add -2 to each element of the prefix. The array becomes <code>[-1, 2, 2]</code>.</li> <li><strong>Operation 2</strong>: Choose the prefix <code>[-1]</code> of length 1 and add 3 to it. The array becomes <code>[2, 2, 2]</code>.</li> <li>Thus, the minimum number of required operations is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [10,10,10]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>All elements are already equal, so no operations are needed.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array
TypeScript
function minOperations(nums: number[]): number { let ans = 0; for (let i = 1; i < nums.length; ++i) { ans += nums[i] !== nums[i - 1] ? 1 : 0; } return ans; }
3,354
Make Array Elements Equal to Zero
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Start by selecting a starting position <code>curr</code> such that <code>nums[curr] == 0</code>, and choose a movement <strong>direction</strong> of&nbsp;either left or right.</p> <p>After that, you repeat the following process:</p> <ul> <li>If <code>curr</code> is out of the range <code>[0, n - 1]</code>, this process ends.</li> <li>If <code>nums[curr] == 0</code>, move in the current direction by <strong>incrementing</strong> <code>curr</code> if you are moving right, or <strong>decrementing</strong> <code>curr</code> if you are moving left.</li> <li>Else if <code>nums[curr] &gt; 0</code>: <ul> <li>Decrement <code>nums[curr]</code> by 1.</li> <li><strong>Reverse</strong>&nbsp;your movement direction (left becomes right and vice versa).</li> <li>Take a step in your new direction.</li> </ul> </li> </ul> <p>A selection of the initial position <code>curr</code> and movement direction is considered <strong>valid</strong> if every element in <code>nums</code> becomes 0 by the end of the process.</p> <p>Return the number of possible <strong>valid</strong> selections.</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,0,2,0,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only possible valid selections are the following:</p> <ul> <li>Choose <code>curr = 3</code>, and a movement direction to the left. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,<strong><u>2</u></strong>,0,3] -&gt; [1,0,1,<strong><u>0</u></strong>,3] -&gt; [1,0,1,0,<strong><u>3</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>1</u></strong>,0,2] -&gt; [1,0,0,<strong><u>0</u></strong>,2] -&gt; [1,0,0,0,<strong><u>2</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>0</u></strong>,0,1] -&gt; [1,<strong><u>0</u></strong>,0,0,1] -&gt; [<strong><u>1</u></strong>,0,0,0,1] -&gt; [0,<strong><u>0</u></strong>,0,0,1] -&gt; [0,0,<strong><u>0</u></strong>,0,1] -&gt; [0,0,0,<strong><u>0</u></strong>,1] -&gt; [0,0,0,0,<strong><u>1</u></strong>] -&gt; [0,0,0,0,0]</code>.</li> </ul> </li> <li>Choose <code>curr = 3</code>, and a movement direction to the right. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,2,0,<strong><u>3</u></strong>] -&gt; [1,0,2,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>2</u></strong>,0,2] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,1,0,<strong><u>2</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>1</u></strong>,0,1] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,0,0,<strong><u>1</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,0] -&gt; [1,0,<strong><u>0</u></strong>,0,0] -&gt; [1,<strong><u>0</u></strong>,0,0,0] -&gt; [<strong><u>1</u></strong>,0,0,0,0] -&gt; [0,0,0,0,0].</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,0,4,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible valid selections.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> <li>There is at least one element <code>i</code> where <code>nums[i] == 0</code>.</li> </ul>
Array; Prefix Sum; Simulation
C++
class Solution { public: int countValidSelections(vector<int>& nums) { int s = accumulate(nums.begin(), nums.end(), 0); int ans = 0, l = 0; for (int x : nums) { if (x) { l += x; } else if (l * 2 == s) { ans += 2; } else if (abs(l * 2 - s) <= 1) { ++ans; } } return ans; } };
3,354
Make Array Elements Equal to Zero
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Start by selecting a starting position <code>curr</code> such that <code>nums[curr] == 0</code>, and choose a movement <strong>direction</strong> of&nbsp;either left or right.</p> <p>After that, you repeat the following process:</p> <ul> <li>If <code>curr</code> is out of the range <code>[0, n - 1]</code>, this process ends.</li> <li>If <code>nums[curr] == 0</code>, move in the current direction by <strong>incrementing</strong> <code>curr</code> if you are moving right, or <strong>decrementing</strong> <code>curr</code> if you are moving left.</li> <li>Else if <code>nums[curr] &gt; 0</code>: <ul> <li>Decrement <code>nums[curr]</code> by 1.</li> <li><strong>Reverse</strong>&nbsp;your movement direction (left becomes right and vice versa).</li> <li>Take a step in your new direction.</li> </ul> </li> </ul> <p>A selection of the initial position <code>curr</code> and movement direction is considered <strong>valid</strong> if every element in <code>nums</code> becomes 0 by the end of the process.</p> <p>Return the number of possible <strong>valid</strong> selections.</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,0,2,0,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only possible valid selections are the following:</p> <ul> <li>Choose <code>curr = 3</code>, and a movement direction to the left. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,<strong><u>2</u></strong>,0,3] -&gt; [1,0,1,<strong><u>0</u></strong>,3] -&gt; [1,0,1,0,<strong><u>3</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>1</u></strong>,0,2] -&gt; [1,0,0,<strong><u>0</u></strong>,2] -&gt; [1,0,0,0,<strong><u>2</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>0</u></strong>,0,1] -&gt; [1,<strong><u>0</u></strong>,0,0,1] -&gt; [<strong><u>1</u></strong>,0,0,0,1] -&gt; [0,<strong><u>0</u></strong>,0,0,1] -&gt; [0,0,<strong><u>0</u></strong>,0,1] -&gt; [0,0,0,<strong><u>0</u></strong>,1] -&gt; [0,0,0,0,<strong><u>1</u></strong>] -&gt; [0,0,0,0,0]</code>.</li> </ul> </li> <li>Choose <code>curr = 3</code>, and a movement direction to the right. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,2,0,<strong><u>3</u></strong>] -&gt; [1,0,2,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>2</u></strong>,0,2] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,1,0,<strong><u>2</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>1</u></strong>,0,1] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,0,0,<strong><u>1</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,0] -&gt; [1,0,<strong><u>0</u></strong>,0,0] -&gt; [1,<strong><u>0</u></strong>,0,0,0] -&gt; [<strong><u>1</u></strong>,0,0,0,0] -&gt; [0,0,0,0,0].</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,0,4,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible valid selections.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> <li>There is at least one element <code>i</code> where <code>nums[i] == 0</code>.</li> </ul>
Array; Prefix Sum; Simulation
Go
func countValidSelections(nums []int) (ans int) { l, s := 0, 0 for _, x := range nums { s += x } for _, x := range nums { if x != 0 { l += x } else if l*2 == s { ans += 2 } else if abs(l*2-s) <= 1 { ans++ } } return } func abs(x int) int { if x < 0 { return -x } return x }
3,354
Make Array Elements Equal to Zero
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Start by selecting a starting position <code>curr</code> such that <code>nums[curr] == 0</code>, and choose a movement <strong>direction</strong> of&nbsp;either left or right.</p> <p>After that, you repeat the following process:</p> <ul> <li>If <code>curr</code> is out of the range <code>[0, n - 1]</code>, this process ends.</li> <li>If <code>nums[curr] == 0</code>, move in the current direction by <strong>incrementing</strong> <code>curr</code> if you are moving right, or <strong>decrementing</strong> <code>curr</code> if you are moving left.</li> <li>Else if <code>nums[curr] &gt; 0</code>: <ul> <li>Decrement <code>nums[curr]</code> by 1.</li> <li><strong>Reverse</strong>&nbsp;your movement direction (left becomes right and vice versa).</li> <li>Take a step in your new direction.</li> </ul> </li> </ul> <p>A selection of the initial position <code>curr</code> and movement direction is considered <strong>valid</strong> if every element in <code>nums</code> becomes 0 by the end of the process.</p> <p>Return the number of possible <strong>valid</strong> selections.</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,0,2,0,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only possible valid selections are the following:</p> <ul> <li>Choose <code>curr = 3</code>, and a movement direction to the left. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,<strong><u>2</u></strong>,0,3] -&gt; [1,0,1,<strong><u>0</u></strong>,3] -&gt; [1,0,1,0,<strong><u>3</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>1</u></strong>,0,2] -&gt; [1,0,0,<strong><u>0</u></strong>,2] -&gt; [1,0,0,0,<strong><u>2</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>0</u></strong>,0,1] -&gt; [1,<strong><u>0</u></strong>,0,0,1] -&gt; [<strong><u>1</u></strong>,0,0,0,1] -&gt; [0,<strong><u>0</u></strong>,0,0,1] -&gt; [0,0,<strong><u>0</u></strong>,0,1] -&gt; [0,0,0,<strong><u>0</u></strong>,1] -&gt; [0,0,0,0,<strong><u>1</u></strong>] -&gt; [0,0,0,0,0]</code>.</li> </ul> </li> <li>Choose <code>curr = 3</code>, and a movement direction to the right. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,2,0,<strong><u>3</u></strong>] -&gt; [1,0,2,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>2</u></strong>,0,2] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,1,0,<strong><u>2</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>1</u></strong>,0,1] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,0,0,<strong><u>1</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,0] -&gt; [1,0,<strong><u>0</u></strong>,0,0] -&gt; [1,<strong><u>0</u></strong>,0,0,0] -&gt; [<strong><u>1</u></strong>,0,0,0,0] -&gt; [0,0,0,0,0].</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,0,4,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible valid selections.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> <li>There is at least one element <code>i</code> where <code>nums[i] == 0</code>.</li> </ul>
Array; Prefix Sum; Simulation
Java
class Solution { public int countValidSelections(int[] nums) { int s = Arrays.stream(nums).sum(); int ans = 0, l = 0; for (int x : nums) { if (x != 0) { l += x; } else if (l * 2 == s) { ans += 2; } else if (Math.abs(l * 2 - s) <= 1) { ++ans; } } return ans; } }
3,354
Make Array Elements Equal to Zero
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Start by selecting a starting position <code>curr</code> such that <code>nums[curr] == 0</code>, and choose a movement <strong>direction</strong> of&nbsp;either left or right.</p> <p>After that, you repeat the following process:</p> <ul> <li>If <code>curr</code> is out of the range <code>[0, n - 1]</code>, this process ends.</li> <li>If <code>nums[curr] == 0</code>, move in the current direction by <strong>incrementing</strong> <code>curr</code> if you are moving right, or <strong>decrementing</strong> <code>curr</code> if you are moving left.</li> <li>Else if <code>nums[curr] &gt; 0</code>: <ul> <li>Decrement <code>nums[curr]</code> by 1.</li> <li><strong>Reverse</strong>&nbsp;your movement direction (left becomes right and vice versa).</li> <li>Take a step in your new direction.</li> </ul> </li> </ul> <p>A selection of the initial position <code>curr</code> and movement direction is considered <strong>valid</strong> if every element in <code>nums</code> becomes 0 by the end of the process.</p> <p>Return the number of possible <strong>valid</strong> selections.</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,0,2,0,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only possible valid selections are the following:</p> <ul> <li>Choose <code>curr = 3</code>, and a movement direction to the left. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,<strong><u>2</u></strong>,0,3] -&gt; [1,0,1,<strong><u>0</u></strong>,3] -&gt; [1,0,1,0,<strong><u>3</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>1</u></strong>,0,2] -&gt; [1,0,0,<strong><u>0</u></strong>,2] -&gt; [1,0,0,0,<strong><u>2</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>0</u></strong>,0,1] -&gt; [1,<strong><u>0</u></strong>,0,0,1] -&gt; [<strong><u>1</u></strong>,0,0,0,1] -&gt; [0,<strong><u>0</u></strong>,0,0,1] -&gt; [0,0,<strong><u>0</u></strong>,0,1] -&gt; [0,0,0,<strong><u>0</u></strong>,1] -&gt; [0,0,0,0,<strong><u>1</u></strong>] -&gt; [0,0,0,0,0]</code>.</li> </ul> </li> <li>Choose <code>curr = 3</code>, and a movement direction to the right. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,2,0,<strong><u>3</u></strong>] -&gt; [1,0,2,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>2</u></strong>,0,2] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,1,0,<strong><u>2</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>1</u></strong>,0,1] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,0,0,<strong><u>1</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,0] -&gt; [1,0,<strong><u>0</u></strong>,0,0] -&gt; [1,<strong><u>0</u></strong>,0,0,0] -&gt; [<strong><u>1</u></strong>,0,0,0,0] -&gt; [0,0,0,0,0].</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,0,4,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible valid selections.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> <li>There is at least one element <code>i</code> where <code>nums[i] == 0</code>.</li> </ul>
Array; Prefix Sum; Simulation
Python
class Solution: def countValidSelections(self, nums: List[int]) -> int: s = sum(nums) ans = l = 0 for x in nums: if x: l += x elif l * 2 == s: ans += 2 elif abs(l * 2 - s) == 1: ans += 1 return ans
3,354
Make Array Elements Equal to Zero
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Start by selecting a starting position <code>curr</code> such that <code>nums[curr] == 0</code>, and choose a movement <strong>direction</strong> of&nbsp;either left or right.</p> <p>After that, you repeat the following process:</p> <ul> <li>If <code>curr</code> is out of the range <code>[0, n - 1]</code>, this process ends.</li> <li>If <code>nums[curr] == 0</code>, move in the current direction by <strong>incrementing</strong> <code>curr</code> if you are moving right, or <strong>decrementing</strong> <code>curr</code> if you are moving left.</li> <li>Else if <code>nums[curr] &gt; 0</code>: <ul> <li>Decrement <code>nums[curr]</code> by 1.</li> <li><strong>Reverse</strong>&nbsp;your movement direction (left becomes right and vice versa).</li> <li>Take a step in your new direction.</li> </ul> </li> </ul> <p>A selection of the initial position <code>curr</code> and movement direction is considered <strong>valid</strong> if every element in <code>nums</code> becomes 0 by the end of the process.</p> <p>Return the number of possible <strong>valid</strong> selections.</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,0,2,0,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only possible valid selections are the following:</p> <ul> <li>Choose <code>curr = 3</code>, and a movement direction to the left. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,<strong><u>2</u></strong>,0,3] -&gt; [1,0,1,<strong><u>0</u></strong>,3] -&gt; [1,0,1,0,<strong><u>3</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>1</u></strong>,0,2] -&gt; [1,0,0,<strong><u>0</u></strong>,2] -&gt; [1,0,0,0,<strong><u>2</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>0</u></strong>,0,1] -&gt; [1,<strong><u>0</u></strong>,0,0,1] -&gt; [<strong><u>1</u></strong>,0,0,0,1] -&gt; [0,<strong><u>0</u></strong>,0,0,1] -&gt; [0,0,<strong><u>0</u></strong>,0,1] -&gt; [0,0,0,<strong><u>0</u></strong>,1] -&gt; [0,0,0,0,<strong><u>1</u></strong>] -&gt; [0,0,0,0,0]</code>.</li> </ul> </li> <li>Choose <code>curr = 3</code>, and a movement direction to the right. <ul> <li><code>[1,0,2,<strong><u>0</u></strong>,3] -&gt; [1,0,2,0,<strong><u>3</u></strong>] -&gt; [1,0,2,<strong><u>0</u></strong>,2] -&gt; [1,0,<strong><u>2</u></strong>,0,2] -&gt; [1,0,1,<strong><u>0</u></strong>,2] -&gt; [1,0,1,0,<strong><u>2</u></strong>] -&gt; [1,0,1,<strong><u>0</u></strong>,1] -&gt; [1,0,<strong><u>1</u></strong>,0,1] -&gt; [1,0,0,<strong><u>0</u></strong>,1] -&gt; [1,0,0,0,<strong><u>1</u></strong>] -&gt; [1,0,0,<strong><u>0</u></strong>,0] -&gt; [1,0,<strong><u>0</u></strong>,0,0] -&gt; [1,<strong><u>0</u></strong>,0,0,0] -&gt; [<strong><u>1</u></strong>,0,0,0,0] -&gt; [0,0,0,0,0].</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,0,4,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible valid selections.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> <li>There is at least one element <code>i</code> where <code>nums[i] == 0</code>.</li> </ul>
Array; Prefix Sum; Simulation
TypeScript
function countValidSelections(nums: number[]): number { const s = nums.reduce((acc, x) => acc + x, 0); let [ans, l] = [0, 0]; for (const x of nums) { if (x) { l += x; } else if (l * 2 === s) { ans += 2; } else if (Math.abs(l * 2 - s) <= 1) { ++ans; } } return ans; }
3,355
Zero Array Transformation I
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each <code>queries[i]</code>:</p> <ul> <li>Select a <span data-keyword="subset">subset</span> of indices within the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code>.</li> <li>Decrement the values at the selected indices by 1.</li> </ul> <p>A <strong>Zero Array</strong> is an array where all elements are equal to 0.</p> <p>Return <code>true</code> if it is <em>possible</em> to transform <code>nums</code> into a <strong>Zero Array </strong>after processing all the queries sequentially, 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">nums = [1,0,1], queries = [[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[0, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3],[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[1, 2, 3]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[4, 2, 1, 0]</code>.</li> </ul> </li> <li><strong>For i = 1:</strong> <ul> <li>Select the subset of indices as <code>[0, 1, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[3, 1, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Array; Prefix Sum
C++
class Solution { public: bool isZeroArray(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); int d[n + 1]; memset(d, 0, sizeof(d)); for (const auto& q : queries) { int l = q[0], r = q[1]; ++d[l]; --d[r + 1]; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; } };
3,355
Zero Array Transformation I
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each <code>queries[i]</code>:</p> <ul> <li>Select a <span data-keyword="subset">subset</span> of indices within the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code>.</li> <li>Decrement the values at the selected indices by 1.</li> </ul> <p>A <strong>Zero Array</strong> is an array where all elements are equal to 0.</p> <p>Return <code>true</code> if it is <em>possible</em> to transform <code>nums</code> into a <strong>Zero Array </strong>after processing all the queries sequentially, 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">nums = [1,0,1], queries = [[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[0, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3],[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[1, 2, 3]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[4, 2, 1, 0]</code>.</li> </ul> </li> <li><strong>For i = 1:</strong> <ul> <li>Select the subset of indices as <code>[0, 1, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[3, 1, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Array; Prefix Sum
Go
func isZeroArray(nums []int, queries [][]int) bool { d := make([]int, len(nums)+1) for _, q := range queries { l, r := q[0], q[1] d[l]++ d[r+1]-- } s := 0 for i, x := range nums { s += d[i] if x > s { return false } } return true }
3,355
Zero Array Transformation I
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each <code>queries[i]</code>:</p> <ul> <li>Select a <span data-keyword="subset">subset</span> of indices within the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code>.</li> <li>Decrement the values at the selected indices by 1.</li> </ul> <p>A <strong>Zero Array</strong> is an array where all elements are equal to 0.</p> <p>Return <code>true</code> if it is <em>possible</em> to transform <code>nums</code> into a <strong>Zero Array </strong>after processing all the queries sequentially, 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">nums = [1,0,1], queries = [[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[0, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3],[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[1, 2, 3]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[4, 2, 1, 0]</code>.</li> </ul> </li> <li><strong>For i = 1:</strong> <ul> <li>Select the subset of indices as <code>[0, 1, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[3, 1, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Array; Prefix Sum
Java
class Solution { public boolean isZeroArray(int[] nums, int[][] queries) { int n = nums.length; int[] d = new int[n + 1]; for (var q : queries) { int l = q[0], r = q[1]; ++d[l]; --d[r + 1]; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; } }
3,355
Zero Array Transformation I
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each <code>queries[i]</code>:</p> <ul> <li>Select a <span data-keyword="subset">subset</span> of indices within the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code>.</li> <li>Decrement the values at the selected indices by 1.</li> </ul> <p>A <strong>Zero Array</strong> is an array where all elements are equal to 0.</p> <p>Return <code>true</code> if it is <em>possible</em> to transform <code>nums</code> into a <strong>Zero Array </strong>after processing all the queries sequentially, 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">nums = [1,0,1], queries = [[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[0, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3],[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[1, 2, 3]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[4, 2, 1, 0]</code>.</li> </ul> </li> <li><strong>For i = 1:</strong> <ul> <li>Select the subset of indices as <code>[0, 1, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[3, 1, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Array; Prefix Sum
Python
class Solution: def isZeroArray(self, nums: List[int], queries: List[List[int]]) -> bool: d = [0] * (len(nums) + 1) for l, r in queries: d[l] += 1 d[r + 1] -= 1 s = 0 for x, y in zip(nums, d): s += y if x > s: return False return True
3,355
Zero Array Transformation I
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each <code>queries[i]</code>:</p> <ul> <li>Select a <span data-keyword="subset">subset</span> of indices within the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code>.</li> <li>Decrement the values at the selected indices by 1.</li> </ul> <p>A <strong>Zero Array</strong> is an array where all elements are equal to 0.</p> <p>Return <code>true</code> if it is <em>possible</em> to transform <code>nums</code> into a <strong>Zero Array </strong>after processing all the queries sequentially, 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">nums = [1,0,1], queries = [[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[0, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3],[0,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0:</strong> <ul> <li>Select the subset of indices as <code>[1, 2, 3]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[4, 2, 1, 0]</code>.</li> </ul> </li> <li><strong>For i = 1:</strong> <ul> <li>Select the subset of indices as <code>[0, 1, 2]</code> and decrement the values at these indices by 1.</li> <li>The array will become <code>[3, 1, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Array; Prefix Sum
TypeScript
function isZeroArray(nums: number[], queries: number[][]): boolean { const n = nums.length; const d: number[] = Array(n + 1).fill(0); for (const [l, r] of queries) { ++d[l]; --d[r + 1]; } for (let i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; }
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
C++
class Solution { public: int minZeroArray(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); int d[n + 1]; int m = queries.size(); int l = 0, r = m + 1; auto check = [&](int k) -> bool { memset(d, 0, sizeof(d)); for (int i = 0; i < k; ++i) { int l = queries[i][0], r = queries[i][1], val = queries[i][2]; d[l] += val; d[r + 1] -= val; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; }; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } };
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
Go
func minZeroArray(nums []int, queries [][]int) int { n, m := len(nums), len(queries) l := sort.Search(m+1, func(k int) bool { d := make([]int, n+1) for _, q := range queries[:k] { l, r, val := q[0], q[1], q[2] d[l] += val d[r+1] -= val } s := 0 for i, x := range nums { s += d[i] if x > s { return false } } return true }) if l > m { return -1 } return l }
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
Java
class Solution { private int n; private int[] nums; private int[][] queries; public int minZeroArray(int[] nums, int[][] queries) { this.nums = nums; this.queries = queries; n = nums.length; int m = queries.length; int l = 0, r = m + 1; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } private boolean check(int k) { int[] d = new int[n + 1]; for (int i = 0; i < k; ++i) { int l = queries[i][0], r = queries[i][1], val = queries[i][2]; d[l] += val; d[r + 1] -= val; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; } }
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
Python
class Solution: def minZeroArray(self, nums: List[int], queries: List[List[int]]) -> int: def check(k: int) -> bool: d = [0] * (len(nums) + 1) for l, r, val in queries[:k]: d[l] += val d[r + 1] -= val s = 0 for x, y in zip(nums, d): s += y if x > s: return False return True m = len(queries) l = bisect_left(range(m + 1), True, key=check) return -1 if l > m else l
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
Rust
impl Solution { pub fn min_zero_array(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> i32 { let n = nums.len(); let m = queries.len(); let mut d: Vec<i64> = vec![0; n + 1]; let (mut l, mut r) = (0_usize, m + 1); let check = |k: usize, d: &mut Vec<i64>| -> bool { d.fill(0); for i in 0..k { let (l, r, val) = ( queries[i][0] as usize, queries[i][1] as usize, queries[i][2] as i64, ); d[l] += val; d[r + 1] -= val; } let mut s: i64 = 0; for i in 0..n { s += d[i]; if nums[i] as i64 > s { return false; } } true }; while l < r { let mid = (l + r) >> 1; if check(mid, &mut d) { r = mid; } else { l = mid + 1; } } if l > m { -1 } else { l as i32 } } }
3,356
Zero Array Transformation II
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>, val<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong> <code>val<sub>i</sub></code>.</li> <li>The amount by which each value is decremented<!-- notionvc: b232c9d9-a32d-448c-85b8-b637de593c11 --> can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>minimum</strong> possible <strong>non-negative</strong> value of <code>k</code>, such that after processing the first <code>k</code> queries in <strong>sequence</strong>, <code>nums</code> becomes a <strong>Zero Array</strong>. If no such <code>k</code> exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[1, 0, 1]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val = 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 0, 1]</code> respectively.</li> <li>The array will become <code>[0, 0, 0]</code>, which is a Zero Array. Therefore, the minimum value of <code>k</code> is 2.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><strong>For i = 0 (l = 1, r = 3, val = 2):</strong> <ul> <li>Decrement values at indices <code>[1, 2, 3]</code> by <code>[2, 2, 1]</code> respectively.</li> <li>The array will become <code>[4, 1, 0, 0]</code>.</li> </ul> </li> <li><strong>For i = 1 (l = 0, r = 2, val<span style="font-size: 13.3333px;"> </span>= 1):</strong> <ul> <li>Decrement values at indices <code>[0, 1, 2]</code> by <code>[1, 1, 0]</code> respectively.</li> <li>The array will become <code>[3, 0, 0, 0]</code>, which is not a Zero Array.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 3</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> <li><code>1 &lt;= val<sub>i</sub> &lt;= 5</code></li> </ul>
Array; Binary Search; Prefix Sum
TypeScript
function minZeroArray(nums: number[], queries: number[][]): number { const [n, m] = [nums.length, queries.length]; const d: number[] = Array(n + 1); let [l, r] = [0, m + 1]; const check = (k: number): boolean => { d.fill(0); for (let i = 0; i < k; ++i) { const [l, r, val] = queries[i]; d[l] += val; d[r + 1] -= val; } for (let i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; }
3,358
Books with NULL Ratings
Easy
<p>Table: <code>books</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | book_id | int | | title | varchar | | author | varchar | | published_year | int | | rating | decimal | +----------------+---------+ book_id is the unique key for this table. Each row of this table contains information about a book including its unique ID, title, author, publication year, and rating. rating can be NULL, indicating that the book hasn&#39;t been rated yet. </pre> <p>Write a solution to find all books that have not been rated yet (i.e., have a <strong>NULL</strong> rating).</p> <p>Return <em>the result table</em> <em>ordered by</em> <code>book_id</code> in <strong>ascending</strong> order.</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>books table:</p> <pre class="example-io"> +---------+------------------------+------------------+----------------+--------+ | book_id | title | author | published_year | rating | +---------+------------------------+------------------+----------------+--------+ | 1 | The Great Gatsby | F. Scott | 1925 | 4.5 | | 2 | To Kill a Mockingbird | Harper Lee | 1960 | NULL | | 3 | Pride and Prejudice | Jane Austen | 1813 | 4.8 | | 4 | The Catcher in the Rye | J.D. Salinger | 1951 | NULL | | 5 | Animal Farm | George Orwell | 1945 | 4.2 | | 6 | Lord of the Flies | William Golding | 1954 | NULL | +---------+------------------------+------------------+----------------+--------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------------+------------------+----------------+ | book_id | title | author | published_year | +---------+------------------------+------------------+----------------+ | 2 | To Kill a Mockingbird | Harper Lee | 1960 | | 4 | The Catcher in the Rye | J.D. Salinger | 1951 | | 6 | Lord of the Flies | William Golding | 1954 | +---------+------------------------+------------------+----------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>The books with book_id 2, 4, and 6 have NULL ratings.</li> <li>These books are included in the result table.</li> <li>The other books (book_id 1, 3, and 5) have ratings and are not included.</li> </ul> The result is ordered by book_id in ascending order</div>
Database
Python
import pandas as pd def find_unrated_books(books: pd.DataFrame) -> pd.DataFrame: unrated_books = books[books["rating"].isnull()] return unrated_books[["book_id", "title", "author", "published_year"]].sort_values( by="book_id" )
3,358
Books with NULL Ratings
Easy
<p>Table: <code>books</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | book_id | int | | title | varchar | | author | varchar | | published_year | int | | rating | decimal | +----------------+---------+ book_id is the unique key for this table. Each row of this table contains information about a book including its unique ID, title, author, publication year, and rating. rating can be NULL, indicating that the book hasn&#39;t been rated yet. </pre> <p>Write a solution to find all books that have not been rated yet (i.e., have a <strong>NULL</strong> rating).</p> <p>Return <em>the result table</em> <em>ordered by</em> <code>book_id</code> in <strong>ascending</strong> order.</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>books table:</p> <pre class="example-io"> +---------+------------------------+------------------+----------------+--------+ | book_id | title | author | published_year | rating | +---------+------------------------+------------------+----------------+--------+ | 1 | The Great Gatsby | F. Scott | 1925 | 4.5 | | 2 | To Kill a Mockingbird | Harper Lee | 1960 | NULL | | 3 | Pride and Prejudice | Jane Austen | 1813 | 4.8 | | 4 | The Catcher in the Rye | J.D. Salinger | 1951 | NULL | | 5 | Animal Farm | George Orwell | 1945 | 4.2 | | 6 | Lord of the Flies | William Golding | 1954 | NULL | +---------+------------------------+------------------+----------------+--------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------------+------------------+----------------+ | book_id | title | author | published_year | +---------+------------------------+------------------+----------------+ | 2 | To Kill a Mockingbird | Harper Lee | 1960 | | 4 | The Catcher in the Rye | J.D. Salinger | 1951 | | 6 | Lord of the Flies | William Golding | 1954 | +---------+------------------------+------------------+----------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>The books with book_id 2, 4, and 6 have NULL ratings.</li> <li>These books are included in the result table.</li> <li>The other books (book_id 1, 3, and 5) have ratings and are not included.</li> </ul> The result is ordered by book_id in ascending order</div>
Database
SQL
# Write your MySQL query statement below SELECT book_id, title, author, published_year FROM books WHERE rating IS NULL ORDER BY 1;
3,360
Stone Removal Game
Easy
<p>Alice and Bob are playing a game where they take turns removing stones from a pile, with <em>Alice going first</em>.</p> <ul> <li>Alice starts by removing <strong>exactly</strong> 10 stones on her first turn.</li> <li>For each subsequent turn, each player removes <strong>exactly</strong> 1 fewer<strong> </strong>stone<strong> </strong>than the previous opponent.</li> </ul> <p>The player who cannot make a move loses the game.</p> <p>Given a positive integer <code>n</code>, return <code>true</code> if Alice wins the game and <code>false</code> otherwise.</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 = 12</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice removes 10 stones on her first turn, leaving 2 stones for Bob.</li> <li>Bob cannot remove 9 stones, so Alice wins.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice cannot remove 10 stones, so Alice loses.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Simulation
C++
class Solution { public: bool canAliceWin(int n) { int x = 10, k = 0; while (n >= x) { n -= x; --x; ++k; } return k % 2; } };
3,360
Stone Removal Game
Easy
<p>Alice and Bob are playing a game where they take turns removing stones from a pile, with <em>Alice going first</em>.</p> <ul> <li>Alice starts by removing <strong>exactly</strong> 10 stones on her first turn.</li> <li>For each subsequent turn, each player removes <strong>exactly</strong> 1 fewer<strong> </strong>stone<strong> </strong>than the previous opponent.</li> </ul> <p>The player who cannot make a move loses the game.</p> <p>Given a positive integer <code>n</code>, return <code>true</code> if Alice wins the game and <code>false</code> otherwise.</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 = 12</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice removes 10 stones on her first turn, leaving 2 stones for Bob.</li> <li>Bob cannot remove 9 stones, so Alice wins.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice cannot remove 10 stones, so Alice loses.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Simulation
Go
func canAliceWin(n int) bool { x, k := 10, 0 for n >= x { n -= x x-- k++ } return k%2 == 1 }
3,360
Stone Removal Game
Easy
<p>Alice and Bob are playing a game where they take turns removing stones from a pile, with <em>Alice going first</em>.</p> <ul> <li>Alice starts by removing <strong>exactly</strong> 10 stones on her first turn.</li> <li>For each subsequent turn, each player removes <strong>exactly</strong> 1 fewer<strong> </strong>stone<strong> </strong>than the previous opponent.</li> </ul> <p>The player who cannot make a move loses the game.</p> <p>Given a positive integer <code>n</code>, return <code>true</code> if Alice wins the game and <code>false</code> otherwise.</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 = 12</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice removes 10 stones on her first turn, leaving 2 stones for Bob.</li> <li>Bob cannot remove 9 stones, so Alice wins.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice cannot remove 10 stones, so Alice loses.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Simulation
Java
class Solution { public boolean canAliceWin(int n) { int x = 10, k = 0; while (n >= x) { n -= x; --x; ++k; } return k % 2 == 1; } }
3,360
Stone Removal Game
Easy
<p>Alice and Bob are playing a game where they take turns removing stones from a pile, with <em>Alice going first</em>.</p> <ul> <li>Alice starts by removing <strong>exactly</strong> 10 stones on her first turn.</li> <li>For each subsequent turn, each player removes <strong>exactly</strong> 1 fewer<strong> </strong>stone<strong> </strong>than the previous opponent.</li> </ul> <p>The player who cannot make a move loses the game.</p> <p>Given a positive integer <code>n</code>, return <code>true</code> if Alice wins the game and <code>false</code> otherwise.</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 = 12</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice removes 10 stones on her first turn, leaving 2 stones for Bob.</li> <li>Bob cannot remove 9 stones, so Alice wins.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice cannot remove 10 stones, so Alice loses.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Simulation
Python
class Solution: def canAliceWin(self, n: int) -> bool: x, k = 10, 0 while n >= x: n -= x x -= 1 k += 1 return k % 2 == 1
3,360
Stone Removal Game
Easy
<p>Alice and Bob are playing a game where they take turns removing stones from a pile, with <em>Alice going first</em>.</p> <ul> <li>Alice starts by removing <strong>exactly</strong> 10 stones on her first turn.</li> <li>For each subsequent turn, each player removes <strong>exactly</strong> 1 fewer<strong> </strong>stone<strong> </strong>than the previous opponent.</li> </ul> <p>The player who cannot make a move loses the game.</p> <p>Given a positive integer <code>n</code>, return <code>true</code> if Alice wins the game and <code>false</code> otherwise.</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 = 12</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice removes 10 stones on her first turn, leaving 2 stones for Bob.</li> <li>Bob cannot remove 9 stones, so Alice wins.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice cannot remove 10 stones, so Alice loses.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> </ul>
Math; Simulation
TypeScript
function canAliceWin(n: number): boolean { let [x, k] = [10, 0]; while (n >= x) { n -= x; --x; ++k; } return k % 2 === 1; }
3,361
Shift Distance Between Two Strings
Medium
<p>You are given two strings <code>s</code> and <code>t</code> of the same length, and two integer arrays <code>nextCost</code> and <code>previousCost</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>s</code>, and perform <strong>either one</strong> of the following actions:</p> <ul> <li>Shift <code>s[i]</code> to the next letter in the alphabet. If <code>s[i] == &#39;z&#39;</code>, you should replace it with <code>&#39;a&#39;</code>. This operation costs <code>nextCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> <li>Shift <code>s[i]</code> to the previous letter in the alphabet. If <code>s[i] == &#39;a&#39;</code>, you should replace it with <code>&#39;z&#39;</code>. This operation costs <code>previousCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> </ul> <p>The <strong>shift distance</strong> is the <strong>minimum</strong> total cost of operations required to transform <code>s</code> into <code>t</code>.</p> <p>Return the <strong>shift distance</strong> from <code>s</code> to <code>t</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;abab&quot;, t = &quot;baba&quot;, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 25 times to the next character for a total cost of 0.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 25 times to the next character for a total cost of 0.</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;leet&quot;, t = &quot;code&quot;, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 9 times to the previous character for a total cost of 9.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 10 times to the next character for a total cost of 10.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 1 time to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 11 times to the next character for a total cost of 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li><code>nextCost.length == previousCost.length == 26</code></li> <li><code>0 &lt;= nextCost[i], previousCost[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; String; Prefix Sum
C++
class Solution { public: long long shiftDistance(string s, string t, vector<int>& nextCost, vector<int>& previousCost) { int m = 26; vector<long long> s1((m << 1) + 1); vector<long long> s2((m << 1) + 1); for (int i = 0; i < (m << 1); ++i) { s1[i + 1] = s1[i] + nextCost[i % m]; s2[i + 1] = s2[i] + previousCost[(i + 1) % m]; } long long ans = 0; for (int i = 0; i < s.size(); ++i) { int x = s[i] - 'a'; int y = t[i] - 'a'; long long c1 = s1[y + (y < x ? m : 0)] - s1[x]; long long c2 = s2[x + (x < y ? m : 0)] - s2[y]; ans += min(c1, c2); } return ans; } };
3,361
Shift Distance Between Two Strings
Medium
<p>You are given two strings <code>s</code> and <code>t</code> of the same length, and two integer arrays <code>nextCost</code> and <code>previousCost</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>s</code>, and perform <strong>either one</strong> of the following actions:</p> <ul> <li>Shift <code>s[i]</code> to the next letter in the alphabet. If <code>s[i] == &#39;z&#39;</code>, you should replace it with <code>&#39;a&#39;</code>. This operation costs <code>nextCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> <li>Shift <code>s[i]</code> to the previous letter in the alphabet. If <code>s[i] == &#39;a&#39;</code>, you should replace it with <code>&#39;z&#39;</code>. This operation costs <code>previousCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> </ul> <p>The <strong>shift distance</strong> is the <strong>minimum</strong> total cost of operations required to transform <code>s</code> into <code>t</code>.</p> <p>Return the <strong>shift distance</strong> from <code>s</code> to <code>t</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;abab&quot;, t = &quot;baba&quot;, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 25 times to the next character for a total cost of 0.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 25 times to the next character for a total cost of 0.</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;leet&quot;, t = &quot;code&quot;, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 9 times to the previous character for a total cost of 9.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 10 times to the next character for a total cost of 10.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 1 time to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 11 times to the next character for a total cost of 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li><code>nextCost.length == previousCost.length == 26</code></li> <li><code>0 &lt;= nextCost[i], previousCost[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; String; Prefix Sum
Go
func shiftDistance(s string, t string, nextCost []int, previousCost []int) (ans int64) { m := 26 s1 := make([]int64, (m<<1)+1) s2 := make([]int64, (m<<1)+1) for i := 0; i < (m << 1); i++ { s1[i+1] = s1[i] + int64(nextCost[i%m]) s2[i+1] = s2[i] + int64(previousCost[(i+1)%m]) } for i := 0; i < len(s); i++ { x := int(s[i] - 'a') y := int(t[i] - 'a') z := y if y < x { z += m } c1 := s1[z] - s1[x] z = x if x < y { z += m } c2 := s2[z] - s2[y] ans += min(c1, c2) } return }
3,361
Shift Distance Between Two Strings
Medium
<p>You are given two strings <code>s</code> and <code>t</code> of the same length, and two integer arrays <code>nextCost</code> and <code>previousCost</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>s</code>, and perform <strong>either one</strong> of the following actions:</p> <ul> <li>Shift <code>s[i]</code> to the next letter in the alphabet. If <code>s[i] == &#39;z&#39;</code>, you should replace it with <code>&#39;a&#39;</code>. This operation costs <code>nextCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> <li>Shift <code>s[i]</code> to the previous letter in the alphabet. If <code>s[i] == &#39;a&#39;</code>, you should replace it with <code>&#39;z&#39;</code>. This operation costs <code>previousCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> </ul> <p>The <strong>shift distance</strong> is the <strong>minimum</strong> total cost of operations required to transform <code>s</code> into <code>t</code>.</p> <p>Return the <strong>shift distance</strong> from <code>s</code> to <code>t</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;abab&quot;, t = &quot;baba&quot;, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 25 times to the next character for a total cost of 0.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 25 times to the next character for a total cost of 0.</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;leet&quot;, t = &quot;code&quot;, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 9 times to the previous character for a total cost of 9.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 10 times to the next character for a total cost of 10.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 1 time to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 11 times to the next character for a total cost of 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li><code>nextCost.length == previousCost.length == 26</code></li> <li><code>0 &lt;= nextCost[i], previousCost[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; String; Prefix Sum
Java
class Solution { public long shiftDistance(String s, String t, int[] nextCost, int[] previousCost) { int m = 26; long[] s1 = new long[(m << 1) + 1]; long[] s2 = new long[(m << 1) + 1]; for (int i = 0; i < (m << 1); i++) { s1[i + 1] = s1[i] + nextCost[i % m]; s2[i + 1] = s2[i] + previousCost[(i + 1) % m]; } long ans = 0; for (int i = 0; i < s.length(); i++) { int x = s.charAt(i) - 'a'; int y = t.charAt(i) - 'a'; long c1 = s1[y + (y < x ? m : 0)] - s1[x]; long c2 = s2[x + (x < y ? m : 0)] - s2[y]; ans += Math.min(c1, c2); } return ans; } }
3,361
Shift Distance Between Two Strings
Medium
<p>You are given two strings <code>s</code> and <code>t</code> of the same length, and two integer arrays <code>nextCost</code> and <code>previousCost</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>s</code>, and perform <strong>either one</strong> of the following actions:</p> <ul> <li>Shift <code>s[i]</code> to the next letter in the alphabet. If <code>s[i] == &#39;z&#39;</code>, you should replace it with <code>&#39;a&#39;</code>. This operation costs <code>nextCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> <li>Shift <code>s[i]</code> to the previous letter in the alphabet. If <code>s[i] == &#39;a&#39;</code>, you should replace it with <code>&#39;z&#39;</code>. This operation costs <code>previousCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> </ul> <p>The <strong>shift distance</strong> is the <strong>minimum</strong> total cost of operations required to transform <code>s</code> into <code>t</code>.</p> <p>Return the <strong>shift distance</strong> from <code>s</code> to <code>t</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;abab&quot;, t = &quot;baba&quot;, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 25 times to the next character for a total cost of 0.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 25 times to the next character for a total cost of 0.</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;leet&quot;, t = &quot;code&quot;, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 9 times to the previous character for a total cost of 9.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 10 times to the next character for a total cost of 10.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 1 time to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 11 times to the next character for a total cost of 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li><code>nextCost.length == previousCost.length == 26</code></li> <li><code>0 &lt;= nextCost[i], previousCost[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; String; Prefix Sum
Python
class Solution: def shiftDistance( self, s: str, t: str, nextCost: List[int], previousCost: List[int] ) -> int: m = 26 s1 = [0] * (m << 1 | 1) s2 = [0] * (m << 1 | 1) for i in range(m << 1): s1[i + 1] = s1[i] + nextCost[i % m] s2[i + 1] = s2[i] + previousCost[(i + 1) % m] ans = 0 for a, b in zip(s, t): x, y = ord(a) - ord("a"), ord(b) - ord("a") c1 = s1[y + m if y < x else y] - s1[x] c2 = s2[x + m if x < y else x] - s2[y] ans += min(c1, c2) return ans
3,361
Shift Distance Between Two Strings
Medium
<p>You are given two strings <code>s</code> and <code>t</code> of the same length, and two integer arrays <code>nextCost</code> and <code>previousCost</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>s</code>, and perform <strong>either one</strong> of the following actions:</p> <ul> <li>Shift <code>s[i]</code> to the next letter in the alphabet. If <code>s[i] == &#39;z&#39;</code>, you should replace it with <code>&#39;a&#39;</code>. This operation costs <code>nextCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> <li>Shift <code>s[i]</code> to the previous letter in the alphabet. If <code>s[i] == &#39;a&#39;</code>, you should replace it with <code>&#39;z&#39;</code>. This operation costs <code>previousCost[j]</code> where <code>j</code> is the index of <code>s[i]</code> in the alphabet.</li> </ul> <p>The <strong>shift distance</strong> is the <strong>minimum</strong> total cost of operations required to transform <code>s</code> into <code>t</code>.</p> <p>Return the <strong>shift distance</strong> from <code>s</code> to <code>t</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;abab&quot;, t = &quot;baba&quot;, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 25 times to the next character for a total cost of 0.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 25 times to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 25 times to the next character for a total cost of 0.</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;leet&quot;, t = &quot;code&quot;, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We choose index <code>i = 0</code> and shift <code>s[0]</code> 9 times to the previous character for a total cost of 9.</li> <li>We choose index <code>i = 1</code> and shift <code>s[1]</code> 10 times to the next character for a total cost of 10.</li> <li>We choose index <code>i = 2</code> and shift <code>s[2]</code> 1 time to the previous character for a total cost of 1.</li> <li>We choose index <code>i = 3</code> and shift <code>s[3]</code> 11 times to the next character for a total cost of 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li><code>nextCost.length == previousCost.length == 26</code></li> <li><code>0 &lt;= nextCost[i], previousCost[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; String; Prefix Sum
TypeScript
function shiftDistance(s: string, t: string, nextCost: number[], previousCost: number[]): number { const m = 26; const s1: number[] = Array((m << 1) + 1).fill(0); const s2: number[] = Array((m << 1) + 1).fill(0); for (let i = 0; i < m << 1; i++) { s1[i + 1] = s1[i] + nextCost[i % m]; s2[i + 1] = s2[i] + previousCost[(i + 1) % m]; } let ans = 0; const a = 'a'.charCodeAt(0); for (let i = 0; i < s.length; i++) { const x = s.charCodeAt(i) - a; const y = t.charCodeAt(i) - a; const c1 = s1[y + (y < x ? m : 0)] - s1[x]; const c2 = s2[x + (x < y ? m : 0)] - s2[y]; ans += Math.min(c1, c2); } return ans; }
3,362
Zero Array Transformation III
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong><strong> </strong>1.</li> <li>The amount by which the value is decremented can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>maximum </strong>number of elements that can be removed from <code>queries</code>, such that <code>nums</code> can still be converted to a <strong>zero array</strong> using the <em>remaining</em> queries. If it is not possible to convert <code>nums</code> to a <strong>zero array</strong>, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>After removing <code>queries[2]</code>, <code>nums</code> can still be converted to a zero array.</p> <ul> <li>Using <code>queries[0]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</li> <li>Using <code>queries[1]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</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,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can remove <code>queries[2]</code> and <code>queries[3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> cannot be converted to a zero array even after using all the queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Greedy; Array; Prefix Sum; Sorting; Heap (Priority Queue)
C++
class Solution { public: int maxRemoval(vector<int>& nums, vector<vector<int>>& queries) { sort(queries.begin(), queries.end()); priority_queue<int> pq; int n = nums.size(); vector<int> d(n + 1, 0); int s = 0, j = 0; for (int i = 0; i < n; ++i) { s += d[i]; while (j < queries.size() && queries[j][0] <= i) { pq.push(queries[j][1]); ++j; } while (s < nums[i] && !pq.empty() && pq.top() >= i) { ++s; int end = pq.top(); pq.pop(); --d[end + 1]; } if (s < nums[i]) { return -1; } } return pq.size(); } };
3,362
Zero Array Transformation III
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong><strong> </strong>1.</li> <li>The amount by which the value is decremented can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>maximum </strong>number of elements that can be removed from <code>queries</code>, such that <code>nums</code> can still be converted to a <strong>zero array</strong> using the <em>remaining</em> queries. If it is not possible to convert <code>nums</code> to a <strong>zero array</strong>, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>After removing <code>queries[2]</code>, <code>nums</code> can still be converted to a zero array.</p> <ul> <li>Using <code>queries[0]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</li> <li>Using <code>queries[1]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</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,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can remove <code>queries[2]</code> and <code>queries[3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> cannot be converted to a zero array even after using all the queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Greedy; Array; Prefix Sum; Sorting; Heap (Priority Queue)
Go
func maxRemoval(nums []int, queries [][]int) int { sort.Slice(queries, func(i, j int) bool { return queries[i][0] < queries[j][0] }) var h hp heap.Init(&h) n := len(nums) d := make([]int, n+1) s, j := 0, 0 for i := 0; i < n; i++ { s += d[i] for j < len(queries) && queries[j][0] <= i { heap.Push(&h, queries[j][1]) j++ } for s < nums[i] && h.Len() > 0 && h.IntSlice[0] >= i { s++ end := heap.Pop(&h).(int) if end+1 < len(d) { d[end+1]-- } } if s < nums[i] { return -1 } } return h.Len() } 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,362
Zero Array Transformation III
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong><strong> </strong>1.</li> <li>The amount by which the value is decremented can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>maximum </strong>number of elements that can be removed from <code>queries</code>, such that <code>nums</code> can still be converted to a <strong>zero array</strong> using the <em>remaining</em> queries. If it is not possible to convert <code>nums</code> to a <strong>zero array</strong>, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>After removing <code>queries[2]</code>, <code>nums</code> can still be converted to a zero array.</p> <ul> <li>Using <code>queries[0]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</li> <li>Using <code>queries[1]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</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,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can remove <code>queries[2]</code> and <code>queries[3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> cannot be converted to a zero array even after using all the queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Greedy; Array; Prefix Sum; Sorting; Heap (Priority Queue)
Java
class Solution { public int maxRemoval(int[] nums, int[][] queries) { Arrays.sort(queries, (a, b) -> Integer.compare(a[0], b[0])); PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); int n = nums.length; int[] d = new int[n + 1]; int s = 0, j = 0; for (int i = 0; i < n; i++) { s += d[i]; while (j < queries.length && queries[j][0] <= i) { pq.offer(queries[j][1]); j++; } while (s < nums[i] && !pq.isEmpty() && pq.peek() >= i) { s++; d[pq.poll() + 1]--; } if (s < nums[i]) { return -1; } } return pq.size(); } }
3,362
Zero Array Transformation III
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong><strong> </strong>1.</li> <li>The amount by which the value is decremented can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>maximum </strong>number of elements that can be removed from <code>queries</code>, such that <code>nums</code> can still be converted to a <strong>zero array</strong> using the <em>remaining</em> queries. If it is not possible to convert <code>nums</code> to a <strong>zero array</strong>, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>After removing <code>queries[2]</code>, <code>nums</code> can still be converted to a zero array.</p> <ul> <li>Using <code>queries[0]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</li> <li>Using <code>queries[1]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</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,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can remove <code>queries[2]</code> and <code>queries[3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> cannot be converted to a zero array even after using all the queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Greedy; Array; Prefix Sum; Sorting; Heap (Priority Queue)
Python
class Solution: def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int: queries.sort() pq = [] d = [0] * (len(nums) + 1) s = j = 0 for i, x in enumerate(nums): s += d[i] while j < len(queries) and queries[j][0] <= i: heappush(pq, -queries[j][1]) j += 1 while s < x and pq and -pq[0] >= i: s += 1 d[-heappop(pq) + 1] -= 1 if s < x: return -1 return len(pq)
3,362
Zero Array Transformation III
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a 2D array <code>queries</code> where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>Each <code>queries[i]</code> represents the following action on <code>nums</code>:</p> <ul> <li>Decrement the value at each index in the range <code>[l<sub>i</sub>, r<sub>i</sub>]</code> in <code>nums</code> by <strong>at most</strong><strong> </strong>1.</li> <li>The amount by which the value is decremented can be chosen <strong>independently</strong> for each index.</li> </ul> <p>A <strong>Zero Array</strong> is an array with all its elements equal to 0.</p> <p>Return the <strong>maximum </strong>number of elements that can be removed from <code>queries</code>, such that <code>nums</code> can still be converted to a <strong>zero array</strong> using the <em>remaining</em> queries. If it is not possible to convert <code>nums</code> to a <strong>zero array</strong>, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>After removing <code>queries[2]</code>, <code>nums</code> can still be converted to a zero array.</p> <ul> <li>Using <code>queries[0]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</li> <li>Using <code>queries[1]</code>, decrement <code>nums[0]</code> and <code>nums[2]</code> by 1 and <code>nums[1]</code> by 0.</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,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can remove <code>queries[2]</code> and <code>queries[3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [[0,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> cannot be converted to a zero array even after using all the queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; nums.length</code></li> </ul>
Greedy; Array; Prefix Sum; Sorting; Heap (Priority Queue)
TypeScript
function maxRemoval(nums: number[], queries: number[][]): number { queries.sort((a, b) => a[0] - b[0]); const pq = new MaxPriorityQueue<number>(); const n = nums.length; const d: number[] = Array(n + 1).fill(0); let [s, j] = [0, 0]; for (let i = 0; i < n; i++) { s += d[i]; while (j < queries.length && queries[j][0] <= i) { pq.enqueue(queries[j][1]); j++; } while (s < nums[i] && !pq.isEmpty() && pq.front() >= i) { s++; d[pq.dequeue() + 1]--; } if (s < nums[i]) { return -1; } } return pq.size(); }
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maxCollectedFruits(vector<vector<int>>& fruits) { int n = fruits.size(); const int inf = 1 << 29; vector<vector<int>> f(n, vector<int>(n, -inf)); f[0][n - 1] = fruits[0][n - 1]; for (int i = 1; i < n; i++) { for (int j = i + 1; j < n; j++) { f[i][j] = max(f[i - 1][j], f[i - 1][j - 1]) + fruits[i][j]; if (j + 1 < n) { f[i][j] = max(f[i][j], f[i - 1][j + 1] + fruits[i][j]); } } } f[n - 1][0] = fruits[n - 1][0]; for (int j = 1; j < n; j++) { for (int i = j + 1; i < n; i++) { f[i][j] = max(f[i][j - 1], f[i - 1][j - 1]) + fruits[i][j]; if (i + 1 < n) { f[i][j] = max(f[i][j], f[i + 1][j - 1] + fruits[i][j]); } } } int ans = f[n - 2][n - 1] + f[n - 1][n - 2]; for (int i = 0; i < n; i++) { ans += fruits[i][i]; } return ans; } };
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Go
func maxCollectedFruits(fruits [][]int) int { n := len(fruits) const inf = 1 << 29 f := make([][]int, n) for i := range f { f[i] = make([]int, n) for j := range f[i] { f[i][j] = -inf } } f[0][n-1] = fruits[0][n-1] for i := 1; i < n; i++ { for j := i + 1; j < n; j++ { f[i][j] = max(f[i-1][j], f[i-1][j-1]) + fruits[i][j] if j+1 < n { f[i][j] = max(f[i][j], f[i-1][j+1]+fruits[i][j]) } } } f[n-1][0] = fruits[n-1][0] for j := 1; j < n; j++ { for i := j + 1; i < n; i++ { f[i][j] = max(f[i][j-1], f[i-1][j-1]) + fruits[i][j] if i+1 < n { f[i][j] = max(f[i][j], f[i+1][j-1]+fruits[i][j]) } } } ans := f[n-2][n-1] + f[n-1][n-2] for i := 0; i < n; i++ { ans += fruits[i][i] } return ans }
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int maxCollectedFruits(int[][] fruits) { int n = fruits.length; final int inf = 1 << 29; int[][] f = new int[n][n]; for (var row : f) { Arrays.fill(row, -inf); } f[0][n - 1] = fruits[0][n - 1]; for (int i = 1; i < n; i++) { for (int j = i + 1; j < n; j++) { f[i][j] = Math.max(f[i - 1][j], f[i - 1][j - 1]) + fruits[i][j]; if (j + 1 < n) { f[i][j] = Math.max(f[i][j], f[i - 1][j + 1] + fruits[i][j]); } } } f[n - 1][0] = fruits[n - 1][0]; for (int j = 1; j < n; j++) { for (int i = j + 1; i < n; i++) { f[i][j] = Math.max(f[i][j - 1], f[i - 1][j - 1]) + fruits[i][j]; if (i + 1 < n) { f[i][j] = Math.max(f[i][j], f[i + 1][j - 1] + fruits[i][j]); } } } int ans = f[n - 2][n - 1] + f[n - 1][n - 2]; for (int i = 0; i < n; i++) { ans += fruits[i][i]; } return ans; } }
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maxCollectedFruits(self, fruits: List[List[int]]) -> int: n = len(fruits) f = [[-inf] * n for _ in range(n)] f[0][n - 1] = fruits[0][n - 1] for i in range(1, n): for j in range(i + 1, n): f[i][j] = max(f[i - 1][j], f[i - 1][j - 1]) + fruits[i][j] if j + 1 < n: f[i][j] = max(f[i][j], f[i - 1][j + 1] + fruits[i][j]) f[n - 1][0] = fruits[n - 1][0] for j in range(1, n): for i in range(j + 1, n): f[i][j] = max(f[i][j - 1], f[i - 1][j - 1]) + fruits[i][j] if i + 1 < n: f[i][j] = max(f[i][j], f[i + 1][j - 1] + fruits[i][j]) return sum(fruits[i][i] for i in range(n)) + f[n - 2][n - 1] + f[n - 1][n - 2]
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Rust
impl Solution { pub fn max_collected_fruits(fruits: Vec<Vec<i32>>) -> i32 { let n = fruits.len(); let inf = 1 << 29; let mut f = vec![vec![-inf; n]; n]; f[0][n - 1] = fruits[0][n - 1]; for i in 1..n { for j in i + 1..n { f[i][j] = std::cmp::max(f[i - 1][j], f[i - 1][j - 1]) + fruits[i][j]; if j + 1 < n { f[i][j] = std::cmp::max(f[i][j], f[i - 1][j + 1] + fruits[i][j]); } } } f[n - 1][0] = fruits[n - 1][0]; for j in 1..n { for i in j + 1..n { f[i][j] = std::cmp::max(f[i][j - 1], f[i - 1][j - 1]) + fruits[i][j]; if i + 1 < n { f[i][j] = std::cmp::max(f[i][j], f[i + 1][j - 1] + fruits[i][j]); } } } let mut ans = f[n - 2][n - 1] + f[n - 1][n - 2]; for i in 0..n { ans += fruits[i][i]; } ans } }
3,363
Find the Maximum Number of Fruits Collected
Hard
<p>There is a game dungeon comprised of&nbsp;<code>n x n</code> rooms arranged in a grid.</p> <p>You are given a 2D array <code>fruits</code> of size <code>n x n</code>, where <code>fruits[i][j]</code> represents the number of fruits in the room <code>(i, j)</code>. Three children will play in the game dungeon, with <strong>initial</strong> positions at the corner rooms <code>(0, 0)</code>, <code>(0, n - 1)</code>, and <code>(n - 1, 0)</code>.</p> <p>The children will make <strong>exactly</strong> <code>n - 1</code> moves according to the following rules to reach the room <code>(n - 1, n - 1)</code>:</p> <ul> <li>The child starting from <code>(0, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j + 1)</code>, <code>(i + 1, j)</code>, and <code>(i, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(0, n - 1)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i + 1, j - 1)</code>, <code>(i + 1, j)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> <li>The child starting from <code>(n - 1, 0)</code> must move from their current room <code>(i, j)</code> to one of the rooms <code>(i - 1, j + 1)</code>, <code>(i, j + 1)</code>, and <code>(i + 1, j + 1)</code> if the target room exists.</li> </ul> <p>When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.</p> <p>Return the <strong>maximum</strong> number of fruits the children can collect from the dungeon.</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 = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]</span></p> <p><strong>Output:</strong> <span class="example-io">100</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3363.Find%20the%20Maximum%20Number%20of%20Fruits%20Collected/images/clideo_editor_d0b446db9ba448e1a3fcdd0eecdb58d0-ezgifcom-crop.gif" style="width: 250px; height: 210px;" /></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child (green) moves on the path <code>(0,0) -&gt; (1,1) -&gt; (2,2) -&gt; (3, 3)</code>.</li> <li>The 2<sup>nd</sup> child (red) moves on the path <code>(0,3) -&gt; (1,2) -&gt; (2,3) -&gt; (3, 3)</code>.</li> <li>The 3<sup>rd</sup> child (blue) moves on the path <code>(3,0) -&gt; (3,1) -&gt; (3,2) -&gt; (3, 3)</code>.</li> </ul> <p>In total they collect <code>1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100</code> fruits.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">fruits = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>In this example:</p> <ul> <li>The 1<sup>st</sup> child moves on the path <code>(0,0) -&gt; (1,1)</code>.</li> <li>The 2<sup>nd</sup> child moves on the path <code>(0,1) -&gt; (1,1)</code>.</li> <li>The 3<sup>rd</sup> child moves on the path <code>(1,0) -&gt; (1,1)</code>.</li> </ul> <p>In total they collect <code>1 + 1 + 1 + 1 = 4</code> fruits.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == fruits.length == fruits[i].length &lt;= 1000</code></li> <li><code>0 &lt;= fruits[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
TypeScript
function maxCollectedFruits(fruits: number[][]): number { const n = fruits.length; const inf = 1 << 29; const f: number[][] = Array.from({ length: n }, () => Array(n).fill(-inf)); f[0][n - 1] = fruits[0][n - 1]; for (let i = 1; i < n; i++) { for (let j = i + 1; j < n; j++) { f[i][j] = Math.max(f[i - 1][j], f[i - 1][j - 1]) + fruits[i][j]; if (j + 1 < n) { f[i][j] = Math.max(f[i][j], f[i - 1][j + 1] + fruits[i][j]); } } } f[n - 1][0] = fruits[n - 1][0]; for (let j = 1; j < n; j++) { for (let i = j + 1; i < n; i++) { f[i][j] = Math.max(f[i][j - 1], f[i - 1][j - 1]) + fruits[i][j]; if (i + 1 < n) { f[i][j] = Math.max(f[i][j], f[i + 1][j - 1] + fruits[i][j]); } } } let ans = f[n - 2][n - 1] + f[n - 1][n - 2]; for (let i = 0; i < n; i++) { ans += fruits[i][i]; } return ans; }
3,364
Minimum Positive Sum Subarray
Easy
<p>You are given an integer array <code>nums</code> and <strong>two</strong> integers <code>l</code> and <code>r</code>. Your task is to find the <strong>minimum</strong> sum of a <strong>subarray</strong> whose size is between <code>l</code> and <code>r</code> (inclusive) and whose sum is greater than 0.</p> <p>Return the <strong>minimum</strong> sum of such a subarray. If no such subarray exists, return -1.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [3, -2, 1, 4], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of length between <code>l = 2</code> and <code>r = 3</code> where the sum is greater than 0 are:</p> <ul> <li><code>[3, -2]</code> with a sum of 1</li> <li><code>[1, 4]</code> with a sum of 5</li> <li><code>[3, -2, 1]</code> with a sum of 2</li> <li><code>[-2, 1, 4]</code> with a sum of 3</li> </ul> <p>Out of these, the subarray <code>[3, -2]</code> has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2, 2, -3, 1], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no subarray of length between <code>l</code> and <code>r</code> that has a sum greater than 0. So, the answer is -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1, 2, 3, 4], l = 2, r = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1, 2]</code> has a length of 2 and the minimum sum greater than 0. So, the answer is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= l &lt;= r &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum; Sliding Window
C++
class Solution { public: int minimumSumSubarray(vector<int>& nums, int l, int r) { int n = nums.size(); const int inf = INT_MAX; int ans = inf; for (int i = 0; i < n; ++i) { int s = 0; for (int j = i; j < n; ++j) { s += nums[j]; int k = j - i + 1; if (k >= l && k <= r && s > 0) { ans = min(ans, s); } } } return ans == inf ? -1 : ans; } };
3,364
Minimum Positive Sum Subarray
Easy
<p>You are given an integer array <code>nums</code> and <strong>two</strong> integers <code>l</code> and <code>r</code>. Your task is to find the <strong>minimum</strong> sum of a <strong>subarray</strong> whose size is between <code>l</code> and <code>r</code> (inclusive) and whose sum is greater than 0.</p> <p>Return the <strong>minimum</strong> sum of such a subarray. If no such subarray exists, return -1.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [3, -2, 1, 4], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of length between <code>l = 2</code> and <code>r = 3</code> where the sum is greater than 0 are:</p> <ul> <li><code>[3, -2]</code> with a sum of 1</li> <li><code>[1, 4]</code> with a sum of 5</li> <li><code>[3, -2, 1]</code> with a sum of 2</li> <li><code>[-2, 1, 4]</code> with a sum of 3</li> </ul> <p>Out of these, the subarray <code>[3, -2]</code> has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2, 2, -3, 1], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no subarray of length between <code>l</code> and <code>r</code> that has a sum greater than 0. So, the answer is -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1, 2, 3, 4], l = 2, r = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1, 2]</code> has a length of 2 and the minimum sum greater than 0. So, the answer is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= l &lt;= r &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum; Sliding Window
Go
func minimumSumSubarray(nums []int, l int, r int) int { const inf int = 1 << 30 ans := inf for i := range nums { s := 0 for j := i; j < len(nums); j++ { s += nums[j] k := j - i + 1 if k >= l && k <= r && s > 0 { ans = min(ans, s) } } } if ans == inf { return -1 } return ans }
3,364
Minimum Positive Sum Subarray
Easy
<p>You are given an integer array <code>nums</code> and <strong>two</strong> integers <code>l</code> and <code>r</code>. Your task is to find the <strong>minimum</strong> sum of a <strong>subarray</strong> whose size is between <code>l</code> and <code>r</code> (inclusive) and whose sum is greater than 0.</p> <p>Return the <strong>minimum</strong> sum of such a subarray. If no such subarray exists, return -1.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [3, -2, 1, 4], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of length between <code>l = 2</code> and <code>r = 3</code> where the sum is greater than 0 are:</p> <ul> <li><code>[3, -2]</code> with a sum of 1</li> <li><code>[1, 4]</code> with a sum of 5</li> <li><code>[3, -2, 1]</code> with a sum of 2</li> <li><code>[-2, 1, 4]</code> with a sum of 3</li> </ul> <p>Out of these, the subarray <code>[3, -2]</code> has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2, 2, -3, 1], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no subarray of length between <code>l</code> and <code>r</code> that has a sum greater than 0. So, the answer is -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1, 2, 3, 4], l = 2, r = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1, 2]</code> has a length of 2 and the minimum sum greater than 0. So, the answer is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= l &lt;= r &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum; Sliding Window
Java
class Solution { public int minimumSumSubarray(List<Integer> nums, int l, int r) { int n = nums.size(); final int inf = Integer.MAX_VALUE; int ans = inf; for (int i = 0; i < n; ++i) { int s = 0; for (int j = i; j < n; ++j) { s += nums.get(j); int k = j - i + 1; if (k >= l && k <= r && s > 0) { ans = Math.min(ans, s); } } } return ans == inf ? -1 : ans; } }
3,364
Minimum Positive Sum Subarray
Easy
<p>You are given an integer array <code>nums</code> and <strong>two</strong> integers <code>l</code> and <code>r</code>. Your task is to find the <strong>minimum</strong> sum of a <strong>subarray</strong> whose size is between <code>l</code> and <code>r</code> (inclusive) and whose sum is greater than 0.</p> <p>Return the <strong>minimum</strong> sum of such a subarray. If no such subarray exists, return -1.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [3, -2, 1, 4], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of length between <code>l = 2</code> and <code>r = 3</code> where the sum is greater than 0 are:</p> <ul> <li><code>[3, -2]</code> with a sum of 1</li> <li><code>[1, 4]</code> with a sum of 5</li> <li><code>[3, -2, 1]</code> with a sum of 2</li> <li><code>[-2, 1, 4]</code> with a sum of 3</li> </ul> <p>Out of these, the subarray <code>[3, -2]</code> has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2, 2, -3, 1], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no subarray of length between <code>l</code> and <code>r</code> that has a sum greater than 0. So, the answer is -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1, 2, 3, 4], l = 2, r = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1, 2]</code> has a length of 2 and the minimum sum greater than 0. So, the answer is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= l &lt;= r &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum; Sliding Window
Python
class Solution: def minimumSumSubarray(self, nums: List[int], l: int, r: int) -> int: n = len(nums) ans = inf for i in range(n): s = 0 for j in range(i, n): s += nums[j] if l <= j - i + 1 <= r and s > 0: ans = min(ans, s) return -1 if ans == inf else ans
3,364
Minimum Positive Sum Subarray
Easy
<p>You are given an integer array <code>nums</code> and <strong>two</strong> integers <code>l</code> and <code>r</code>. Your task is to find the <strong>minimum</strong> sum of a <strong>subarray</strong> whose size is between <code>l</code> and <code>r</code> (inclusive) and whose sum is greater than 0.</p> <p>Return the <strong>minimum</strong> sum of such a subarray. If no such subarray exists, return -1.</p> <p>A <strong>subarray</strong> is a contiguous <b>non-empty</b> sequence of elements within an 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 = [3, -2, 1, 4], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of length between <code>l = 2</code> and <code>r = 3</code> where the sum is greater than 0 are:</p> <ul> <li><code>[3, -2]</code> with a sum of 1</li> <li><code>[1, 4]</code> with a sum of 5</li> <li><code>[3, -2, 1]</code> with a sum of 2</li> <li><code>[-2, 1, 4]</code> with a sum of 3</li> </ul> <p>Out of these, the subarray <code>[3, -2]</code> has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2, 2, -3, 1], l = 2, r = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>There is no subarray of length between <code>l</code> and <code>r</code> that has a sum greater than 0. So, the answer is -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1, 2, 3, 4], l = 2, r = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1, 2]</code> has a length of 2 and the minimum sum greater than 0. So, the answer is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= l &lt;= r &lt;= nums.length</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum; Sliding Window
TypeScript
function minimumSumSubarray(nums: number[], l: number, r: number): number { const n = nums.length; let ans = Infinity; for (let i = 0; i < n; ++i) { let s = 0; for (let j = i; j < n; ++j) { s += nums[j]; const k = j - i + 1; if (k >= l && k <= r && s > 0) { ans = Math.min(ans, s); } } } return ans == Infinity ? -1 : ans; }
3,365
Rearrange K Substrings to Form Target String
Medium
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p> <p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p> <p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p> <p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p> <p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 2: <code>[&quot;ab&quot;, &quot;cd&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;cd&quot;, &quot;ab&quot;]</code>, and then concatenating them results in <code>&quot;cdab&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 3 substrings of length 2: <code>[&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;bb&quot;, &quot;aa&quot;, &quot;cc&quot;]</code>, and then concatenating them results in <code>&quot;bbaacc&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 3: <code>[&quot;aab&quot;, &quot;bcc&quot;]</code>.</li> <li>These substrings cannot be rearranged to form <code>t = &quot;bbaacc&quot;</code>, so the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s.length</code> is divisible by <code>k</code>.</li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li> </ul>
Hash Table; String; Sorting
C++
class Solution { public: bool isPossibleToRearrange(string s, string t, int k) { unordered_map<string, int> cnt; int n = s.size(); int m = n / k; for (int i = 0; i < n; i += m) { cnt[s.substr(i, m)]++; cnt[t.substr(i, m)]--; } for (auto& [_, v] : cnt) { if (v) { return false; } } return true; } };
3,365
Rearrange K Substrings to Form Target String
Medium
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p> <p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p> <p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p> <p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p> <p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 2: <code>[&quot;ab&quot;, &quot;cd&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;cd&quot;, &quot;ab&quot;]</code>, and then concatenating them results in <code>&quot;cdab&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 3 substrings of length 2: <code>[&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;bb&quot;, &quot;aa&quot;, &quot;cc&quot;]</code>, and then concatenating them results in <code>&quot;bbaacc&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 3: <code>[&quot;aab&quot;, &quot;bcc&quot;]</code>.</li> <li>These substrings cannot be rearranged to form <code>t = &quot;bbaacc&quot;</code>, so the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s.length</code> is divisible by <code>k</code>.</li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li> </ul>
Hash Table; String; Sorting
Go
func isPossibleToRearrange(s string, t string, k int) bool { n := len(s) m := n / k cnt := map[string]int{} for i := 0; i < n; i += m { cnt[s[i:i+m]]++ cnt[t[i:i+m]]-- } for _, v := range cnt { if v != 0 { return false } } return true }
3,365
Rearrange K Substrings to Form Target String
Medium
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p> <p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p> <p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p> <p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p> <p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 2: <code>[&quot;ab&quot;, &quot;cd&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;cd&quot;, &quot;ab&quot;]</code>, and then concatenating them results in <code>&quot;cdab&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 3 substrings of length 2: <code>[&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;bb&quot;, &quot;aa&quot;, &quot;cc&quot;]</code>, and then concatenating them results in <code>&quot;bbaacc&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 3: <code>[&quot;aab&quot;, &quot;bcc&quot;]</code>.</li> <li>These substrings cannot be rearranged to form <code>t = &quot;bbaacc&quot;</code>, so the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s.length</code> is divisible by <code>k</code>.</li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li> </ul>
Hash Table; String; Sorting
Java
class Solution { public boolean isPossibleToRearrange(String s, String t, int k) { Map<String, Integer> cnt = new HashMap<>(k); int n = s.length(); int m = n / k; for (int i = 0; i < n; i += m) { cnt.merge(s.substring(i, i + m), 1, Integer::sum); cnt.merge(t.substring(i, i + m), -1, Integer::sum); } for (int v : cnt.values()) { if (v != 0) { return false; } } return true; } }
3,365
Rearrange K Substrings to Form Target String
Medium
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p> <p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p> <p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p> <p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p> <p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 2: <code>[&quot;ab&quot;, &quot;cd&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;cd&quot;, &quot;ab&quot;]</code>, and then concatenating them results in <code>&quot;cdab&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 3 substrings of length 2: <code>[&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;bb&quot;, &quot;aa&quot;, &quot;cc&quot;]</code>, and then concatenating them results in <code>&quot;bbaacc&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 3: <code>[&quot;aab&quot;, &quot;bcc&quot;]</code>.</li> <li>These substrings cannot be rearranged to form <code>t = &quot;bbaacc&quot;</code>, so the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s.length</code> is divisible by <code>k</code>.</li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li> </ul>
Hash Table; String; Sorting
Python
class Solution: def isPossibleToRearrange(self, s: str, t: str, k: int) -> bool: cnt = Counter() n = len(s) m = n // k for i in range(0, n, m): cnt[s[i : i + m]] += 1 cnt[t[i : i + m]] -= 1 return all(v == 0 for v in cnt.values())
3,365
Rearrange K Substrings to Form Target String
Medium
<p>You are given two strings <code>s</code> and <code>t</code>, both of which are anagrams of each other, and an integer <code>k</code>.</p> <p>Your task is to determine whether it is possible to split the string <code>s</code> into <code>k</code> equal-sized substrings, rearrange the substrings, and concatenate them in <em>any order</em> to create a new string that matches the given string <code>t</code>.</p> <p>Return <code>true</code> if this is possible, otherwise, return <code>false</code>.</p> <p>An <strong>anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p> <p>A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 2: <code>[&quot;ab&quot;, &quot;cd&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;cd&quot;, &quot;ab&quot;]</code>, and then concatenating them results in <code>&quot;cdab&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 3 substrings of length 2: <code>[&quot;aa&quot;, &quot;bb&quot;, &quot;cc&quot;]</code>.</li> <li>Rearranging these substrings as <code>[&quot;bb&quot;, &quot;aa&quot;, &quot;cc&quot;]</code>, and then concatenating them results in <code>&quot;bbaacc&quot;</code>, which matches <code>t</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabbcc&quot;, t = &quot;bbaacc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>s</code> into 2 substrings of length 3: <code>[&quot;aab&quot;, &quot;bcc&quot;]</code>.</li> <li>These substrings cannot be rearranged to form <code>t = &quot;bbaacc&quot;</code>, so the output is <code>false</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length == t.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s.length</code> is divisible by <code>k</code>.</li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> <li>The input is generated such that<!-- notionvc: 53e485fc-71ce-4032-aed1-f712dd3822ba --> <code>s</code> and <code>t</code> are anagrams of each other.</li> </ul>
Hash Table; String; Sorting
TypeScript
function isPossibleToRearrange(s: string, t: string, k: number): boolean { const cnt: Record<string, number> = {}; const n = s.length; const m = Math.floor(n / k); for (let i = 0; i < n; i += m) { const a = s.slice(i, i + m); cnt[a] = (cnt[a] || 0) + 1; const b = t.slice(i, i + m); cnt[b] = (cnt[b] || 0) - 1; } return Object.values(cnt).every(x => x === 0); }
3,366
Minimum Array Sum
Medium
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p> <p>You can perform the following operations on <code>nums</code>:</p> <ul> <li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li> <li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li> </ul> <p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p> <p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li> <li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li> <li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li> <li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li> <li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li> <li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">0 &lt;= nums[i] &lt;= 10<sup>5</sup></font></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= op1, op2 &lt;= nums.length</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int minArraySum(vector<int>& nums, int d, int op1, int op2) { int n = nums.size(); int f[n + 1][op1 + 1][op2 + 1]; memset(f, 0x3f, sizeof f); f[0][0][0] = 0; for (int i = 1; i <= n; ++i) { int x = nums[i - 1]; for (int j = 0; j <= op1; ++j) { for (int k = 0; k <= op2; ++k) { f[i][j][k] = f[i - 1][j][k] + x; if (j > 0) { f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2); } if (k > 0 && x >= d) { f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d)); } if (j > 0 && k > 0) { int y = (x + 1) / 2; if (y >= d) { f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d)); } if (x >= d) { f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2); } } } } } int ans = INT_MAX; for (int j = 0; j <= op1; ++j) { for (int k = 0; k <= op2; ++k) { ans = min(ans, f[n][j][k]); } } return ans; } };
3,366
Minimum Array Sum
Medium
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p> <p>You can perform the following operations on <code>nums</code>:</p> <ul> <li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li> <li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li> </ul> <p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p> <p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li> <li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li> <li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li> <li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li> <li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li> <li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">0 &lt;= nums[i] &lt;= 10<sup>5</sup></font></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= op1, op2 &lt;= nums.length</code></li> </ul>
Array; Dynamic Programming
Go
func minArraySum(nums []int, d int, op1 int, op2 int) int { n := len(nums) const inf = int(1e9) f := make([][][]int, n+1) for i := range f { f[i] = make([][]int, op1+1) for j := range f[i] { f[i][j] = make([]int, op2+1) for k := range f[i][j] { f[i][j][k] = inf } } } f[0][0][0] = 0 for i := 1; i <= n; i++ { x := nums[i-1] for j := 0; j <= op1; j++ { for k := 0; k <= op2; k++ { f[i][j][k] = f[i-1][j][k] + x if j > 0 { f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k]+(x+1)/2) } if k > 0 && x >= d { f[i][j][k] = min(f[i][j][k], f[i-1][j][k-1]+(x-d)) } if j > 0 && k > 0 { y := (x + 1) / 2 if y >= d { f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(y-d)) } if x >= d { f[i][j][k] = min(f[i][j][k], f[i-1][j-1][k-1]+(x-d+1)/2) } } } } } ans := inf for j := 0; j <= op1; j++ { for k := 0; k <= op2; k++ { ans = min(ans, f[n][j][k]) } } return ans }
3,366
Minimum Array Sum
Medium
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p> <p>You can perform the following operations on <code>nums</code>:</p> <ul> <li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li> <li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li> </ul> <p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p> <p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li> <li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li> <li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li> <li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li> <li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li> <li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">0 &lt;= nums[i] &lt;= 10<sup>5</sup></font></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= op1, op2 &lt;= nums.length</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int minArraySum(int[] nums, int d, int op1, int op2) { int n = nums.length; int[][][] f = new int[n + 1][op1 + 1][op2 + 1]; final int inf = 1 << 29; for (var g : f) { for (var h : g) { Arrays.fill(h, inf); } } f[0][0][0] = 0; for (int i = 1; i <= n; ++i) { int x = nums[i - 1]; for (int j = 0; j <= op1; ++j) { for (int k = 0; k <= op2; ++k) { f[i][j][k] = f[i - 1][j][k] + x; if (j > 0) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) / 2); } if (k > 0 && x >= d) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d)); } if (j > 0 && k > 0) { int y = (x + 1) / 2; if (y >= d) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d)); } if (x >= d) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) / 2); } } } } } int ans = inf; for (int j = 0; j <= op1; ++j) { for (int k = 0; k <= op2; ++k) { ans = Math.min(ans, f[n][j][k]); } } return ans; } }
3,366
Minimum Array Sum
Medium
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p> <p>You can perform the following operations on <code>nums</code>:</p> <ul> <li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li> <li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li> </ul> <p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p> <p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li> <li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li> <li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li> <li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li> <li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li> <li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">0 &lt;= nums[i] &lt;= 10<sup>5</sup></font></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= op1, op2 &lt;= nums.length</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def minArraySum(self, nums: List[int], d: int, op1: int, op2: int) -> int: n = len(nums) f = [[[inf] * (op2 + 1) for _ in range(op1 + 1)] for _ in range(n + 1)] f[0][0][0] = 0 for i, x in enumerate(nums, 1): for j in range(op1 + 1): for k in range(op2 + 1): f[i][j][k] = f[i - 1][j][k] + x if j > 0: f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k] + (x + 1) // 2) if k > 0 and x >= d: f[i][j][k] = min(f[i][j][k], f[i - 1][j][k - 1] + (x - d)) if j > 0 and k > 0: y = (x + 1) // 2 if y >= d: f[i][j][k] = min(f[i][j][k], f[i - 1][j - 1][k - 1] + y - d) if x >= d: f[i][j][k] = min( f[i][j][k], f[i - 1][j - 1][k - 1] + (x - d + 1) // 2 ) ans = inf for j in range(op1 + 1): for k in range(op2 + 1): ans = min(ans, f[n][j][k]) return ans
3,366
Minimum Array Sum
Medium
<p>You are given an integer array <code>nums</code> and three integers <code>k</code>, <code>op1</code>, and <code>op2</code>.</p> <p>You can perform the following operations on <code>nums</code>:</p> <ul> <li><strong>Operation 1</strong>: Choose an index <code>i</code> and divide <code>nums[i]</code> by 2, <strong>rounding up</strong> to the nearest whole number. You can perform this operation at most <code>op1</code> times, and not more than <strong>once</strong> per index.</li> <li><strong>Operation 2</strong>: Choose an index <code>i</code> and subtract <code>k</code> from <code>nums[i]</code>, but only if <code>nums[i]</code> is greater than or equal to <code>k</code>. You can perform this operation at most <code>op2</code> times, and not more than <strong>once</strong> per index.</li> </ul> <p><strong>Note:</strong> Both operations can be applied to the same index, but at most once each.</p> <p>Return the <strong>minimum</strong> possible <strong>sum</strong> of all elements in <code>nums</code> after performing any number of operations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 2 to <code>nums[1] = 8</code>, making <code>nums[1] = 5</code>.</li> <li>Apply Operation 1 to <code>nums[3] = 19</code>, making <code>nums[3] = 10</code>.</li> <li>The resulting array becomes <code>[2, 5, 3, 10, 3]</code>, which has the minimum possible sum of 23 after applying the operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,3], k = 3, op1 = 2, op2 = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Apply Operation 1 to <code>nums[0] = 2</code>, making <code>nums[0] = 1</code>.</li> <li>Apply Operation 1 to <code>nums[1] = 4</code>, making <code>nums[1] = 2</code>.</li> <li>Apply Operation 2 to <code>nums[2] = 3</code>, making <code>nums[2] = 0</code>.</li> <li>The resulting array becomes <code>[1, 2, 0]</code>, which has the minimum possible sum of 3 after applying the operations.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">0 &lt;= nums[i] &lt;= 10<sup>5</sup></font></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= op1, op2 &lt;= nums.length</code></li> </ul>
Array; Dynamic Programming
TypeScript
function minArraySum(nums: number[], d: number, op1: number, op2: number): number { const n = nums.length; const inf = Number.MAX_SAFE_INTEGER; const f: number[][][] = Array.from({ length: n + 1 }, () => Array.from({ length: op1 + 1 }, () => Array(op2 + 1).fill(inf)), ); f[0][0][0] = 0; for (let i = 1; i <= n; i++) { const x = nums[i - 1]; for (let j = 0; j <= op1; j++) { for (let k = 0; k <= op2; k++) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + x); if (j > 0) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k] + Math.floor((x + 1) / 2)); } if (k > 0 && x >= d) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k - 1] + (x - d)); } if (j > 0 && k > 0) { const y = Math.floor((x + 1) / 2); if (y >= d) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j - 1][k - 1] + (y - d)); } if (x >= d) { f[i][j][k] = Math.min( f[i][j][k], f[i - 1][j - 1][k - 1] + Math.floor((x - d + 1) / 2), ); } } } } } let ans = inf; for (let j = 0; j <= op1; j++) { for (let l = 0; l <= op2; l++) { ans = Math.min(ans, f[n][j][l]); } } return ans; }
3,367
Maximize Sum of Weights after Edge Removals
Hard
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>Your task is to remove <em>zero or more</em> edges such that:</p> <ul> <li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li> <li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li> </ul> <p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p> <ul> <li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li> <li>The sum of weights is 22, and we can&#39;t achieve a greater sum. Thus, the answer is 22.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">65</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don&#39;t remove any edges.</li> <li>The sum of weights is 65. Thus, the answer is 65.</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;= k &lt;= n - 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code><font face="monospace">0 &lt;= edges[i][0] &lt;= n - 1</font></code></li> <li><code><font face="monospace">0 &lt;= edges[i][1] &lt;= n - 1</font></code></li> <li><code><font face="monospace">1 &lt;= edges[i][2] &lt;= 10<sup>6</sup></font></code></li> <li>The input is generated such that <code>edges</code> form a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming
C++
class Solution { public: long long maximizeSumOfWeights(vector<vector<int>>& edges, int k) { int n = edges.size() + 1; vector<vector<pair<int, int>>> g(n); for (auto& e : edges) { int u = e[0], v = e[1], w = e[2]; g[u].emplace_back(v, w); g[v].emplace_back(u, w); } using ll = long long; auto dfs = [&](this auto&& dfs, int u, int fa) -> pair<ll, ll> { ll s = 0; vector<ll> t; for (auto& [v, w] : g[u]) { if (v == fa) { continue; } auto [a, b] = dfs(v, u); s += a; ll d = w + b - a; if (d > 0) { t.push_back(d); } } ranges::sort(t, greater<>()); for (int i = 0; i < min((int) t.size(), k - 1); ++i) { s += t[i]; } return {s + (t.size() >= k ? t[k - 1] : 0), s}; }; auto [x, y] = dfs(0, -1); return max(x, y); } };
3,367
Maximize Sum of Weights after Edge Removals
Hard
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>Your task is to remove <em>zero or more</em> edges such that:</p> <ul> <li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li> <li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li> </ul> <p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p> <ul> <li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li> <li>The sum of weights is 22, and we can&#39;t achieve a greater sum. Thus, the answer is 22.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">65</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don&#39;t remove any edges.</li> <li>The sum of weights is 65. Thus, the answer is 65.</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;= k &lt;= n - 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code><font face="monospace">0 &lt;= edges[i][0] &lt;= n - 1</font></code></li> <li><code><font face="monospace">0 &lt;= edges[i][1] &lt;= n - 1</font></code></li> <li><code><font face="monospace">1 &lt;= edges[i][2] &lt;= 10<sup>6</sup></font></code></li> <li>The input is generated such that <code>edges</code> form a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming
Go
func maximizeSumOfWeights(edges [][]int, k int) int64 { n := len(edges) + 1 g := make([][][]int, n) for _, e := range edges { u, v, w := e[0], e[1], e[2] g[u] = append(g[u], []int{v, w}) g[v] = append(g[v], []int{u, w}) } var dfs func(u, fa int) (int64, int64) dfs = func(u, fa int) (int64, int64) { var s int64 var t []int64 for _, e := range g[u] { v, w := e[0], e[1] if v == fa { continue } a, b := dfs(v, u) s += a d := int64(w) + b - a if d > 0 { t = append(t, d) } } sort.Slice(t, func(i, j int) bool { return t[i] > t[j] }) for i := 0; i < min(len(t), k-1); i++ { s += t[i] } s2 := s if len(t) >= k { s += t[k-1] } return s, s2 } x, y := dfs(0, -1) return max(x, y) }
3,367
Maximize Sum of Weights after Edge Removals
Hard
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>Your task is to remove <em>zero or more</em> edges such that:</p> <ul> <li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li> <li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li> </ul> <p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p> <ul> <li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li> <li>The sum of weights is 22, and we can&#39;t achieve a greater sum. Thus, the answer is 22.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">65</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don&#39;t remove any edges.</li> <li>The sum of weights is 65. Thus, the answer is 65.</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;= k &lt;= n - 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code><font face="monospace">0 &lt;= edges[i][0] &lt;= n - 1</font></code></li> <li><code><font face="monospace">0 &lt;= edges[i][1] &lt;= n - 1</font></code></li> <li><code><font face="monospace">1 &lt;= edges[i][2] &lt;= 10<sup>6</sup></font></code></li> <li>The input is generated such that <code>edges</code> form a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming
Java
class Solution { private List<int[]>[] g; private int k; public long maximizeSumOfWeights(int[][] edges, int k) { this.k = k; int n = edges.length + 1; g = new List[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (var e : edges) { int u = e[0], v = e[1], w = e[2]; g[u].add(new int[] {v, w}); g[v].add(new int[] {u, w}); } var ans = dfs(0, -1); return Math.max(ans[0], ans[1]); } private long[] dfs(int u, int fa) { long s = 0; List<Long> t = new ArrayList<>(); for (var e : g[u]) { int v = e[0], w = e[1]; if (v == fa) { continue; } var res = dfs(v, u); s += res[0]; long d = w + res[1] - res[0]; if (d > 0) { t.add(d); } } t.sort(Comparator.reverseOrder()); for (int i = 0; i < Math.min(t.size(), k - 1); ++i) { s += t.get(i); } return new long[] {s + (t.size() >= k ? t.get(k - 1) : 0), s}; } }
3,367
Maximize Sum of Weights after Edge Removals
Hard
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>Your task is to remove <em>zero or more</em> edges such that:</p> <ul> <li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li> <li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li> </ul> <p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p> <ul> <li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li> <li>The sum of weights is 22, and we can&#39;t achieve a greater sum. Thus, the answer is 22.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">65</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don&#39;t remove any edges.</li> <li>The sum of weights is 65. Thus, the answer is 65.</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;= k &lt;= n - 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code><font face="monospace">0 &lt;= edges[i][0] &lt;= n - 1</font></code></li> <li><code><font face="monospace">0 &lt;= edges[i][1] &lt;= n - 1</font></code></li> <li><code><font face="monospace">1 &lt;= edges[i][2] &lt;= 10<sup>6</sup></font></code></li> <li>The input is generated such that <code>edges</code> form a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming
Python
class Solution: def maximizeSumOfWeights(self, edges: List[List[int]], k: int) -> int: def dfs(u: int, fa: int) -> Tuple[int, int]: s = 0 t = [] for v, w in g[u]: if v == fa: continue a, b = dfs(v, u) s += a if (d := (w + b - a)) > 0: t.append(d) t.sort(reverse=True) return s + sum(t[:k]), s + sum(t[: k - 1]) n = len(edges) + 1 g: List[List[Tuple[int, int]]] = [[] for _ in range(n)] for u, v, w in edges: g[u].append((v, w)) g[v].append((u, w)) x, y = dfs(0, -1) return max(x, y)
3,367
Maximize Sum of Weights after Edge Removals
Hard
<p>There exists an <strong>undirected</strong> tree with <code>n</code> nodes numbered <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>Your task is to remove <em>zero or more</em> edges such that:</p> <ul> <li>Each node has an edge with <strong>at most</strong> <code>k</code> other nodes, where <code>k</code> is given.</li> <li>The sum of the weights of the remaining edges is <strong>maximized</strong>.</li> </ul> <p>Return the <strong>maximum </strong>possible sum of weights for the remaining edges after making the necessary removals.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3367.Maximize%20Sum%20of%20Weights%20after%20Edge%20Removals/images/test1drawio.png" style="width: 250px; height: 250px;" /></p> <ul> <li>Node 2 has edges with 3 other nodes. We remove the edge <code>[0, 2, 2]</code>, ensuring that no node has edges with more than <code>k = 2</code> nodes.</li> <li>The sum of weights is 22, and we can&#39;t achieve a greater sum. Thus, the answer is 22.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">65</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no node has edges connecting it to more than <code>k = 3</code> nodes, we don&#39;t remove any edges.</li> <li>The sum of weights is 65. Thus, the answer is 65.</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;= k &lt;= n - 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code><font face="monospace">0 &lt;= edges[i][0] &lt;= n - 1</font></code></li> <li><code><font face="monospace">0 &lt;= edges[i][1] &lt;= n - 1</font></code></li> <li><code><font face="monospace">1 &lt;= edges[i][2] &lt;= 10<sup>6</sup></font></code></li> <li>The input is generated such that <code>edges</code> form a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming
TypeScript
function maximizeSumOfWeights(edges: number[][], k: number): number { const n = edges.length + 1; const g: [number, number][][] = Array.from({ length: n }, () => []); for (const [u, v, w] of edges) { g[u].push([v, w]); g[v].push([u, w]); } const dfs = (u: number, fa: number): [number, number] => { let s = 0; const t: number[] = []; for (const [v, w] of g[u]) { if (v === fa) continue; const [a, b] = dfs(v, u); s += a; const d = w + b - a; if (d > 0) t.push(d); } t.sort((a, b) => b - a); for (let i = 0; i < Math.min(t.length, k - 1); i++) { s += t[i]; } const s2 = s; if (t.length >= k) { s += t[k - 1]; } return [s, s2]; }; const [x, y] = dfs(0, -1); return Math.max(x, y); }
3,368
First Letter Capitalization
Hard
<p>Table: <code>user_content</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | content_id | int | | content_text| varchar | +-------------+---------+ content_id is the unique key for this table. Each row contains a unique ID and the corresponding text content. </pre> <p>Write a solution to transform the text in the <code>content_text</code> column by applying the following rules:</p> <ul> <li>Convert the first letter of each word to uppercase</li> <li>Keep all other letters in lowercase</li> <li>Preserve all existing spaces</li> </ul> <p><strong>Note</strong>: There will be no special character in <code>content_text</code>.</p> <p>Return <em>the result table that includes both the original <code>content_text</code> and the modified text where each word starts with a capital letter</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>user_content table:</p> <pre class="example-io"> +------------+-----------------------------------+ | content_id | content_text | +------------+-----------------------------------+ | 1 | hello world of SQL | | 2 | the QUICK brown fox | | 3 | data science AND machine learning | | 4 | TOP rated programming BOOKS | +------------+-----------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+-----------------------------------+-----------------------------------+ | content_id | original_text | converted_text | +------------+-----------------------------------+-----------------------------------+ | 1 | hello world of SQL | Hello World Of Sql | | 2 | the QUICK brown fox | The Quick Brown Fox | | 3 | data science AND machine learning | Data Science And Machine Learning | | 4 | TOP rated programming BOOKS | Top Rated Programming Books | +------------+-----------------------------------+-----------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For content_id = 1: <ul> <li>Each word&#39;s first letter is capitalized: Hello World Of Sql</li> </ul> </li> <li>For content_id = 2: <ul> <li>Original mixed-case text is transformed to title case: The Quick Brown Fox</li> </ul> </li> <li>For content_id = 3: <ul> <li>The word AND&nbsp;is converted to &quot;And&quot;: &quot;Data Science And Machine Learning&quot;</li> </ul> </li> <li>For content_id = 4: <ul> <li>Handles&nbsp;word TOP rated&nbsp;correctly: Top Rated</li> <li>Converts BOOKS&nbsp;from all caps to title case: Books</li> </ul> </li> </ul> </div>
Database
Python
import pandas as pd def process_text(user_content: pd.DataFrame) -> pd.DataFrame: user_content["converted_text"] = user_content["content_text"].apply( lambda text: " ".join(word.capitalize() for word in text.split(" ")) ) return user_content[["content_id", "content_text", "converted_text"]].rename( columns={"content_text": "original_text"} )
3,368
First Letter Capitalization
Hard
<p>Table: <code>user_content</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | content_id | int | | content_text| varchar | +-------------+---------+ content_id is the unique key for this table. Each row contains a unique ID and the corresponding text content. </pre> <p>Write a solution to transform the text in the <code>content_text</code> column by applying the following rules:</p> <ul> <li>Convert the first letter of each word to uppercase</li> <li>Keep all other letters in lowercase</li> <li>Preserve all existing spaces</li> </ul> <p><strong>Note</strong>: There will be no special character in <code>content_text</code>.</p> <p>Return <em>the result table that includes both the original <code>content_text</code> and the modified text where each word starts with a capital letter</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>user_content table:</p> <pre class="example-io"> +------------+-----------------------------------+ | content_id | content_text | +------------+-----------------------------------+ | 1 | hello world of SQL | | 2 | the QUICK brown fox | | 3 | data science AND machine learning | | 4 | TOP rated programming BOOKS | +------------+-----------------------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+-----------------------------------+-----------------------------------+ | content_id | original_text | converted_text | +------------+-----------------------------------+-----------------------------------+ | 1 | hello world of SQL | Hello World Of Sql | | 2 | the QUICK brown fox | The Quick Brown Fox | | 3 | data science AND machine learning | Data Science And Machine Learning | | 4 | TOP rated programming BOOKS | Top Rated Programming Books | +------------+-----------------------------------+-----------------------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For content_id = 1: <ul> <li>Each word&#39;s first letter is capitalized: Hello World Of Sql</li> </ul> </li> <li>For content_id = 2: <ul> <li>Original mixed-case text is transformed to title case: The Quick Brown Fox</li> </ul> </li> <li>For content_id = 3: <ul> <li>The word AND&nbsp;is converted to &quot;And&quot;: &quot;Data Science And Machine Learning&quot;</li> </ul> </li> <li>For content_id = 4: <ul> <li>Handles&nbsp;word TOP rated&nbsp;correctly: Top Rated</li> <li>Converts BOOKS&nbsp;from all caps to title case: Books</li> </ul> </li> </ul> </div>
Database
SQL
WITH RECURSIVE capitalized_words AS ( SELECT content_id, content_text, SUBSTRING_INDEX(content_text, ' ', 1) AS word, SUBSTRING( content_text, LENGTH(SUBSTRING_INDEX(content_text, ' ', 1)) + 2 ) AS remaining_text, CONCAT( UPPER(LEFT(SUBSTRING_INDEX(content_text, ' ', 1), 1)), LOWER(SUBSTRING(SUBSTRING_INDEX(content_text, ' ', 1), 2)) ) AS processed_word FROM user_content UNION ALL SELECT c.content_id, c.content_text, SUBSTRING_INDEX(c.remaining_text, ' ', 1), SUBSTRING(c.remaining_text, LENGTH(SUBSTRING_INDEX(c.remaining_text, ' ', 1)) + 2), CONCAT( c.processed_word, ' ', CONCAT( UPPER(LEFT(SUBSTRING_INDEX(c.remaining_text, ' ', 1), 1)), LOWER(SUBSTRING(SUBSTRING_INDEX(c.remaining_text, ' ', 1), 2)) ) ) FROM capitalized_words c WHERE c.remaining_text != '' ) SELECT content_id, content_text AS original_text, MAX(processed_word) AS converted_text FROM capitalized_words GROUP BY 1, 2;