id
int64
1
3.64k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,422
Minimum Operations to Make Subarray Elements Equal
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Increase or decrease any element of <code>nums</code> by 1.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to ensure that <strong>at least</strong> one <span data-keyword="subarray">subarray</span> of size <code>k</code> in <code>nums</code> has all elements 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 = [4,-3,2,1,-4,6], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Use 4 operations to add 4 to <code>nums[1]</code>. The resulting array is <span class="example-io"><code>[4, 1, 2, 1, -4, 6]</code>.</span></li> <li><span class="example-io">Use 1 operation to subtract 1 from <code>nums[2]</code>. The resulting array is <code>[4, 1, 1, 1, -4, 6]</code>.</span></li> <li><span class="example-io">The array now contains a subarray <code>[1, 1, 1]</code> of size <code>k = 3</code> with all elements equal. Hence, the answer is 5.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2,-2,3,1,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p>The subarray <code>[-2, -2]</code> of size <code>k = 2</code> already contains all equal elements, so no operations are needed. Hence, the answer is 0.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>2 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Math; Sliding Window; Heap (Priority Queue)
Java
class Solution { public long minOperations(int[] nums, int k) { TreeMap<Integer, Integer> l = new TreeMap<>(); TreeMap<Integer, Integer> r = new TreeMap<>(); long s1 = 0, s2 = 0; int sz1 = 0, sz2 = 0; long ans = Long.MAX_VALUE; for (int i = 0; i < nums.length; ++i) { l.merge(nums[i], 1, Integer::sum); s1 += nums[i]; ++sz1; int y = l.lastKey(); if (l.merge(y, -1, Integer::sum) == 0) { l.remove(y); } s1 -= y; --sz1; r.merge(y, 1, Integer::sum); s2 += y; ++sz2; if (sz2 - sz1 > 1) { y = r.firstKey(); if (r.merge(y, -1, Integer::sum) == 0) { r.remove(y); } s2 -= y; --sz2; l.merge(y, 1, Integer::sum); s1 += y; ++sz1; } if (i >= k - 1) { ans = Math.min(ans, s2 - r.firstKey() * sz2 + r.firstKey() * sz1 - s1); int j = i - k + 1; if (r.containsKey(nums[j])) { if (r.merge(nums[j], -1, Integer::sum) == 0) { r.remove(nums[j]); } s2 -= nums[j]; --sz2; } else { if (l.merge(nums[j], -1, Integer::sum) == 0) { l.remove(nums[j]); } s1 -= nums[j]; --sz1; } } } return ans; } }
3,422
Minimum Operations to Make Subarray Elements Equal
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Increase or decrease any element of <code>nums</code> by 1.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to ensure that <strong>at least</strong> one <span data-keyword="subarray">subarray</span> of size <code>k</code> in <code>nums</code> has all elements 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 = [4,-3,2,1,-4,6], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Use 4 operations to add 4 to <code>nums[1]</code>. The resulting array is <span class="example-io"><code>[4, 1, 2, 1, -4, 6]</code>.</span></li> <li><span class="example-io">Use 1 operation to subtract 1 from <code>nums[2]</code>. The resulting array is <code>[4, 1, 1, 1, -4, 6]</code>.</span></li> <li><span class="example-io">The array now contains a subarray <code>[1, 1, 1]</code> of size <code>k = 3</code> with all elements equal. Hence, the answer is 5.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2,-2,3,1,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p>The subarray <code>[-2, -2]</code> of size <code>k = 2</code> already contains all equal elements, so no operations are needed. Hence, the answer is 0.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>2 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Math; Sliding Window; Heap (Priority Queue)
Python
class Solution: def minOperations(self, nums: List[int], k: int) -> int: l = SortedList() r = SortedList() s1 = s2 = 0 ans = inf for i, x in enumerate(nums): l.add(x) s1 += x y = l.pop() s1 -= y r.add(y) s2 += y if len(r) - len(l) > 1: y = r.pop(0) s2 -= y l.add(y) s1 += y if i >= k - 1: ans = min(ans, s2 - r[0] * len(r) + r[0] * len(l) - s1) j = i - k + 1 if nums[j] in r: r.remove(nums[j]) s2 -= nums[j] else: l.remove(nums[j]) s1 -= nums[j] return ans
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
C++
class Solution { public: int maxAdjacentDistance(vector<int>& nums) { int ans = abs(nums[0] - nums.back()); for (int i = 1; i < nums.size(); ++i) { ans = max(ans, abs(nums[i] - nums[i - 1])); } return ans; } };
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
C#
public class Solution { public int MaxAdjacentDistance(int[] nums) { int n = nums.Length; int ans = Math.Abs(nums[0] - nums[n - 1]); for (int i = 1; i < n; ++i) { ans = Math.Max(ans, Math.Abs(nums[i] - nums[i - 1])); } return ans; } }
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
Go
func maxAdjacentDistance(nums []int) int { ans := abs(nums[0] - nums[len(nums)-1]) for i := 1; i < len(nums); i++ { ans = max(ans, abs(nums[i]-nums[i-1])) } return ans } func abs(x int) int { if x < 0 { return -x } return x }
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
Java
class Solution { public int maxAdjacentDistance(int[] nums) { int n = nums.length; int ans = Math.abs(nums[0] - nums[n - 1]); for (int i = 1; i < n; ++i) { ans = Math.max(ans, Math.abs(nums[i] - nums[i - 1])); } return ans; } }
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
Python
class Solution: def maxAdjacentDistance(self, nums: List[int]) -> int: return max(abs(a - b) for a, b in pairwise(nums + [nums[0]]))
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
Rust
impl Solution { pub fn max_adjacent_distance(nums: Vec<i32>) -> i32 { nums.iter() .zip(nums.iter().cycle().skip(1)) .take(nums.len()) .map(|(a, b)| (*a - *b).abs()) .max() .unwrap_or(0) } }
3,423
Maximum Difference Between Adjacent Elements in a Circular Array
Easy
<p>Given a <strong>circular</strong> array <code>nums</code>, find the <b>maximum</b> absolute difference between adjacent elements.</p> <p><strong>Note</strong>: In a circular array, the first and last elements are adjacent.</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,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Because <code>nums</code> is circular, <code>nums[0]</code> and <code>nums[2]</code> are adjacent. They have the maximum absolute difference of <code>|4 - 1| = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-5,-10,-5]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The adjacent elements <code>nums[0]</code> and <code>nums[1]</code> have the maximum absolute difference of <code>|-5 - (-10)| = 5</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array
TypeScript
function maxAdjacentDistance(nums: number[]): number { const n = nums.length; let ans = Math.abs(nums[0] - nums[n - 1]); for (let i = 1; i < n; ++i) { ans = Math.max(ans, Math.abs(nums[i] - nums[i - 1])); } return ans; }
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: long long minCost(vector<int>& arr, vector<int>& brr, long long k) { auto calc = [&](vector<int>& arr, vector<int>& brr) { long long ans = 0; for (int i = 0; i < arr.size(); ++i) { ans += abs(arr[i] - brr[i]); } return ans; }; long long c1 = calc(arr, brr); ranges::sort(arr); ranges::sort(brr); long long c2 = calc(arr, brr) + k; return min(c1, c2); } };
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func minCost(arr []int, brr []int, k int64) int64 { calc := func(a, b []int) (ans int64) { for i := range a { ans += int64(abs(a[i] - b[i])) } return } c1 := calc(arr, brr) sort.Ints(arr) sort.Ints(brr) c2 := calc(arr, brr) + k return min(c1, c2) } func abs(x int) int { if x < 0 { return -x } return x }
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public long minCost(int[] arr, int[] brr, long k) { long c1 = calc(arr, brr); Arrays.sort(arr); Arrays.sort(brr); long c2 = calc(arr, brr) + k; return Math.min(c1, c2); } private long calc(int[] arr, int[] brr) { long ans = 0; for (int i = 0; i < arr.length; ++i) { ans += Math.abs(arr[i] - brr[i]); } return ans; } }
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minCost(self, arr: List[int], brr: List[int], k: int) -> int: c1 = sum(abs(a - b) for a, b in zip(arr, brr)) arr.sort() brr.sort() c2 = k + sum(abs(a - b) for a, b in zip(arr, brr)) return min(c1, c2)
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Rust
impl Solution { pub fn min_cost(mut arr: Vec<i32>, mut brr: Vec<i32>, k: i64) -> i64 { let c1: i64 = arr .iter() .zip(&brr) .map(|(a, b)| (*a - *b).abs() as i64) .sum(); arr.sort_unstable(); brr.sort_unstable(); let c2: i64 = k + arr .iter() .zip(&brr) .map(|(a, b)| (*a - *b).abs() as i64) .sum::<i64>(); c1.min(c2) } }
3,424
Minimum Cost to Make Arrays Identical
Medium
<p>You are given two integer arrays <code>arr</code> and <code>brr</code> of length <code>n</code>, and an integer <code>k</code>. You can perform the following operations on <code>arr</code> <em>any</em> number of times:</p> <ul> <li>Split <code>arr</code> into <em>any</em> number of <strong>contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> and rearrange these subarrays in <em>any order</em>. This operation has a fixed cost of <code>k</code>.</li> <li> <p>Choose any element in <code>arr</code> and add or subtract a positive integer <code>x</code> to it. The cost of this operation is <code>x</code>.</p> </li> </ul> <p>Return the <strong>minimum </strong>total cost to make <code>arr</code> <strong>equal</strong> to <code>brr</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">arr = [-7,9,5], brr = [7,-2,-5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Split <code>arr</code> into two contiguous subarrays: <code>[-7]</code> and <code>[9, 5]</code> and rearrange them as <code>[9, 5, -7]</code>, with a cost of 2.</li> <li>Subtract 2 from element <code>arr[0]</code>. The array becomes <code>[7, 5, -7]</code>. The cost of this operation is 2.</li> <li>Subtract 7 from element <code>arr[1]</code>. The array becomes <code>[7, -2, -7]</code>. The cost of this operation is 7.</li> <li>Add 2 to element <code>arr[2]</code>. The array becomes <code>[7, -2, -5]</code>. The cost of this operation is 2.</li> </ul> <p>The total cost to make the arrays equal is <code>2 + 2 + 7 + 2 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">arr = [2,1], brr = [2,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Since the arrays are already equal, no operations are needed, and the total cost is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr.length == brr.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 2 * 10<sup>10</sup></code></li> <li><code>-10<sup>5</sup> &lt;= arr[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= brr[i] &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minCost(arr: number[], brr: number[], k: number): number { const calc = (a: number[], b: number[]) => { let ans = 0; for (let i = 0; i < a.length; ++i) { ans += Math.abs(a[i] - b[i]); } return ans; }; const c1 = calc(arr, brr); arr.sort((a, b) => a - b); brr.sort((a, b) => a - b); const c2 = calc(arr, brr) + k; return Math.min(c1, c2); }
3,427
Sum of Variable Length Subarrays
Easy
<p>You are given an integer array <code>nums</code> of size <code>n</code>. For <strong>each</strong> index <code>i</code> where <code>0 &lt;= i &lt; n</code>, define a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[start ... i]</code> where <code>start = max(0, i - nums[i])</code>.</p> <p>Return the total sum of all elements from the subarray defined for each index in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [2]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [2, 3]</code></td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">11</td> </tr> </tbody> </table> <p>The total sum is 11. Hence, 11 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [3]</code></td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [1, 1]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;"><code>nums[1 ... 3] = [1, 1, 2]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">13</td> </tr> </tbody> </table> <p>The total sum is 13. Hence, 13 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum
C++
class Solution { public: int subarraySum(vector<int>& nums) { int n = nums.size(); vector<int> s(n + 1); for (int i = 1; i <= n; ++i) { s[i] = s[i - 1] + nums[i - 1]; } int ans = 0; for (int i = 0; i < n; ++i) { ans += s[i + 1] - s[max(0, i - nums[i])]; } return ans; } };
3,427
Sum of Variable Length Subarrays
Easy
<p>You are given an integer array <code>nums</code> of size <code>n</code>. For <strong>each</strong> index <code>i</code> where <code>0 &lt;= i &lt; n</code>, define a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[start ... i]</code> where <code>start = max(0, i - nums[i])</code>.</p> <p>Return the total sum of all elements from the subarray defined for each index in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [2]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [2, 3]</code></td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">11</td> </tr> </tbody> </table> <p>The total sum is 11. Hence, 11 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [3]</code></td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [1, 1]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;"><code>nums[1 ... 3] = [1, 1, 2]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">13</td> </tr> </tbody> </table> <p>The total sum is 13. Hence, 13 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Go
func subarraySum(nums []int) (ans int) { s := make([]int, len(nums)+1) for i, x := range nums { s[i+1] = s[i] + x } for i, x := range nums { ans += s[i+1] - s[max(0, i-x)] } return }
3,427
Sum of Variable Length Subarrays
Easy
<p>You are given an integer array <code>nums</code> of size <code>n</code>. For <strong>each</strong> index <code>i</code> where <code>0 &lt;= i &lt; n</code>, define a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[start ... i]</code> where <code>start = max(0, i - nums[i])</code>.</p> <p>Return the total sum of all elements from the subarray defined for each index in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [2]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [2, 3]</code></td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">11</td> </tr> </tbody> </table> <p>The total sum is 11. Hence, 11 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [3]</code></td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [1, 1]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;"><code>nums[1 ... 3] = [1, 1, 2]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">13</td> </tr> </tbody> </table> <p>The total sum is 13. Hence, 13 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Java
class Solution { public int subarraySum(int[] nums) { int n = nums.length; int[] s = new int[n + 1]; for (int i = 1; i <= n; ++i) { s[i] = s[i - 1] + nums[i - 1]; } int ans = 0; for (int i = 0; i < n; ++i) { ans += s[i + 1] - s[Math.max(0, i - nums[i])]; } return ans; } }
3,427
Sum of Variable Length Subarrays
Easy
<p>You are given an integer array <code>nums</code> of size <code>n</code>. For <strong>each</strong> index <code>i</code> where <code>0 &lt;= i &lt; n</code>, define a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[start ... i]</code> where <code>start = max(0, i - nums[i])</code>.</p> <p>Return the total sum of all elements from the subarray defined for each index in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [2]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [2, 3]</code></td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">11</td> </tr> </tbody> </table> <p>The total sum is 11. Hence, 11 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [3]</code></td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [1, 1]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;"><code>nums[1 ... 3] = [1, 1, 2]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">13</td> </tr> </tbody> </table> <p>The total sum is 13. Hence, 13 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum
Python
class Solution: def subarraySum(self, nums: List[int]) -> int: s = list(accumulate(nums, initial=0)) return sum(s[i + 1] - s[max(0, i - x)] for i, x in enumerate(nums))
3,427
Sum of Variable Length Subarrays
Easy
<p>You are given an integer array <code>nums</code> of size <code>n</code>. For <strong>each</strong> index <code>i</code> where <code>0 &lt;= i &lt; n</code>, define a <span data-keyword="subarray-nonempty">subarray</span> <code>nums[start ... i]</code> where <code>start = max(0, i - nums[i])</code>.</p> <p>Return the total sum of all elements from the subarray defined for each index in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [2]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [2, 3]</code></td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">11</td> </tr> </tbody> </table> <p>The total sum is 11. Hence, 11 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">i</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;"><code>nums[0] = [3]</code></td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;"><code>nums[0 ... 1] = [3, 1]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;"><code>nums[1 ... 2] = [1, 1]</code></td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;"><code>nums[1 ... 3] = [1, 1, 2]</code></td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Total Sum</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">13</td> </tr> </tbody> </table> <p>The total sum is 13. Hence, 13 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Prefix Sum
TypeScript
function subarraySum(nums: number[]): number { const n = nums.length; const s: number[] = Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } let ans = 0; for (let i = 0; i < n; ++i) { ans += s[i + 1] - s[Math.max(0, i - nums[i])]; } return ans; }
3,430
Maximum and Minimum Sums of at Most Size K Subarrays
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>. Return the sum of the <strong>maximum</strong> and <strong>minimum</strong> elements of all <span data-keyword="subarray-nonempty">subarrays</span> with <strong>at most</strong> <code>k</code> elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of <code>nums</code> with at most 2 elements are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;"><b>Subarray</b></th> <th style="border: 1px solid black;">Minimum</th> <th style="border: 1px solid black;">Maximum</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;"><code>[1]</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;"><code>[2]</code></td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">4</td> </tr> <tr> <td style="border: 1px solid black;"><code>[3]</code></td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">6</td> </tr> <tr> <td style="border: 1px solid black;"><code>[1, 2]</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>[2, 3]</code></td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">5</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Final Total</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">20</td> </tr> </tbody> </table> <p>The output would be 20.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-3,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">-6</span></p> <p><strong>Explanation:</strong></p> <p>The subarrays of <code>nums</code> with at most 2 elements are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;"><b>Subarray</b></th> <th style="border: 1px solid black;">Minimum</th> <th style="border: 1px solid black;">Maximum</th> <th style="border: 1px solid black;">Sum</th> </tr> <tr> <td style="border: 1px solid black;"><code>[1]</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;"><code>[-3]</code></td> <td style="border: 1px solid black;">-3</td> <td style="border: 1px solid black;">-3</td> <td style="border: 1px solid black;">-6</td> </tr> <tr> <td style="border: 1px solid black;"><code>[1]</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;"><code>[1, -3]</code></td> <td style="border: 1px solid black;">-3</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">-2</td> </tr> <tr> <td style="border: 1px solid black;"><code>[-3, 1]</code></td> <td style="border: 1px solid black;">-3</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">-2</td> </tr> <tr> <td style="border: 1px solid black;"><strong>Final Total</strong></td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">&nbsp;</td> <td style="border: 1px solid black;">-6</td> </tr> </tbody> </table> <p>The output would be -6.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 80000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Array; Math; Monotonic Stack
JavaScript
/** * @param {number[]} nums * @param {number} k * @return {number} */ var minMaxSubarraySum = function (nums, k) { const computeSum = (nums, k, isMin) => { const n = nums.length; const prev = Array(n).fill(-1); const next = Array(n).fill(n); let stk = []; if (isMin) { for (let i = 0; i < n; i++) { while (stk.length > 0 && nums[stk[stk.length - 1]] >= nums[i]) { stk.pop(); } prev[i] = stk.length > 0 ? stk[stk.length - 1] : -1; stk.push(i); } stk = []; for (let i = n - 1; i >= 0; i--) { while (stk.length > 0 && nums[stk[stk.length - 1]] > nums[i]) { stk.pop(); } next[i] = stk.length > 0 ? stk[stk.length - 1] : n; stk.push(i); } } else { for (let i = 0; i < n; i++) { while (stk.length > 0 && nums[stk[stk.length - 1]] <= nums[i]) { stk.pop(); } prev[i] = stk.length > 0 ? stk[stk.length - 1] : -1; stk.push(i); } stk = []; for (let i = n - 1; i >= 0; i--) { while (stk.length > 0 && nums[stk[stk.length - 1]] < nums[i]) { stk.pop(); } next[i] = stk.length > 0 ? stk[stk.length - 1] : n; stk.push(i); } } let totalSum = 0; for (let i = 0; i < n; i++) { const left = prev[i]; const right = next[i]; const a = left + 1; const b = i; const c = i; const d = right - 1; let start1 = Math.max(a, i - k + 1); let endCandidate1 = d - k + 1; let upper1 = Math.min(b, endCandidate1); let sum1 = 0; if (upper1 >= start1) { const termCount = upper1 - start1 + 1; const first = start1; const last = upper1; const indexSum = (last * (last + 1)) / 2 - ((first - 1) * first) / 2; const constantSum = (k - i) * termCount; sum1 = indexSum + constantSum; } let start2 = upper1 + 1; let end2 = b; start2 = Math.max(start2, a); end2 = Math.min(end2, b); let sum2 = 0; if (start2 <= end2) { const count = end2 - start2 + 1; const term = d - i + 1; sum2 = term * count; } totalSum += nums[i] * (sum1 + sum2); } return totalSum; }; const minSum = computeSum(nums, k, true); const maxSum = computeSum(nums, k, false); return minSum + maxSum; };
3,431
Minimum Unlocked Indices to Sort Nums
Medium
<p>You are given an array <code>nums</code> consisting of integers between 1 and 3, and a <strong>binary</strong> array <code>locked</code> of the same size.</p> <p>We consider <code>nums</code> <strong>sortable</strong> if it can be sorted using adjacent swaps, where a swap between two indices <code>i</code> and <code>i + 1</code> is allowed if <code>nums[i] - nums[i + 1] == 1</code> and <code>locked[i] == 0</code>.</p> <p>In one operation, you can unlock any index <code>i</code> by setting <code>locked[i]</code> to 0.</p> <p>Return the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>sortable</strong>. If it is not possible to make <code>nums</code> sortable, 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 = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>We can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 4 with 5</li> </ul> <p>So, there is no need to unlock any index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>If we unlock indices 2 and 5, we can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 2 with 3</li> <li>swap indices 4 with 5</li> <li>swap indices 5 with 6</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>Even if all indices are unlocked, it can be shown that <code>nums</code> is not sortable.</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>1 &lt;= nums[i] &lt;= 3</code></li> <li><code>locked.length == nums.length</code></li> <li><code>0 &lt;= locked[i] &lt;= 1</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int minUnlockedIndices(vector<int>& nums, vector<int>& locked) { int n = nums.size(); int first2 = n, first3 = n; int last1 = -1, last2 = -1; for (int i = 0; i < n; ++i) { if (nums[i] == 1) { last1 = i; } else if (nums[i] == 2) { first2 = min(first2, i); last2 = i; } else { first3 = min(first3, i); } } if (first3 < last1) { return -1; } int ans = 0; for (int i = 0; i < n; ++i) { if (locked[i] == 1 && ((first2 <= i && i < last1) || (first3 <= i && i < last2))) { ++ans; } } return ans; } };
3,431
Minimum Unlocked Indices to Sort Nums
Medium
<p>You are given an array <code>nums</code> consisting of integers between 1 and 3, and a <strong>binary</strong> array <code>locked</code> of the same size.</p> <p>We consider <code>nums</code> <strong>sortable</strong> if it can be sorted using adjacent swaps, where a swap between two indices <code>i</code> and <code>i + 1</code> is allowed if <code>nums[i] - nums[i + 1] == 1</code> and <code>locked[i] == 0</code>.</p> <p>In one operation, you can unlock any index <code>i</code> by setting <code>locked[i]</code> to 0.</p> <p>Return the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>sortable</strong>. If it is not possible to make <code>nums</code> sortable, 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 = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>We can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 4 with 5</li> </ul> <p>So, there is no need to unlock any index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>If we unlock indices 2 and 5, we can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 2 with 3</li> <li>swap indices 4 with 5</li> <li>swap indices 5 with 6</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>Even if all indices are unlocked, it can be shown that <code>nums</code> is not sortable.</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>1 &lt;= nums[i] &lt;= 3</code></li> <li><code>locked.length == nums.length</code></li> <li><code>0 &lt;= locked[i] &lt;= 1</code></li> </ul>
Array; Hash Table
Go
func minUnlockedIndices(nums []int, locked []int) (ans int) { n := len(nums) first2, first3 := n, n last1, last2 := -1, -1 for i, x := range nums { if x == 1 { last1 = i } else if x == 2 { if i < first2 { first2 = i } last2 = i } else { if i < first3 { first3 = i } } } if first3 < last1 { return -1 } for i, st := range locked { if st == 1 && ((first2 <= i && i < last1) || (first3 <= i && i < last2)) { ans++ } } return ans }
3,431
Minimum Unlocked Indices to Sort Nums
Medium
<p>You are given an array <code>nums</code> consisting of integers between 1 and 3, and a <strong>binary</strong> array <code>locked</code> of the same size.</p> <p>We consider <code>nums</code> <strong>sortable</strong> if it can be sorted using adjacent swaps, where a swap between two indices <code>i</code> and <code>i + 1</code> is allowed if <code>nums[i] - nums[i + 1] == 1</code> and <code>locked[i] == 0</code>.</p> <p>In one operation, you can unlock any index <code>i</code> by setting <code>locked[i]</code> to 0.</p> <p>Return the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>sortable</strong>. If it is not possible to make <code>nums</code> sortable, 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 = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>We can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 4 with 5</li> </ul> <p>So, there is no need to unlock any index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>If we unlock indices 2 and 5, we can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 2 with 3</li> <li>swap indices 4 with 5</li> <li>swap indices 5 with 6</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>Even if all indices are unlocked, it can be shown that <code>nums</code> is not sortable.</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>1 &lt;= nums[i] &lt;= 3</code></li> <li><code>locked.length == nums.length</code></li> <li><code>0 &lt;= locked[i] &lt;= 1</code></li> </ul>
Array; Hash Table
Java
class Solution { public int minUnlockedIndices(int[] nums, int[] locked) { int n = nums.length; int first2 = n, first3 = n; int last1 = -1, last2 = -1; for (int i = 0; i < n; ++i) { if (nums[i] == 1) { last1 = i; } else if (nums[i] == 2) { first2 = Math.min(first2, i); last2 = i; } else { first3 = Math.min(first3, i); } } if (first3 < last1) { return -1; } int ans = 0; for (int i = 0; i < n; ++i) { if (locked[i] == 1 && ((first2 <= i && i < last1) || (first3 <= i && i < last2))) { ++ans; } } return ans; } }
3,431
Minimum Unlocked Indices to Sort Nums
Medium
<p>You are given an array <code>nums</code> consisting of integers between 1 and 3, and a <strong>binary</strong> array <code>locked</code> of the same size.</p> <p>We consider <code>nums</code> <strong>sortable</strong> if it can be sorted using adjacent swaps, where a swap between two indices <code>i</code> and <code>i + 1</code> is allowed if <code>nums[i] - nums[i + 1] == 1</code> and <code>locked[i] == 0</code>.</p> <p>In one operation, you can unlock any index <code>i</code> by setting <code>locked[i]</code> to 0.</p> <p>Return the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>sortable</strong>. If it is not possible to make <code>nums</code> sortable, 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 = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>We can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 4 with 5</li> </ul> <p>So, there is no need to unlock any index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>If we unlock indices 2 and 5, we can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 2 with 3</li> <li>swap indices 4 with 5</li> <li>swap indices 5 with 6</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>Even if all indices are unlocked, it can be shown that <code>nums</code> is not sortable.</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>1 &lt;= nums[i] &lt;= 3</code></li> <li><code>locked.length == nums.length</code></li> <li><code>0 &lt;= locked[i] &lt;= 1</code></li> </ul>
Array; Hash Table
Python
class Solution: def minUnlockedIndices(self, nums: List[int], locked: List[int]) -> int: n = len(nums) first2 = first3 = n last1 = last2 = -1 for i, x in enumerate(nums): if x == 1: last1 = i elif x == 2: first2 = min(first2, i) last2 = i else: first3 = min(first3, i) if first3 < last1: return -1 return sum( st and (first2 <= i < last1 or first3 <= i < last2) for i, st in enumerate(locked) )
3,431
Minimum Unlocked Indices to Sort Nums
Medium
<p>You are given an array <code>nums</code> consisting of integers between 1 and 3, and a <strong>binary</strong> array <code>locked</code> of the same size.</p> <p>We consider <code>nums</code> <strong>sortable</strong> if it can be sorted using adjacent swaps, where a swap between two indices <code>i</code> and <code>i + 1</code> is allowed if <code>nums[i] - nums[i + 1] == 1</code> and <code>locked[i] == 0</code>.</p> <p>In one operation, you can unlock any index <code>i</code> by setting <code>locked[i]</code> to 0.</p> <p>Return the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>sortable</strong>. If it is not possible to make <code>nums</code> sortable, 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 = [1,2,1,2,3,2], locked = [1,0,1,1,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>We can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 4 with 5</li> </ul> <p>So, there is no need to unlock any index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,3,2,2], locked = [1,0,1,1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>If we unlock indices 2 and 5, we can sort <code>nums</code> using the following swaps:</p> <ul> <li>swap indices 1 with 2</li> <li>swap indices 2 with 3</li> <li>swap indices 4 with 5</li> <li>swap indices 5 with 6</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,3,2,1], locked = [0,0,0,0,0,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>Even if all indices are unlocked, it can be shown that <code>nums</code> is not sortable.</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>1 &lt;= nums[i] &lt;= 3</code></li> <li><code>locked.length == nums.length</code></li> <li><code>0 &lt;= locked[i] &lt;= 1</code></li> </ul>
Array; Hash Table
TypeScript
function minUnlockedIndices(nums: number[], locked: number[]): number { const n = nums.length; let [first2, first3] = [n, n]; let [last1, last2] = [-1, -1]; for (let i = 0; i < n; i++) { if (nums[i] === 1) { last1 = i; } else if (nums[i] === 2) { first2 = Math.min(first2, i); last2 = i; } else { first3 = Math.min(first3, i); } } if (first3 < last1) { return -1; } let ans = 0; for (let i = 0; i < n; i++) { if (locked[i] === 1 && ((first2 <= i && i < last1) || (first3 <= i && i < last2))) { ans++; } } return ans; }
3,432
Count Partitions with Even Sum Difference
Easy
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>A <strong>partition</strong> is defined as an index <code>i</code> where <code>0 &lt;= i &lt; n - 1</code>, splitting the array into two <strong>non-empty</strong> subarrays such that:</p> <ul> <li>Left subarray contains indices <code>[0, i]</code>.</li> <li>Right subarray contains indices <code>[i + 1, n - 1]</code>.</li> </ul> <p>Return the number of <strong>partitions</strong> where the <strong>difference</strong> between the <strong>sum</strong> of the left and right subarrays is <strong>even</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 = [10,10,3,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The 4 partitions are:</p> <ul> <li><code>[10]</code>, <code>[10, 3, 7, 6]</code> with a sum difference of <code>10 - 26 = -16</code>, which is even.</li> <li><code>[10, 10]</code>, <code>[3, 7, 6]</code> with a sum difference of <code>20 - 16 = 4</code>, which is even.</li> <li><code>[10, 10, 3]</code>, <code>[7, 6]</code> with a sum difference of <code>23 - 13 = 10</code>, which is even.</li> <li><code>[10, 10, 3, 7]</code>, <code>[6]</code> with a sum difference of <code>30 - 6 = 24</code>, which is even.</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,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No partition results in an even sum difference.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>All partitions result in an even sum difference.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Prefix Sum
C++
class Solution { public: int countPartitions(vector<int>& nums) { int l = 0, r = accumulate(nums.begin(), nums.end(), 0); int ans = 0; for (int i = 0; i < nums.size() - 1; ++i) { l += nums[i]; r -= nums[i]; if ((l - r) % 2 == 0) { ++ans; } } return ans; } };
3,432
Count Partitions with Even Sum Difference
Easy
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>A <strong>partition</strong> is defined as an index <code>i</code> where <code>0 &lt;= i &lt; n - 1</code>, splitting the array into two <strong>non-empty</strong> subarrays such that:</p> <ul> <li>Left subarray contains indices <code>[0, i]</code>.</li> <li>Right subarray contains indices <code>[i + 1, n - 1]</code>.</li> </ul> <p>Return the number of <strong>partitions</strong> where the <strong>difference</strong> between the <strong>sum</strong> of the left and right subarrays is <strong>even</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 = [10,10,3,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The 4 partitions are:</p> <ul> <li><code>[10]</code>, <code>[10, 3, 7, 6]</code> with a sum difference of <code>10 - 26 = -16</code>, which is even.</li> <li><code>[10, 10]</code>, <code>[3, 7, 6]</code> with a sum difference of <code>20 - 16 = 4</code>, which is even.</li> <li><code>[10, 10, 3]</code>, <code>[7, 6]</code> with a sum difference of <code>23 - 13 = 10</code>, which is even.</li> <li><code>[10, 10, 3, 7]</code>, <code>[6]</code> with a sum difference of <code>30 - 6 = 24</code>, which is even.</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,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No partition results in an even sum difference.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>All partitions result in an even sum difference.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Prefix Sum
Go
func countPartitions(nums []int) (ans int) { l, r := 0, 0 for _, x := range nums { r += x } for _, x := range nums[:len(nums)-1] { l += x r -= x if (l-r)%2 == 0 { ans++ } } return }
3,432
Count Partitions with Even Sum Difference
Easy
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>A <strong>partition</strong> is defined as an index <code>i</code> where <code>0 &lt;= i &lt; n - 1</code>, splitting the array into two <strong>non-empty</strong> subarrays such that:</p> <ul> <li>Left subarray contains indices <code>[0, i]</code>.</li> <li>Right subarray contains indices <code>[i + 1, n - 1]</code>.</li> </ul> <p>Return the number of <strong>partitions</strong> where the <strong>difference</strong> between the <strong>sum</strong> of the left and right subarrays is <strong>even</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 = [10,10,3,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The 4 partitions are:</p> <ul> <li><code>[10]</code>, <code>[10, 3, 7, 6]</code> with a sum difference of <code>10 - 26 = -16</code>, which is even.</li> <li><code>[10, 10]</code>, <code>[3, 7, 6]</code> with a sum difference of <code>20 - 16 = 4</code>, which is even.</li> <li><code>[10, 10, 3]</code>, <code>[7, 6]</code> with a sum difference of <code>23 - 13 = 10</code>, which is even.</li> <li><code>[10, 10, 3, 7]</code>, <code>[6]</code> with a sum difference of <code>30 - 6 = 24</code>, which is even.</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,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No partition results in an even sum difference.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>All partitions result in an even sum difference.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Prefix Sum
Java
class Solution { public int countPartitions(int[] nums) { int l = 0, r = 0; for (int x : nums) { r += x; } int ans = 0; for (int i = 0; i < nums.length - 1; ++i) { l += nums[i]; r -= nums[i]; if ((l - r) % 2 == 0) { ++ans; } } return ans; } }
3,432
Count Partitions with Even Sum Difference
Easy
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>A <strong>partition</strong> is defined as an index <code>i</code> where <code>0 &lt;= i &lt; n - 1</code>, splitting the array into two <strong>non-empty</strong> subarrays such that:</p> <ul> <li>Left subarray contains indices <code>[0, i]</code>.</li> <li>Right subarray contains indices <code>[i + 1, n - 1]</code>.</li> </ul> <p>Return the number of <strong>partitions</strong> where the <strong>difference</strong> between the <strong>sum</strong> of the left and right subarrays is <strong>even</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 = [10,10,3,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The 4 partitions are:</p> <ul> <li><code>[10]</code>, <code>[10, 3, 7, 6]</code> with a sum difference of <code>10 - 26 = -16</code>, which is even.</li> <li><code>[10, 10]</code>, <code>[3, 7, 6]</code> with a sum difference of <code>20 - 16 = 4</code>, which is even.</li> <li><code>[10, 10, 3]</code>, <code>[7, 6]</code> with a sum difference of <code>23 - 13 = 10</code>, which is even.</li> <li><code>[10, 10, 3, 7]</code>, <code>[6]</code> with a sum difference of <code>30 - 6 = 24</code>, which is even.</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,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No partition results in an even sum difference.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>All partitions result in an even sum difference.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Prefix Sum
Python
class Solution: def countPartitions(self, nums: List[int]) -> int: l, r = 0, sum(nums) ans = 0 for x in nums[:-1]: l += x r -= x ans += (l - r) % 2 == 0 return ans
3,432
Count Partitions with Even Sum Difference
Easy
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>A <strong>partition</strong> is defined as an index <code>i</code> where <code>0 &lt;= i &lt; n - 1</code>, splitting the array into two <strong>non-empty</strong> subarrays such that:</p> <ul> <li>Left subarray contains indices <code>[0, i]</code>.</li> <li>Right subarray contains indices <code>[i + 1, n - 1]</code>.</li> </ul> <p>Return the number of <strong>partitions</strong> where the <strong>difference</strong> between the <strong>sum</strong> of the left and right subarrays is <strong>even</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 = [10,10,3,7,6]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The 4 partitions are:</p> <ul> <li><code>[10]</code>, <code>[10, 3, 7, 6]</code> with a sum difference of <code>10 - 26 = -16</code>, which is even.</li> <li><code>[10, 10]</code>, <code>[3, 7, 6]</code> with a sum difference of <code>20 - 16 = 4</code>, which is even.</li> <li><code>[10, 10, 3]</code>, <code>[7, 6]</code> with a sum difference of <code>23 - 13 = 10</code>, which is even.</li> <li><code>[10, 10, 3, 7]</code>, <code>[6]</code> with a sum difference of <code>30 - 6 = 24</code>, which is even.</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,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No partition results in an even sum difference.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>All partitions result in an even sum difference.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Prefix Sum
TypeScript
function countPartitions(nums: number[]): number { let l = 0; let r = nums.reduce((a, b) => a + b, 0); let ans = 0; for (const x of nums.slice(0, -1)) { l += x; r -= x; ans += (l - r) % 2 === 0 ? 1 : 0; } return ans; }
3,433
Count Mentions Per User
Medium
<p>You are given an integer <code>numberOfUsers</code> representing the total number of users and an array <code>events</code> of size <code>n x 3</code>.</p> <p>Each <code inline="">events[i]</code> can be either of the following two types:</p> <ol> <li><strong>Message Event:</strong> <code>[&quot;MESSAGE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;mentions_string<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that a set of users was mentioned in a message at <code>timestamp<sub>i</sub></code>.</li> <li>The <code>mentions_string<sub>i</sub></code> string can contain one of the following tokens: <ul> <li><code>id&lt;number&gt;</code>: where <code>&lt;number&gt;</code> is an integer in range <code>[0,numberOfUsers - 1]</code>. There can be <strong>multiple</strong> ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.</li> <li><code>ALL</code>: mentions <strong>all</strong> users.</li> <li><code>HERE</code>: mentions all <strong>online</strong> users.</li> </ul> </li> </ul> </li> <li><strong>Offline Event:</strong> <code>[&quot;OFFLINE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;id<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that the user <code>id<sub>i</sub></code> had become offline at <code>timestamp<sub>i</sub></code> for <strong>60 time units</strong>. The user will automatically be online again at time <code>timestamp<sub>i</sub> + 60</code>.</li> </ul> </li> </ol> <p>Return an array <code>mentions</code> where <code>mentions[i]</code> represents the number of mentions the user with id <code>i</code> has across all <code>MESSAGE</code> events.</p> <p>All users are initially online, and if a user goes offline or comes back online, their status change is processed <em>before</em> handling any message event that occurs at the same timestamp.</p> <p><strong>Note </strong>that a user can be mentioned <strong>multiple</strong> times in a <strong>single</strong> message event, and each mention should be counted <strong>separately</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">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;71&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 71, <code>id0</code> comes back <strong>online</strong> and <code>&quot;HERE&quot;</code> is mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;ALL&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;ALL&quot;</code> is mentioned. This includes offline users, so both <code>id0</code> and <code>id1</code> are mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;OFFLINE&quot;,&quot;10&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;HERE&quot;</code> is mentioned. Because <code>id0</code> is still offline, they will not be mentioned. <code>mentions = [0,1]</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numberOfUsers &lt;= 100</code></li> <li><code>1 &lt;= events.length &lt;= 100</code></li> <li><code>events[i].length == 3</code></li> <li><code>events[i][0]</code> will be one of <code>MESSAGE</code> or <code>OFFLINE</code>.</li> <li><code>1 &lt;= int(events[i][1]) &lt;= 10<sup>5</sup></code></li> <li>The number of <code>id&lt;number&gt;</code> mentions in any <code>&quot;MESSAGE&quot;</code> event is between <code>1</code> and <code>100</code>.</li> <li><code>0 &lt;= &lt;number&gt; &lt;= numberOfUsers - 1</code></li> <li>It is <strong>guaranteed</strong> that the user id referenced in the <code>OFFLINE</code> event is <strong>online</strong> at the time the event occurs.</li> </ul>
Array; Math; Sorting; Simulation
C++
class Solution { public: vector<int> countMentions(int numberOfUsers, vector<vector<string>>& events) { ranges::sort(events, [](const vector<string>& a, const vector<string>& b) { int x = stoi(a[1]); int y = stoi(b[1]); if (x == y) { return a[0][2] < b[0][2]; } return x < y; }); vector<int> ans(numberOfUsers, 0); vector<int> onlineT(numberOfUsers, 0); int lazy = 0; for (const auto& e : events) { string etype = e[0]; int cur = stoi(e[1]); string s = e[2]; if (etype[0] == 'O') { onlineT[stoi(s)] = cur + 60; } else if (s[0] == 'A') { lazy++; } else if (s[0] == 'H') { for (int i = 0; i < numberOfUsers; ++i) { if (onlineT[i] <= cur) { ++ans[i]; } } } else { stringstream ss(s); string token; while (ss >> token) { ans[stoi(token.substr(2))]++; } } } if (lazy > 0) { for (int i = 0; i < numberOfUsers; ++i) { ans[i] += lazy; } } return ans; } };
3,433
Count Mentions Per User
Medium
<p>You are given an integer <code>numberOfUsers</code> representing the total number of users and an array <code>events</code> of size <code>n x 3</code>.</p> <p>Each <code inline="">events[i]</code> can be either of the following two types:</p> <ol> <li><strong>Message Event:</strong> <code>[&quot;MESSAGE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;mentions_string<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that a set of users was mentioned in a message at <code>timestamp<sub>i</sub></code>.</li> <li>The <code>mentions_string<sub>i</sub></code> string can contain one of the following tokens: <ul> <li><code>id&lt;number&gt;</code>: where <code>&lt;number&gt;</code> is an integer in range <code>[0,numberOfUsers - 1]</code>. There can be <strong>multiple</strong> ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.</li> <li><code>ALL</code>: mentions <strong>all</strong> users.</li> <li><code>HERE</code>: mentions all <strong>online</strong> users.</li> </ul> </li> </ul> </li> <li><strong>Offline Event:</strong> <code>[&quot;OFFLINE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;id<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that the user <code>id<sub>i</sub></code> had become offline at <code>timestamp<sub>i</sub></code> for <strong>60 time units</strong>. The user will automatically be online again at time <code>timestamp<sub>i</sub> + 60</code>.</li> </ul> </li> </ol> <p>Return an array <code>mentions</code> where <code>mentions[i]</code> represents the number of mentions the user with id <code>i</code> has across all <code>MESSAGE</code> events.</p> <p>All users are initially online, and if a user goes offline or comes back online, their status change is processed <em>before</em> handling any message event that occurs at the same timestamp.</p> <p><strong>Note </strong>that a user can be mentioned <strong>multiple</strong> times in a <strong>single</strong> message event, and each mention should be counted <strong>separately</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">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;71&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 71, <code>id0</code> comes back <strong>online</strong> and <code>&quot;HERE&quot;</code> is mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;ALL&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;ALL&quot;</code> is mentioned. This includes offline users, so both <code>id0</code> and <code>id1</code> are mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;OFFLINE&quot;,&quot;10&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;HERE&quot;</code> is mentioned. Because <code>id0</code> is still offline, they will not be mentioned. <code>mentions = [0,1]</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numberOfUsers &lt;= 100</code></li> <li><code>1 &lt;= events.length &lt;= 100</code></li> <li><code>events[i].length == 3</code></li> <li><code>events[i][0]</code> will be one of <code>MESSAGE</code> or <code>OFFLINE</code>.</li> <li><code>1 &lt;= int(events[i][1]) &lt;= 10<sup>5</sup></code></li> <li>The number of <code>id&lt;number&gt;</code> mentions in any <code>&quot;MESSAGE&quot;</code> event is between <code>1</code> and <code>100</code>.</li> <li><code>0 &lt;= &lt;number&gt; &lt;= numberOfUsers - 1</code></li> <li>It is <strong>guaranteed</strong> that the user id referenced in the <code>OFFLINE</code> event is <strong>online</strong> at the time the event occurs.</li> </ul>
Array; Math; Sorting; Simulation
Go
func countMentions(numberOfUsers int, events [][]string) []int { sort.Slice(events, func(i, j int) bool { x, _ := strconv.Atoi(events[i][1]) y, _ := strconv.Atoi(events[j][1]) if x == y { return events[i][0][2] < events[j][0][2] } return x < y }) ans := make([]int, numberOfUsers) onlineT := make([]int, numberOfUsers) lazy := 0 for _, e := range events { etype := e[0] cur, _ := strconv.Atoi(e[1]) s := e[2] if etype[0] == 'O' { userID, _ := strconv.Atoi(s) onlineT[userID] = cur + 60 } else if s[0] == 'A' { lazy++ } else if s[0] == 'H' { for i := 0; i < numberOfUsers; i++ { if onlineT[i] <= cur { ans[i]++ } } } else { mentions := strings.Split(s, " ") for _, m := range mentions { userID, _ := strconv.Atoi(m[2:]) ans[userID]++ } } } if lazy > 0 { for i := 0; i < numberOfUsers; i++ { ans[i] += lazy } } return ans }
3,433
Count Mentions Per User
Medium
<p>You are given an integer <code>numberOfUsers</code> representing the total number of users and an array <code>events</code> of size <code>n x 3</code>.</p> <p>Each <code inline="">events[i]</code> can be either of the following two types:</p> <ol> <li><strong>Message Event:</strong> <code>[&quot;MESSAGE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;mentions_string<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that a set of users was mentioned in a message at <code>timestamp<sub>i</sub></code>.</li> <li>The <code>mentions_string<sub>i</sub></code> string can contain one of the following tokens: <ul> <li><code>id&lt;number&gt;</code>: where <code>&lt;number&gt;</code> is an integer in range <code>[0,numberOfUsers - 1]</code>. There can be <strong>multiple</strong> ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.</li> <li><code>ALL</code>: mentions <strong>all</strong> users.</li> <li><code>HERE</code>: mentions all <strong>online</strong> users.</li> </ul> </li> </ul> </li> <li><strong>Offline Event:</strong> <code>[&quot;OFFLINE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;id<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that the user <code>id<sub>i</sub></code> had become offline at <code>timestamp<sub>i</sub></code> for <strong>60 time units</strong>. The user will automatically be online again at time <code>timestamp<sub>i</sub> + 60</code>.</li> </ul> </li> </ol> <p>Return an array <code>mentions</code> where <code>mentions[i]</code> represents the number of mentions the user with id <code>i</code> has across all <code>MESSAGE</code> events.</p> <p>All users are initially online, and if a user goes offline or comes back online, their status change is processed <em>before</em> handling any message event that occurs at the same timestamp.</p> <p><strong>Note </strong>that a user can be mentioned <strong>multiple</strong> times in a <strong>single</strong> message event, and each mention should be counted <strong>separately</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">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;71&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 71, <code>id0</code> comes back <strong>online</strong> and <code>&quot;HERE&quot;</code> is mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;ALL&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;ALL&quot;</code> is mentioned. This includes offline users, so both <code>id0</code> and <code>id1</code> are mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;OFFLINE&quot;,&quot;10&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;HERE&quot;</code> is mentioned. Because <code>id0</code> is still offline, they will not be mentioned. <code>mentions = [0,1]</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numberOfUsers &lt;= 100</code></li> <li><code>1 &lt;= events.length &lt;= 100</code></li> <li><code>events[i].length == 3</code></li> <li><code>events[i][0]</code> will be one of <code>MESSAGE</code> or <code>OFFLINE</code>.</li> <li><code>1 &lt;= int(events[i][1]) &lt;= 10<sup>5</sup></code></li> <li>The number of <code>id&lt;number&gt;</code> mentions in any <code>&quot;MESSAGE&quot;</code> event is between <code>1</code> and <code>100</code>.</li> <li><code>0 &lt;= &lt;number&gt; &lt;= numberOfUsers - 1</code></li> <li>It is <strong>guaranteed</strong> that the user id referenced in the <code>OFFLINE</code> event is <strong>online</strong> at the time the event occurs.</li> </ul>
Array; Math; Sorting; Simulation
Java
class Solution { public int[] countMentions(int numberOfUsers, List<List<String>> events) { events.sort((a, b) -> { int x = Integer.parseInt(a.get(1)); int y = Integer.parseInt(b.get(1)); if (x == y) { return a.get(0).charAt(2) - b.get(0).charAt(2); } return x - y; }); int[] ans = new int[numberOfUsers]; int[] onlineT = new int[numberOfUsers]; int lazy = 0; for (var e : events) { String etype = e.get(0); int cur = Integer.parseInt(e.get(1)); String s = e.get(2); if (etype.charAt(0) == 'O') { onlineT[Integer.parseInt(s)] = cur + 60; } else if (s.charAt(0) == 'A') { ++lazy; } else if (s.charAt(0) == 'H') { for (int i = 0; i < numberOfUsers; ++i) { if (onlineT[i] <= cur) { ++ans[i]; } } } else { for (var a : s.split(" ")) { ++ans[Integer.parseInt(a.substring(2))]; } } } if (lazy > 0) { for (int i = 0; i < numberOfUsers; ++i) { ans[i] += lazy; } } return ans; } }
3,433
Count Mentions Per User
Medium
<p>You are given an integer <code>numberOfUsers</code> representing the total number of users and an array <code>events</code> of size <code>n x 3</code>.</p> <p>Each <code inline="">events[i]</code> can be either of the following two types:</p> <ol> <li><strong>Message Event:</strong> <code>[&quot;MESSAGE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;mentions_string<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that a set of users was mentioned in a message at <code>timestamp<sub>i</sub></code>.</li> <li>The <code>mentions_string<sub>i</sub></code> string can contain one of the following tokens: <ul> <li><code>id&lt;number&gt;</code>: where <code>&lt;number&gt;</code> is an integer in range <code>[0,numberOfUsers - 1]</code>. There can be <strong>multiple</strong> ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.</li> <li><code>ALL</code>: mentions <strong>all</strong> users.</li> <li><code>HERE</code>: mentions all <strong>online</strong> users.</li> </ul> </li> </ul> </li> <li><strong>Offline Event:</strong> <code>[&quot;OFFLINE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;id<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that the user <code>id<sub>i</sub></code> had become offline at <code>timestamp<sub>i</sub></code> for <strong>60 time units</strong>. The user will automatically be online again at time <code>timestamp<sub>i</sub> + 60</code>.</li> </ul> </li> </ol> <p>Return an array <code>mentions</code> where <code>mentions[i]</code> represents the number of mentions the user with id <code>i</code> has across all <code>MESSAGE</code> events.</p> <p>All users are initially online, and if a user goes offline or comes back online, their status change is processed <em>before</em> handling any message event that occurs at the same timestamp.</p> <p><strong>Note </strong>that a user can be mentioned <strong>multiple</strong> times in a <strong>single</strong> message event, and each mention should be counted <strong>separately</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">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;71&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 71, <code>id0</code> comes back <strong>online</strong> and <code>&quot;HERE&quot;</code> is mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;ALL&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;ALL&quot;</code> is mentioned. This includes offline users, so both <code>id0</code> and <code>id1</code> are mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;OFFLINE&quot;,&quot;10&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;HERE&quot;</code> is mentioned. Because <code>id0</code> is still offline, they will not be mentioned. <code>mentions = [0,1]</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numberOfUsers &lt;= 100</code></li> <li><code>1 &lt;= events.length &lt;= 100</code></li> <li><code>events[i].length == 3</code></li> <li><code>events[i][0]</code> will be one of <code>MESSAGE</code> or <code>OFFLINE</code>.</li> <li><code>1 &lt;= int(events[i][1]) &lt;= 10<sup>5</sup></code></li> <li>The number of <code>id&lt;number&gt;</code> mentions in any <code>&quot;MESSAGE&quot;</code> event is between <code>1</code> and <code>100</code>.</li> <li><code>0 &lt;= &lt;number&gt; &lt;= numberOfUsers - 1</code></li> <li>It is <strong>guaranteed</strong> that the user id referenced in the <code>OFFLINE</code> event is <strong>online</strong> at the time the event occurs.</li> </ul>
Array; Math; Sorting; Simulation
Python
class Solution: def countMentions(self, numberOfUsers: int, events: List[List[str]]) -> List[int]: events.sort(key=lambda e: (int(e[1]), e[0][2])) ans = [0] * numberOfUsers online_t = [0] * numberOfUsers lazy = 0 for etype, ts, s in events: cur = int(ts) if etype[0] == "O": online_t[int(s)] = cur + 60 elif s[0] == "A": lazy += 1 elif s[0] == "H": for i, t in enumerate(online_t): if t <= cur: ans[i] += 1 else: for a in s.split(): ans[int(a[2:])] += 1 if lazy: for i in range(numberOfUsers): ans[i] += lazy return ans
3,433
Count Mentions Per User
Medium
<p>You are given an integer <code>numberOfUsers</code> representing the total number of users and an array <code>events</code> of size <code>n x 3</code>.</p> <p>Each <code inline="">events[i]</code> can be either of the following two types:</p> <ol> <li><strong>Message Event:</strong> <code>[&quot;MESSAGE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;mentions_string<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that a set of users was mentioned in a message at <code>timestamp<sub>i</sub></code>.</li> <li>The <code>mentions_string<sub>i</sub></code> string can contain one of the following tokens: <ul> <li><code>id&lt;number&gt;</code>: where <code>&lt;number&gt;</code> is an integer in range <code>[0,numberOfUsers - 1]</code>. There can be <strong>multiple</strong> ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.</li> <li><code>ALL</code>: mentions <strong>all</strong> users.</li> <li><code>HERE</code>: mentions all <strong>online</strong> users.</li> </ul> </li> </ul> </li> <li><strong>Offline Event:</strong> <code>[&quot;OFFLINE&quot;, &quot;timestamp<sub>i</sub>&quot;, &quot;id<sub>i</sub>&quot;]</code> <ul> <li>This event indicates that the user <code>id<sub>i</sub></code> had become offline at <code>timestamp<sub>i</sub></code> for <strong>60 time units</strong>. The user will automatically be online again at time <code>timestamp<sub>i</sub> + 60</code>.</li> </ul> </li> </ol> <p>Return an array <code>mentions</code> where <code>mentions[i]</code> represents the number of mentions the user with id <code>i</code> has across all <code>MESSAGE</code> events.</p> <p>All users are initially online, and if a user goes offline or comes back online, their status change is processed <em>before</em> handling any message event that occurs at the same timestamp.</p> <p><strong>Note </strong>that a user can be mentioned <strong>multiple</strong> times in a <strong>single</strong> message event, and each mention should be counted <strong>separately</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">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;71&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 71, <code>id0</code> comes back <strong>online</strong> and <code>&quot;HERE&quot;</code> is mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;MESSAGE&quot;,&quot;10&quot;,&quot;id1 id0&quot;],[&quot;OFFLINE&quot;,&quot;11&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;ALL&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id1</code> and <code>id0</code> are mentioned. <code>mentions = [1,1]</code></p> <p>At timestamp 11, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;ALL&quot;</code> is mentioned. This includes offline users, so both <code>id0</code> and <code>id1</code> are mentioned. <code>mentions = [2,2]</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numberOfUsers = 2, events = [[&quot;OFFLINE&quot;,&quot;10&quot;,&quot;0&quot;],[&quot;MESSAGE&quot;,&quot;12&quot;,&quot;HERE&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>Initially, all users are online.</p> <p>At timestamp 10, <code>id0</code> goes <strong>offline.</strong></p> <p>At timestamp 12, <code>&quot;HERE&quot;</code> is mentioned. Because <code>id0</code> is still offline, they will not be mentioned. <code>mentions = [0,1]</code></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numberOfUsers &lt;= 100</code></li> <li><code>1 &lt;= events.length &lt;= 100</code></li> <li><code>events[i].length == 3</code></li> <li><code>events[i][0]</code> will be one of <code>MESSAGE</code> or <code>OFFLINE</code>.</li> <li><code>1 &lt;= int(events[i][1]) &lt;= 10<sup>5</sup></code></li> <li>The number of <code>id&lt;number&gt;</code> mentions in any <code>&quot;MESSAGE&quot;</code> event is between <code>1</code> and <code>100</code>.</li> <li><code>0 &lt;= &lt;number&gt; &lt;= numberOfUsers - 1</code></li> <li>It is <strong>guaranteed</strong> that the user id referenced in the <code>OFFLINE</code> event is <strong>online</strong> at the time the event occurs.</li> </ul>
Array; Math; Sorting; Simulation
TypeScript
function countMentions(numberOfUsers: number, events: string[][]): number[] { events.sort((a, b) => { const x = +a[1]; const y = +b[1]; if (x === y) { return a[0].charAt(2) < b[0].charAt(2) ? -1 : 1; } return x - y; }); const ans: number[] = Array(numberOfUsers).fill(0); const onlineT: number[] = Array(numberOfUsers).fill(0); let lazy = 0; for (const [etype, ts, s] of events) { const cur = +ts; if (etype.charAt(0) === 'O') { const userID = +s; onlineT[userID] = cur + 60; } else if (s.charAt(0) === 'A') { lazy++; } else if (s.charAt(0) === 'H') { for (let i = 0; i < numberOfUsers; i++) { if (onlineT[i] <= cur) { ans[i]++; } } } else { const mentions = s.split(' '); for (const m of mentions) { const userID = +m.slice(2); ans[userID]++; } } } if (lazy > 0) { for (let i = 0; i < numberOfUsers; i++) { ans[i] += lazy; } } return ans; }
3,436
Find Valid Emails
Easy
<p>Table: <code>Users</code></p> <pre> +-----------------+---------+ | Column Name | Type | +-----------------+---------+ | user_id | int | | email | varchar | +-----------------+---------+ (user_id) is the unique key for this table. Each row contains a user&#39;s unique ID and email address. </pre> <p>Write a solution to find all the <strong>valid email addresses</strong>. A valid email address meets the following criteria:</p> <ul> <li>It contains exactly one <code>@</code> symbol.</li> <li>It ends with <code>.com</code>.</li> <li>The part before the <code>@</code> symbol contains only <strong>alphanumeric</strong> characters and <strong>underscores</strong>.</li> <li>The part after the <code>@</code> symbol and before <code>.com</code> contains a domain name <strong>that contains only letters</strong>.</li> </ul> <p>Return<em> the result table ordered by</em> <code>user_id</code> <em>in</em> <strong>ascending </strong><em>order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Users table:</p> <pre class="example-io"> +---------+---------------------+ | user_id | email | +---------+---------------------+ | 1 | [email protected] | | 2 | bob_at_example.com | | 3 | [email protected] | | 4 | [email protected] | | 5 | eve@invalid | +---------+---------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+-------------------+ | user_id | email | +---------+-------------------+ | 1 | [email protected] | | 4 | [email protected] | +---------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>[email protected]</strong> is valid because it contains one <code>@</code>, alice&nbsp;is alphanumeric, and example.com&nbsp;starts with a letter and ends with .com.</li> <li><strong>bob_at_example.com</strong> is invalid because it contains an underscore instead of an <code>@</code>.</li> <li><strong>[email protected]</strong> is invalid because the domain does not end with <code>.com</code>.</li> <li><strong>[email protected]</strong> is valid because it meets all criteria.</li> <li><strong>eve@invalid</strong> is invalid because the domain does not end with <code>.com</code>.</li> </ul> <p>Result table is ordered by user_id in ascending order.</p> </div>
Database
Python
import pandas as pd def find_valid_emails(users: pd.DataFrame) -> pd.DataFrame: email_pattern = r"^[A-Za-z0-9_]+@[A-Za-z][A-Za-z0-9]*\.com$" valid_emails = users[users["email"].str.match(email_pattern)] valid_emails = valid_emails.sort_values(by="user_id") return valid_emails
3,436
Find Valid Emails
Easy
<p>Table: <code>Users</code></p> <pre> +-----------------+---------+ | Column Name | Type | +-----------------+---------+ | user_id | int | | email | varchar | +-----------------+---------+ (user_id) is the unique key for this table. Each row contains a user&#39;s unique ID and email address. </pre> <p>Write a solution to find all the <strong>valid email addresses</strong>. A valid email address meets the following criteria:</p> <ul> <li>It contains exactly one <code>@</code> symbol.</li> <li>It ends with <code>.com</code>.</li> <li>The part before the <code>@</code> symbol contains only <strong>alphanumeric</strong> characters and <strong>underscores</strong>.</li> <li>The part after the <code>@</code> symbol and before <code>.com</code> contains a domain name <strong>that contains only letters</strong>.</li> </ul> <p>Return<em> the result table ordered by</em> <code>user_id</code> <em>in</em> <strong>ascending </strong><em>order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Users table:</p> <pre class="example-io"> +---------+---------------------+ | user_id | email | +---------+---------------------+ | 1 | [email protected] | | 2 | bob_at_example.com | | 3 | [email protected] | | 4 | [email protected] | | 5 | eve@invalid | +---------+---------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+-------------------+ | user_id | email | +---------+-------------------+ | 1 | [email protected] | | 4 | [email protected] | +---------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>[email protected]</strong> is valid because it contains one <code>@</code>, alice&nbsp;is alphanumeric, and example.com&nbsp;starts with a letter and ends with .com.</li> <li><strong>bob_at_example.com</strong> is invalid because it contains an underscore instead of an <code>@</code>.</li> <li><strong>[email protected]</strong> is invalid because the domain does not end with <code>.com</code>.</li> <li><strong>[email protected]</strong> is valid because it meets all criteria.</li> <li><strong>eve@invalid</strong> is invalid because the domain does not end with <code>.com</code>.</li> </ul> <p>Result table is ordered by user_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT user_id, email FROM Users WHERE email REGEXP '^[A-Za-z0-9_]+@[A-Za-z][A-Za-z0-9]*\\.com$' ORDER BY 1;
3,437
Permutations III
Medium
<p>Given an integer <code>n</code>, an <strong>alternating permutation</strong> is a permutation of the first <code>n</code> positive integers such that no <strong>two</strong> adjacent elements are <strong>both</strong> odd or <strong>both</strong> even.</p> <p>Return <em>all such </em><strong>alternating permutations</strong> sorted in lexicographical order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2],[2,1]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3],[3,2,1]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<int>> permute(int n) { vector<vector<int>> ans; vector<bool> vis(n); vector<int> t; auto dfs = [&](this auto&& dfs, int i) -> void { if (i >= n) { ans.push_back(t); return; } for (int j = 1; j <= n; ++j) { if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { vis[j] = true; t.push_back(j); dfs(i + 1); t.pop_back(); vis[j] = false; } } }; dfs(0); return ans; } };
3,437
Permutations III
Medium
<p>Given an integer <code>n</code>, an <strong>alternating permutation</strong> is a permutation of the first <code>n</code> positive integers such that no <strong>two</strong> adjacent elements are <strong>both</strong> odd or <strong>both</strong> even.</p> <p>Return <em>all such </em><strong>alternating permutations</strong> sorted in lexicographical order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2],[2,1]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3],[3,2,1]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> </ul>
Array; Backtracking
Go
func permute(n int) (ans [][]int) { vis := make([]bool, n+1) t := make([]int, n) var dfs func(i int) dfs = func(i int) { if i >= n { ans = append(ans, slices.Clone(t)) return } for j := 1; j <= n; j++ { if !vis[j] && (i == 0 || t[i-1]%2 != j%2) { vis[j] = true t[i] = j dfs(i + 1) vis[j] = false } } } dfs(0) return }
3,437
Permutations III
Medium
<p>Given an integer <code>n</code>, an <strong>alternating permutation</strong> is a permutation of the first <code>n</code> positive integers such that no <strong>two</strong> adjacent elements are <strong>both</strong> odd or <strong>both</strong> even.</p> <p>Return <em>all such </em><strong>alternating permutations</strong> sorted in lexicographical order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2],[2,1]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3],[3,2,1]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> </ul>
Array; Backtracking
Java
class Solution { private List<int[]> ans = new ArrayList<>(); private boolean[] vis; private int[] t; private int n; public int[][] permute(int n) { this.n = n; t = new int[n]; vis = new boolean[n + 1]; dfs(0); return ans.toArray(new int[0][]); } private void dfs(int i) { if (i >= n) { ans.add(t.clone()); return; } for (int j = 1; j <= n; ++j) { if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { vis[j] = true; t[i] = j; dfs(i + 1); vis[j] = false; } } } }
3,437
Permutations III
Medium
<p>Given an integer <code>n</code>, an <strong>alternating permutation</strong> is a permutation of the first <code>n</code> positive integers such that no <strong>two</strong> adjacent elements are <strong>both</strong> odd or <strong>both</strong> even.</p> <p>Return <em>all such </em><strong>alternating permutations</strong> sorted in lexicographical order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2],[2,1]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3],[3,2,1]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> </ul>
Array; Backtracking
Python
class Solution: def permute(self, n: int) -> List[List[int]]: def dfs(i: int) -> None: if i >= n: ans.append(t[:]) return for j in range(1, n + 1): if not vis[j] and (i == 0 or t[-1] % 2 != j % 2): t.append(j) vis[j] = True dfs(i + 1) vis[j] = False t.pop() ans = [] t = [] vis = [False] * (n + 1) dfs(0) return ans
3,437
Permutations III
Medium
<p>Given an integer <code>n</code>, an <strong>alternating permutation</strong> is a permutation of the first <code>n</code> positive integers such that no <strong>two</strong> adjacent elements are <strong>both</strong> odd or <strong>both</strong> even.</p> <p>Return <em>all such </em><strong>alternating permutations</strong> sorted in lexicographical order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2],[2,1]]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3],[3,2,1]]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> </ul>
Array; Backtracking
TypeScript
function permute(n: number): number[][] { const ans: number[][] = []; const vis: boolean[] = Array(n).fill(false); const t: number[] = Array(n).fill(0); const dfs = (i: number) => { if (i >= n) { ans.push([...t]); return; } for (let j = 1; j <= n; ++j) { if (!vis[j] && (i === 0 || t[i - 1] % 2 !== j % 2)) { vis[j] = true; t[i] = j; dfs(i + 1); vis[j] = false; } } }; dfs(0); return ans; }
3,438
Find Valid Pair of Adjacent Digits in String
Easy
<p>You are given a string <code>s</code> consisting only of digits. A <strong>valid pair</strong> is defined as two <strong>adjacent</strong> digits in <code>s</code> such that:</p> <ul> <li>The first digit is <strong>not equal</strong> to the second.</li> <li>Each digit in the pair appears in <code>s</code> <strong>exactly</strong> as many times as its numeric value.</li> </ul> <p>Return the first <strong>valid pair</strong> found in the string <code>s</code> when traversing from left to right. If no valid pair exists, return an empty 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;2523533&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;23&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;3&#39;</code> appears 3 times. Each digit in the pair <code>&quot;23&quot;</code> appears in <code>s</code> exactly as many times as its numeric value. Hence, the output is <code>&quot;23&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;221&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;21&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;1&#39;</code> appears 1 time. Hence, the output is <code>&quot;21&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;22&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There are no valid adjacent pairs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> only consists of digits from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Hash Table; String; Counting
C++
class Solution { public: string findValidPair(string s) { int cnt[10]{}; for (char c : s) { ++cnt[c - '0']; } for (int i = 1; i < s.size(); ++i) { int x = s[i - 1] - '0'; int y = s[i] - '0'; if (x != y && cnt[x] == x && cnt[y] == y) { return s.substr(i - 1, 2); } } return ""; } };
3,438
Find Valid Pair of Adjacent Digits in String
Easy
<p>You are given a string <code>s</code> consisting only of digits. A <strong>valid pair</strong> is defined as two <strong>adjacent</strong> digits in <code>s</code> such that:</p> <ul> <li>The first digit is <strong>not equal</strong> to the second.</li> <li>Each digit in the pair appears in <code>s</code> <strong>exactly</strong> as many times as its numeric value.</li> </ul> <p>Return the first <strong>valid pair</strong> found in the string <code>s</code> when traversing from left to right. If no valid pair exists, return an empty 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;2523533&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;23&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;3&#39;</code> appears 3 times. Each digit in the pair <code>&quot;23&quot;</code> appears in <code>s</code> exactly as many times as its numeric value. Hence, the output is <code>&quot;23&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;221&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;21&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;1&#39;</code> appears 1 time. Hence, the output is <code>&quot;21&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;22&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There are no valid adjacent pairs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> only consists of digits from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Hash Table; String; Counting
Go
func findValidPair(s string) string { cnt := [10]int{} for _, c := range s { cnt[c-'0']++ } for i := 1; i < len(s); i++ { x, y := int(s[i-1]-'0'), int(s[i]-'0') if x != y && cnt[x] == x && cnt[y] == y { return s[i-1 : i+1] } } return "" }
3,438
Find Valid Pair of Adjacent Digits in String
Easy
<p>You are given a string <code>s</code> consisting only of digits. A <strong>valid pair</strong> is defined as two <strong>adjacent</strong> digits in <code>s</code> such that:</p> <ul> <li>The first digit is <strong>not equal</strong> to the second.</li> <li>Each digit in the pair appears in <code>s</code> <strong>exactly</strong> as many times as its numeric value.</li> </ul> <p>Return the first <strong>valid pair</strong> found in the string <code>s</code> when traversing from left to right. If no valid pair exists, return an empty 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;2523533&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;23&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;3&#39;</code> appears 3 times. Each digit in the pair <code>&quot;23&quot;</code> appears in <code>s</code> exactly as many times as its numeric value. Hence, the output is <code>&quot;23&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;221&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;21&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;1&#39;</code> appears 1 time. Hence, the output is <code>&quot;21&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;22&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There are no valid adjacent pairs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> only consists of digits from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Hash Table; String; Counting
Java
class Solution { public String findValidPair(String s) { int[] cnt = new int[10]; for (char c : s.toCharArray()) { ++cnt[c - '0']; } for (int i = 1; i < s.length(); ++i) { int x = s.charAt(i - 1) - '0'; int y = s.charAt(i) - '0'; if (x != y && cnt[x] == x && cnt[y] == y) { return s.substring(i - 1, i + 1); } } return ""; } }
3,438
Find Valid Pair of Adjacent Digits in String
Easy
<p>You are given a string <code>s</code> consisting only of digits. A <strong>valid pair</strong> is defined as two <strong>adjacent</strong> digits in <code>s</code> such that:</p> <ul> <li>The first digit is <strong>not equal</strong> to the second.</li> <li>Each digit in the pair appears in <code>s</code> <strong>exactly</strong> as many times as its numeric value.</li> </ul> <p>Return the first <strong>valid pair</strong> found in the string <code>s</code> when traversing from left to right. If no valid pair exists, return an empty 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;2523533&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;23&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;3&#39;</code> appears 3 times. Each digit in the pair <code>&quot;23&quot;</code> appears in <code>s</code> exactly as many times as its numeric value. Hence, the output is <code>&quot;23&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;221&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;21&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;1&#39;</code> appears 1 time. Hence, the output is <code>&quot;21&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;22&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There are no valid adjacent pairs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> only consists of digits from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Hash Table; String; Counting
Python
class Solution: def findValidPair(self, s: str) -> str: cnt = [0] * 10 for x in map(int, s): cnt[x] += 1 for x, y in pairwise(map(int, s)): if x != y and cnt[x] == x and cnt[y] == y: return f"{x}{y}" return ""
3,438
Find Valid Pair of Adjacent Digits in String
Easy
<p>You are given a string <code>s</code> consisting only of digits. A <strong>valid pair</strong> is defined as two <strong>adjacent</strong> digits in <code>s</code> such that:</p> <ul> <li>The first digit is <strong>not equal</strong> to the second.</li> <li>Each digit in the pair appears in <code>s</code> <strong>exactly</strong> as many times as its numeric value.</li> </ul> <p>Return the first <strong>valid pair</strong> found in the string <code>s</code> when traversing from left to right. If no valid pair exists, return an empty 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;2523533&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;23&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;3&#39;</code> appears 3 times. Each digit in the pair <code>&quot;23&quot;</code> appears in <code>s</code> exactly as many times as its numeric value. Hence, the output is <code>&quot;23&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;221&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;21&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Digit <code>&#39;2&#39;</code> appears 2 times and digit <code>&#39;1&#39;</code> appears 1 time. Hence, the output is <code>&quot;21&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;22&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <p>There are no valid adjacent pairs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> only consists of digits from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Hash Table; String; Counting
TypeScript
function findValidPair(s: string): string { const cnt: number[] = Array(10).fill(0); for (const c of s) { ++cnt[+c]; } for (let i = 1; i < s.length; ++i) { const x = +s[i - 1]; const y = +s[i]; if (x !== y && cnt[x] === x && cnt[y] === y) { return `${x}${y}`; } } return ''; }
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
C++
class Solution { public: int maxFreeTime(int eventTime, int k, vector<int>& startTime, vector<int>& endTime) { int n = endTime.size(); vector<int> nums(n + 1); nums[0] = startTime[0]; for (int i = 1; i < n; ++i) { nums[i] = startTime[i] - endTime[i - 1]; } nums[n] = eventTime - endTime[n - 1]; int ans = 0, s = 0; for (int i = 0; i <= n; ++i) { s += nums[i]; if (i >= k) { ans = max(ans, s); s -= nums[i - k]; } } return ans; } };
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
Go
func maxFreeTime(eventTime int, k int, startTime []int, endTime []int) int { n := len(endTime) nums := make([]int, n+1) nums[0] = startTime[0] for i := 1; i < n; i++ { nums[i] = startTime[i] - endTime[i-1] } nums[n] = eventTime - endTime[n-1] ans, s := 0, 0 for i := 0; i <= n; i++ { s += nums[i] if i >= k { ans = max(ans, s) s -= nums[i-k] } } return ans }
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
Java
class Solution { public int maxFreeTime(int eventTime, int k, int[] startTime, int[] endTime) { int n = endTime.length; int[] nums = new int[n + 1]; nums[0] = startTime[0]; for (int i = 1; i < n; ++i) { nums[i] = startTime[i] - endTime[i - 1]; } nums[n] = eventTime - endTime[n - 1]; int ans = 0, s = 0; for (int i = 0; i <= n; ++i) { s += nums[i]; if (i >= k) { ans = Math.max(ans, s); s -= nums[i - k]; } } return ans; } }
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
Python
class Solution: def maxFreeTime( self, eventTime: int, k: int, startTime: List[int], endTime: List[int] ) -> int: nums = [startTime[0]] for i in range(1, len(endTime)): nums.append(startTime[i] - endTime[i - 1]) nums.append(eventTime - endTime[-1]) ans = s = 0 for i, x in enumerate(nums): s += x if i >= k: ans = max(ans, s) s -= nums[i - k] return ans
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
Rust
impl Solution { pub fn max_free_time(event_time: i32, k: i32, start_time: Vec<i32>, end_time: Vec<i32>) -> i32 { let n = end_time.len(); let mut nums = vec![0; n + 1]; nums[0] = start_time[0]; for i in 1..n { nums[i] = start_time[i] - end_time[i - 1]; } nums[n] = event_time - end_time[n - 1]; let mut ans = 0; let mut s = 0; for i in 0..=n { s += nums[i]; if i as i32 >= k { ans = ans.max(s); s -= nums[i - k as usize]; } } ans } }
3,439
Reschedule Meetings for Maximum Free Time I
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event, where the event occurs from time <code>t = 0</code> to time <code>t = eventTime</code>.</p> <p>You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>. These represent the start and end time of <code>n</code> <strong>non-overlapping</strong> meetings, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]]</code>.</p> <p>You can reschedule <strong>at most</strong> <code>k</code> meetings by moving their start time while maintaining the <strong>same duration</strong>, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>The <strong>relative</strong> order of all the meetings should stay the<em> same</em> and they should remain non-overlapping.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3439.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20I/images/example1_rescheduled.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[2, 4]</code> to <code>[1, 3]</code>, leaving no meetings during the time <code>[3, 9]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Sliding Window
TypeScript
function maxFreeTime(eventTime: number, k: number, startTime: number[], endTime: number[]): number { const n = endTime.length; const nums: number[] = new Array(n + 1); nums[0] = startTime[0]; for (let i = 1; i < n; i++) { nums[i] = startTime[i] - endTime[i - 1]; } nums[n] = eventTime - endTime[n - 1]; let [ans, s] = [0, 0]; for (let i = 0; i <= n; i++) { s += nums[i]; if (i >= k) { ans = Math.max(ans, s); s -= nums[i - k]; } } return ans; }
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
C++
class Solution { public: int maxFreeTime(int eventTime, vector<int>& startTime, vector<int>& endTime) { int n = startTime.size(); vector<int> pre(n), suf(n); pre[0] = startTime[0]; suf[n - 1] = eventTime - endTime[n - 1]; for (int i = 1; i < n; ++i) { pre[i] = max(pre[i - 1], startTime[i] - endTime[i - 1]); } for (int i = n - 2; i >= 0; --i) { suf[i] = max(suf[i + 1], startTime[i + 1] - endTime[i]); } int ans = 0; for (int i = 0; i < n; ++i) { int l = (i == 0) ? 0 : endTime[i - 1]; int r = (i == n - 1) ? eventTime : startTime[i + 1]; int w = endTime[i] - startTime[i]; ans = max(ans, r - l - w); if (i > 0 && pre[i - 1] >= w) { ans = max(ans, r - l); } else if (i + 1 < n && suf[i + 1] >= w) { ans = max(ans, r - l); } } return ans; } };
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
Go
func maxFreeTime(eventTime int, startTime []int, endTime []int) int { n := len(startTime) pre := make([]int, n) suf := make([]int, n) pre[0] = startTime[0] suf[n-1] = eventTime - endTime[n-1] for i := 1; i < n; i++ { pre[i] = max(pre[i-1], startTime[i]-endTime[i-1]) } for i := n - 2; i >= 0; i-- { suf[i] = max(suf[i+1], startTime[i+1]-endTime[i]) } ans := 0 for i := 0; i < n; i++ { l := 0 if i > 0 { l = endTime[i-1] } r := eventTime if i < n-1 { r = startTime[i+1] } w := endTime[i] - startTime[i] ans = max(ans, r-l-w) if i > 0 && pre[i-1] >= w { ans = max(ans, r-l) } else if i+1 < n && suf[i+1] >= w { ans = max(ans, r-l) } } return ans }
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
Java
class Solution { public int maxFreeTime(int eventTime, int[] startTime, int[] endTime) { int n = startTime.length; int[] pre = new int[n]; int[] suf = new int[n]; pre[0] = startTime[0]; suf[n - 1] = eventTime - endTime[n - 1]; for (int i = 1; i < n; i++) { pre[i] = Math.max(pre[i - 1], startTime[i] - endTime[i - 1]); } for (int i = n - 2; i >= 0; i--) { suf[i] = Math.max(suf[i + 1], startTime[i + 1] - endTime[i]); } int ans = 0; for (int i = 0; i < n; i++) { int l = (i == 0) ? 0 : endTime[i - 1]; int r = (i == n - 1) ? eventTime : startTime[i + 1]; int w = endTime[i] - startTime[i]; ans = Math.max(ans, r - l - w); if (i > 0 && pre[i - 1] >= w) { ans = Math.max(ans, r - l); } else if (i + 1 < n && suf[i + 1] >= w) { ans = Math.max(ans, r - l); } } return ans; } }
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
Python
class Solution: def maxFreeTime( self, eventTime: int, startTime: List[int], endTime: List[int] ) -> int: n = len(startTime) pre = [0] * n suf = [0] * n pre[0] = startTime[0] suf[n - 1] = eventTime - endTime[-1] for i in range(1, n): pre[i] = max(pre[i - 1], startTime[i] - endTime[i - 1]) for i in range(n - 2, -1, -1): suf[i] = max(suf[i + 1], startTime[i + 1] - endTime[i]) ans = 0 for i in range(n): l = 0 if i == 0 else endTime[i - 1] r = eventTime if i == n - 1 else startTime[i + 1] w = endTime[i] - startTime[i] ans = max(ans, r - l - w) if i and pre[i - 1] >= w: ans = max(ans, r - l) elif i + 1 < n and suf[i + 1] >= w: ans = max(ans, r - l) return ans
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
Rust
impl Solution { pub fn max_free_time(event_time: i32, start_time: Vec<i32>, end_time: Vec<i32>) -> i32 { let n = start_time.len(); let mut pre = vec![0; n]; let mut suf = vec![0; n]; pre[0] = start_time[0]; suf[n - 1] = event_time - end_time[n - 1]; for i in 1..n { pre[i] = pre[i - 1].max(start_time[i] - end_time[i - 1]); } for i in (0..n - 1).rev() { suf[i] = suf[i + 1].max(start_time[i + 1] - end_time[i]); } let mut ans = 0; for i in 0..n { let l = if i == 0 { 0 } else { end_time[i - 1] }; let r = if i == n - 1 { event_time } else { start_time[i + 1] }; let w = end_time[i] - start_time[i]; ans = ans.max(r - l - w); if i > 0 && pre[i - 1] >= w { ans = ans.max(r - l); } else if i + 1 < n && suf[i + 1] >= w { ans = ans.max(r - l); } } ans } }
3,440
Reschedule Meetings for Maximum Free Time II
Medium
<p>You are given an integer <code>eventTime</code> denoting the duration of an event. You are also given two integer arrays <code>startTime</code> and <code>endTime</code>, each of length <code>n</code>.</p> <p>These represent the start and end times of <code>n</code> <strong>non-overlapping</strong> meetings that occur during the event between time <code>t = 0</code> and time <code>t = eventTime</code>, where the <code>i<sup>th</sup></code> meeting occurs during the time <code>[startTime[i], endTime[i]].</code></p> <p>You can reschedule <strong>at most </strong>one meeting by moving its start time while maintaining the <strong>same duration</strong>, such that the meetings remain non-overlapping, to <strong>maximize</strong> the <strong>longest</strong> <em>continuous period of free time</em> during the event.</p> <p>Return the <strong>maximum</strong> amount of free time possible after rearranging the meetings.</p> <p><strong>Note</strong> that the meetings can <strong>not</strong> be rescheduled to a time outside the event and they should remain non-overlapping.</p> <p><strong>Note:</strong> <em>In this version</em>, it is <strong>valid</strong> for the relative ordering of the meetings to change after rescheduling one meeting.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [1,3], endTime = [2,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/example0_rescheduled.png" style="width: 375px; height: 123px;" /></p> <p>Reschedule the meeting at <code>[1, 2]</code> to <code>[2, 3]</code>, leaving no meetings during the time <code>[0, 2]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/rescheduled_example0.png" style="width: 375px; height: 125px;" /></p> <p>Reschedule the meeting at <code>[0, 1]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[0, 7]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]</span></p> <p><strong>Output:</strong> 6</p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3440.Reschedule%20Meetings%20for%20Maximum%20Free%20Time%20II/images/image3.png" style="width: 375px; height: 125px;" /></strong></p> <p>Reschedule the meeting at <code>[3, 4]</code> to <code>[8, 9]</code>, leaving no meetings during the time <code>[1, 7]</code>.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There is no time during the event not occupied by meetings.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= eventTime &lt;= 10<sup>9</sup></code></li> <li><code>n == startTime.length == endTime.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= startTime[i] &lt; endTime[i] &lt;= eventTime</code></li> <li><code>endTime[i] &lt;= startTime[i + 1]</code> where <code>i</code> lies in the range <code>[0, n - 2]</code>.</li> </ul>
Greedy; Array; Enumeration
TypeScript
function maxFreeTime(eventTime: number, startTime: number[], endTime: number[]): number { const n = startTime.length; const pre: number[] = Array(n).fill(0); const suf: number[] = Array(n).fill(0); pre[0] = startTime[0]; suf[n - 1] = eventTime - endTime[n - 1]; for (let i = 1; i < n; i++) { pre[i] = Math.max(pre[i - 1], startTime[i] - endTime[i - 1]); } for (let i = n - 2; i >= 0; i--) { suf[i] = Math.max(suf[i + 1], startTime[i + 1] - endTime[i]); } let ans = 0; for (let i = 0; i < n; i++) { const l = i === 0 ? 0 : endTime[i - 1]; const r = i === n - 1 ? eventTime : startTime[i + 1]; const w = endTime[i] - startTime[i]; ans = Math.max(ans, r - l - w); if (i > 0 && pre[i - 1] >= w) { ans = Math.max(ans, r - l); } else if (i + 1 < n && suf[i + 1] >= w) { ans = Math.max(ans, r - l); } } return ans; }
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
C++
class Solution { public: int maxDifference(string s) { int cnt[26]{}; for (char c : s) { ++cnt[c - 'a']; } int a = 0, b = 1 << 30; for (int v : cnt) { if (v % 2 == 1) { a = max(a, v); } else if (v > 0) { b = min(b, v); } } return a - b; } };
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
C#
public class Solution { public int MaxDifference(string s) { int[] cnt = new int[26]; foreach (char c in s) { ++cnt[c - 'a']; } int a = 0, b = 1 << 30; foreach (int v in cnt) { if (v % 2 == 1) { a = Math.Max(a, v); } else if (v > 0) { b = Math.Min(b, v); } } return a - b; } }
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
Go
func maxDifference(s string) int { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } a, b := 0, 1<<30 for _, v := range cnt { if v%2 == 1 { a = max(a, v) } else if v > 0 { b = min(b, v) } } return a - b }
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
Java
class Solution { public int maxDifference(String s) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { ++cnt[c - 'a']; } int a = 0, b = 1 << 30; for (int v : cnt) { if (v % 2 == 1) { a = Math.max(a, v); } else if (v > 0) { b = Math.min(b, v); } } return a - b; } }
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
Python
class Solution: def maxDifference(self, s: str) -> int: cnt = Counter(s) a, b = 0, inf for v in cnt.values(): if v % 2: a = max(a, v) else: b = min(b, v) return a - b
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
Rust
impl Solution { pub fn max_difference(s: String) -> i32 { let mut cnt = [0; 26]; for c in s.bytes() { cnt[(c - b'a') as usize] += 1; } let mut a = 0; let mut b = 1 << 30; for &v in cnt.iter() { if v % 2 == 1 { a = a.max(v); } else if v > 0 { b = b.min(v); } } a - b } }
3,442
Maximum Difference Between Even and Odd Frequency I
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>Your task is to find the <strong>maximum</strong> difference <code>diff = freq(a<sub>1</sub>) - freq(a<sub>2</sub>)</code> between the frequency of characters <code>a<sub>1</sub></code> and <code>a<sub>2</sub></code> in the string such that:</p> <ul> <li><code>a<sub>1</sub></code> has an <strong>odd frequency</strong> in the string.</li> <li><code>a<sub>2</sub></code> has an <strong>even frequency</strong> in the string.</li> </ul> <p>Return this <strong>maximum</strong> difference.</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;aaaaabbc&quot;</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">5</font></code><font face="monospace">,</font> and <code>&#39;b&#39;</code> has an <strong>even frequency</strong> of <code><font face="monospace">2</font></code>.</li> <li>The maximum difference is <code>5 - 2 = 3</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;abcabcab&quot;</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <ul> <li>The character <code>&#39;a&#39;</code> has an <strong>odd frequency</strong> of <code><font face="monospace">3</font></code><font face="monospace">,</font> and <code>&#39;c&#39;</code> has an <strong>even frequency</strong> of <font face="monospace">2</font>.</li> <li>The maximum difference is <code>3 - 2 = 1</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>s</code> contains at least one character with an odd frequency and one with an even frequency.</li> </ul>
Hash Table; String; Counting
TypeScript
function maxDifference(s: string): number { const cnt: Record<string, number> = {}; for (const c of s) { cnt[c] = (cnt[c] || 0) + 1; } let [a, b] = [0, Infinity]; for (const [_, v] of Object.entries(cnt)) { if (v % 2 === 1) { a = Math.max(a, v); } else { b = Math.min(b, v); } } return a - b; }
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
C++
class Solution { public: int maxDistance(string s, int k) { auto calc = [&](char a, char b) { int ans = 0, mx = 0, cnt = 0; for (char c : s) { if (c == a || c == b) { ++mx; } else if (cnt < k) { ++mx; ++cnt; } else { --mx; } ans = max(ans, mx); } return ans; }; int a = calc('S', 'E'); int b = calc('S', 'W'); int c = calc('N', 'E'); int d = calc('N', 'W'); return max({a, b, c, d}); } };
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
Go
func maxDistance(s string, k int) int { calc := func(a rune, b rune) int { var ans, mx, cnt int for _, c := range s { if c == a || c == b { mx++ } else if cnt < k { mx++ cnt++ } else { mx-- } ans = max(ans, mx) } return ans } a := calc('S', 'E') b := calc('S', 'W') c := calc('N', 'E') d := calc('N', 'W') return max(a, b, c, d) }
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
Java
class Solution { private char[] s; private int k; public int maxDistance(String s, int k) { this.s = s.toCharArray(); this.k = k; int a = calc('S', 'E'); int b = calc('S', 'W'); int c = calc('N', 'E'); int d = calc('N', 'W'); return Math.max(Math.max(a, b), Math.max(c, d)); } private int calc(char a, char b) { int ans = 0, mx = 0, cnt = 0; for (char c : s) { if (c == a || c == b) { ++mx; } else if (cnt < k) { ++mx; ++cnt; } else { --mx; } ans = Math.max(ans, mx); } return ans; } }
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
Python
class Solution: def maxDistance(self, s: str, k: int) -> int: def calc(a: str, b: str) -> int: ans = mx = cnt = 0 for c in s: if c == a or c == b: mx += 1 elif cnt < k: cnt += 1 mx += 1 else: mx -= 1 ans = max(ans, mx) return ans a = calc("S", "E") b = calc("S", "W") c = calc("N", "E") d = calc("N", "W") return max(a, b, c, d)
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
Rust
impl Solution { pub fn max_distance(s: String, k: i32) -> i32 { fn calc(s: &str, a: char, b: char, k: i32) -> i32 { let mut ans = 0; let mut mx = 0; let mut cnt = 0; for c in s.chars() { if c == a || c == b { mx += 1; } else if cnt < k { mx += 1; cnt += 1; } else { mx -= 1; } ans = ans.max(mx); } ans } let a = calc(&s, 'S', 'E', k); let b = calc(&s, 'S', 'W', k); let c = calc(&s, 'N', 'E', k); let d = calc(&s, 'N', 'W', k); a.max(b).max(c).max(d) } }
3,443
Maximum Manhattan Distance After K Changes
Medium
<p>You are given a string <code>s</code> consisting of the characters <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>, where <code>s[i]</code> indicates movements in an infinite grid:</p> <ul> <li><code>&#39;N&#39;</code> : Move north by 1 unit.</li> <li><code>&#39;S&#39;</code> : Move south by 1 unit.</li> <li><code>&#39;E&#39;</code> : Move east by 1 unit.</li> <li><code>&#39;W&#39;</code> : Move west by 1 unit.</li> </ul> <p>Initially, you are at the origin <code>(0, 0)</code>. You can change <strong>at most</strong> <code>k</code> characters to any of the four directions.</p> <p>Find the <strong>maximum</strong> <strong>Manhattan distance</strong> from the origin that can be achieved <strong>at any time</strong> while performing the movements <strong>in order</strong>.</p> The <strong>Manhattan Distance</strong> between two cells <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and <code>(x<sub>j</sub>, y<sub>j</sub>)</code> is <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>. <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;NWSE&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[2]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>. The string <code>s</code> becomes <code>&quot;NWNE&quot;</code>.</p> <table style="border: 1px solid black;"> <thead> <tr> <th style="border: 1px solid black;">Movement</th> <th style="border: 1px solid black;">Position (x, y)</th> <th style="border: 1px solid black;">Manhattan Distance</th> <th style="border: 1px solid black;">Maximum</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid black;">s[0] == &#39;N&#39;</td> <td style="border: 1px solid black;">(0, 1)</td> <td style="border: 1px solid black;">0 + 1 = 1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;">s[1] == &#39;W&#39;</td> <td style="border: 1px solid black;">(-1, 1)</td> <td style="border: 1px solid black;">1 + 1 = 2</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">s[2] == &#39;N&#39;</td> <td style="border: 1px solid black;">(-1, 2)</td> <td style="border: 1px solid black;">1 + 2 = 3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">s[3] == &#39;E&#39;</td> <td style="border: 1px solid black;">(0, 2)</td> <td style="border: 1px solid black;">0 + 2 = 2</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;NSWWEW&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s[1]</code> from <code>&#39;S&#39;</code> to <code>&#39;N&#39;</code>, and <code>s[4]</code> from <code>&#39;E&#39;</code> to <code>&#39;W&#39;</code>. The string <code>s</code> becomes <code>&quot;NNWWWW&quot;</code>.</p> <p>The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists of only <code>&#39;N&#39;</code>, <code>&#39;S&#39;</code>, <code>&#39;E&#39;</code>, and <code>&#39;W&#39;</code>.</li> </ul>
Hash Table; Math; String; Counting
TypeScript
function maxDistance(s: string, k: number): number { const calc = (a: string, b: string): number => { let [ans, mx, cnt] = [0, 0, 0]; for (const c of s) { if (c === a || c === b) { ++mx; } else if (cnt < k) { ++mx; ++cnt; } else { --mx; } ans = Math.max(ans, mx); } return ans; }; const a = calc('S', 'E'); const b = calc('S', 'W'); const c = calc('N', 'E'); const d = calc('N', 'W'); return Math.max(a, b, c, d); }
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
C++
class Solution { public: int maxDifference(string s, int k) { const int n = s.size(); const int inf = INT_MAX / 2; int ans = -inf; for (int a = 0; a < 5; ++a) { for (int b = 0; b < 5; ++b) { if (a == b) { continue; } int curA = 0, curB = 0; int preA = 0, preB = 0; int t[2][2] = {{inf, inf}, {inf, inf}}; int l = -1; for (int r = 0; r < n; ++r) { curA += (s[r] == '0' + a); curB += (s[r] == '0' + b); while (r - l >= k && curB - preB >= 2) { t[preA & 1][preB & 1] = min(t[preA & 1][preB & 1], preA - preB); ++l; preA += (s[l] == '0' + a); preB += (s[l] == '0' + b); } ans = max(ans, curA - curB - t[(curA & 1) ^ 1][curB & 1]); } } } return ans; } };
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
Go
func maxDifference(s string, k int) int { n := len(s) inf := math.MaxInt32 / 2 ans := -inf for a := 0; a < 5; a++ { for b := 0; b < 5; b++ { if a == b { continue } curA, curB := 0, 0 preA, preB := 0, 0 t := [2][2]int{{inf, inf}, {inf, inf}} l := -1 for r := 0; r < n; r++ { if s[r] == byte('0'+a) { curA++ } if s[r] == byte('0'+b) { curB++ } for r-l >= k && curB-preB >= 2 { t[preA&1][preB&1] = min(t[preA&1][preB&1], preA-preB) l++ if s[l] == byte('0'+a) { preA++ } if s[l] == byte('0'+b) { preB++ } } ans = max(ans, curA-curB-t[curA&1^1][curB&1]) } } } return ans }
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
Java
class Solution { public int maxDifference(String S, int k) { char[] s = S.toCharArray(); int n = s.length; final int inf = Integer.MAX_VALUE / 2; int ans = -inf; for (int a = 0; a < 5; ++a) { for (int b = 0; b < 5; ++b) { if (a == b) { continue; } int curA = 0, curB = 0; int preA = 0, preB = 0; int[][] t = {{inf, inf}, {inf, inf}}; for (int l = -1, r = 0; r < n; ++r) { curA += s[r] == '0' + a ? 1 : 0; curB += s[r] == '0' + b ? 1 : 0; while (r - l >= k && curB - preB >= 2) { t[preA & 1][preB & 1] = Math.min(t[preA & 1][preB & 1], preA - preB); ++l; preA += s[l] == '0' + a ? 1 : 0; preB += s[l] == '0' + b ? 1 : 0; } ans = Math.max(ans, curA - curB - t[curA & 1 ^ 1][curB & 1]); } } } return ans; } }
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
Python
class Solution: def maxDifference(self, S: str, k: int) -> int: s = list(map(int, S)) ans = -inf for a in range(5): for b in range(5): if a == b: continue curA = curB = 0 preA = preB = 0 t = [[inf, inf], [inf, inf]] l = -1 for r, x in enumerate(s): curA += x == a curB += x == b while r - l >= k and curB - preB >= 2: t[preA & 1][preB & 1] = min(t[preA & 1][preB & 1], preA - preB) l += 1 preA += s[l] == a preB += s[l] == b ans = max(ans, curA - curB - t[curA & 1 ^ 1][curB & 1]) return ans
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
Rust
use std::cmp::{max, min}; use std::i32::{MAX, MIN}; impl Solution { pub fn max_difference(S: String, k: i32) -> i32 { let s: Vec<usize> = S .chars() .map(|c| c.to_digit(10).unwrap() as usize) .collect(); let k = k as usize; let mut ans = MIN; for a in 0..5 { for b in 0..5 { if a == b { continue; } let mut curA = 0; let mut curB = 0; let mut preA = 0; let mut preB = 0; let mut t = [[MAX; 2]; 2]; let mut l: isize = -1; for (r, &x) in s.iter().enumerate() { curA += (x == a) as i32; curB += (x == b) as i32; while (r as isize - l) as usize >= k && curB - preB >= 2 { let i = (preA & 1) as usize; let j = (preB & 1) as usize; t[i][j] = min(t[i][j], preA - preB); l += 1; if l >= 0 { preA += (s[l as usize] == a) as i32; preB += (s[l as usize] == b) as i32; } } let i = (curA & 1 ^ 1) as usize; let j = (curB & 1) as usize; if t[i][j] != MAX { ans = max(ans, curA - curB - t[i][j]); } } } } ans } }
3,445
Maximum Difference Between Even and Odd Frequency II
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p> <ul> <li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li> <li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li> <li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li> </ul> <p>Return the <strong>maximum</strong> difference.</p> <p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</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;12233&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;12233&quot;</code>, the frequency of <code>&#39;1&#39;</code> is 1 and the frequency of <code>&#39;3&#39;</code> is 2. The difference is <code>1 - 2 = -1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1122211&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>For the substring <code>&quot;11222&quot;</code>, the frequency of <code>&#39;2&#39;</code> is 3 and the frequency of <code>&#39;1&#39;</code> is 2. The difference is <code>3 - 2 = 1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;110&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of digits <code>&#39;0&#39;</code> to <code>&#39;4&#39;</code>.</li> <li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li> <li><code>1 &lt;= k &lt;= s.length</code></li> </ul>
String; Enumeration; Prefix Sum; Sliding Window
TypeScript
function maxDifference(S: string, k: number): number { const s = S.split('').map(Number); let ans = -Infinity; for (let a = 0; a < 5; a++) { for (let b = 0; b < 5; b++) { if (a === b) { continue; } let [curA, curB, preA, preB] = [0, 0, 0, 0]; const t: number[][] = [ [Infinity, Infinity], [Infinity, Infinity], ]; let l = -1; for (let r = 0; r < s.length; r++) { const x = s[r]; curA += x === a ? 1 : 0; curB += x === b ? 1 : 0; while (r - l >= k && curB - preB >= 2) { t[preA & 1][preB & 1] = Math.min(t[preA & 1][preB & 1], preA - preB); l++; preA += s[l] === a ? 1 : 0; preB += s[l] === b ? 1 : 0; } ans = Math.max(ans, curA - curB - t[(curA & 1) ^ 1][curB & 1]); } } } return ans; }
3,446
Sort Matrix by Diagonals
Medium
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p> <ul> <li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li> <li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p> <p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p> <ul> <li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li> <li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li> </ul> <p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p> <ul> <li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li> <li><code>[3]</code> remains unchanged.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p> <p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[1]]</span></p> <p><strong>Explanation:</strong></p> <p>Diagonals with exactly one element are already in order, so no changes are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == n</code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Sorting
C++
class Solution { public: vector<vector<int>> sortMatrix(vector<vector<int>>& grid) { int n = grid.size(); for (int k = n - 2; k >= 0; --k) { int i = k, j = 0; vector<int> t; while (i < n && j < n) { t.push_back(grid[i++][j++]); } ranges::sort(t); for (int x : t) { grid[--i][--j] = x; } } for (int k = n - 2; k > 0; --k) { int i = k, j = n - 1; vector<int> t; while (i >= 0 && j >= 0) { t.push_back(grid[i--][j--]); } ranges::sort(t); for (int x : t) { grid[++i][++j] = x; } } return grid; } };
3,446
Sort Matrix by Diagonals
Medium
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p> <ul> <li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li> <li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p> <p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p> <ul> <li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li> <li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li> </ul> <p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p> <ul> <li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li> <li><code>[3]</code> remains unchanged.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p> <p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[1]]</span></p> <p><strong>Explanation:</strong></p> <p>Diagonals with exactly one element are already in order, so no changes are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == n</code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Sorting
Go
func sortMatrix(grid [][]int) [][]int { n := len(grid) for k := n - 2; k >= 0; k-- { i, j := k, 0 t := []int{} for ; i < n && j < n; i, j = i+1, j+1 { t = append(t, grid[i][j]) } sort.Ints(t) for _, x := range t { i, j = i-1, j-1 grid[i][j] = x } } for k := n - 2; k > 0; k-- { i, j := k, n-1 t := []int{} for ; i >= 0 && j >= 0; i, j = i-1, j-1 { t = append(t, grid[i][j]) } sort.Ints(t) for _, x := range t { i, j = i+1, j+1 grid[i][j] = x } } return grid }
3,446
Sort Matrix by Diagonals
Medium
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p> <ul> <li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li> <li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p> <p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p> <ul> <li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li> <li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li> </ul> <p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p> <ul> <li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li> <li><code>[3]</code> remains unchanged.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p> <p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[1]]</span></p> <p><strong>Explanation:</strong></p> <p>Diagonals with exactly one element are already in order, so no changes are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == n</code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Sorting
Java
class Solution { public int[][] sortMatrix(int[][] grid) { int n = grid.length; for (int k = n - 2; k >= 0; --k) { int i = k, j = 0; List<Integer> t = new ArrayList<>(); while (i < n && j < n) { t.add(grid[i++][j++]); } Collections.sort(t); for (int x : t) { grid[--i][--j] = x; } } for (int k = n - 2; k > 0; --k) { int i = k, j = n - 1; List<Integer> t = new ArrayList<>(); while (i >= 0 && j >= 0) { t.add(grid[i--][j--]); } Collections.sort(t); for (int x : t) { grid[++i][++j] = x; } } return grid; } }
3,446
Sort Matrix by Diagonals
Medium
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p> <ul> <li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li> <li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p> <p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p> <ul> <li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li> <li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li> </ul> <p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p> <ul> <li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li> <li><code>[3]</code> remains unchanged.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p> <p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[1]]</span></p> <p><strong>Explanation:</strong></p> <p>Diagonals with exactly one element are already in order, so no changes are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == n</code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Sorting
Python
class Solution: def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) for k in range(n - 2, -1, -1): i, j = k, 0 t = [] while i < n and j < n: t.append(grid[i][j]) i += 1 j += 1 t.sort() i, j = k, 0 while i < n and j < n: grid[i][j] = t.pop() i += 1 j += 1 for k in range(n - 2, 0, -1): i, j = k, n - 1 t = [] while i >= 0 and j >= 0: t.append(grid[i][j]) i -= 1 j -= 1 t.sort() i, j = k, n - 1 while i >= 0 and j >= 0: grid[i][j] = t.pop() i -= 1 j -= 1 return grid
3,446
Sort Matrix by Diagonals
Medium
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p> <ul> <li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li> <li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p> <p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p> <ul> <li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li> <li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li> </ul> <p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p> <ul> <li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li> <li><code>[3]</code> remains unchanged.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p> <p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[[1]]</span></p> <p><strong>Explanation:</strong></p> <p>Diagonals with exactly one element are already in order, so no changes are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == n</code></li> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Matrix; Sorting
TypeScript
function sortMatrix(grid: number[][]): number[][] { const n = grid.length; for (let k = n - 2; k >= 0; --k) { let [i, j] = [k, 0]; const t: number[] = []; while (i < n && j < n) { t.push(grid[i++][j++]); } t.sort((a, b) => a - b); for (const x of t) { grid[--i][--j] = x; } } for (let k = n - 2; k > 0; --k) { let [i, j] = [k, n - 1]; const t: number[] = []; while (i >= 0 && j >= 0) { t.push(grid[i--][j--]); } t.sort((a, b) => a - b); for (const x of t) { grid[++i][++j] = x; } } return grid; }
3,447
Assign Elements to Groups with Constraints
Medium
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p> <p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p> <ul> <li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li> <li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li> <li>If no element satisfies the condition for a group, assign -1 to that group.</li> </ul> <p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p> <p><strong>Note</strong>: An element may be assigned to more than one group.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li> <li><code>elements[1] = 2</code> is assigned to group 3.</li> <li>Group 2 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[1] = 3</code> is assigned to group 1.</li> <li><code>elements[0] = 5</code> is assigned to group 2.</li> <li>Groups 0 and 3 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p> <p><strong>Explanation:</strong></p> <p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= groups.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= groups[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
C++
class Solution { public: vector<int> assignElements(vector<int>& groups, vector<int>& elements) { int mx = ranges::max(groups); vector<int> d(mx + 1, -1); for (int j = 0; j < elements.size(); ++j) { int x = elements[j]; if (x > mx || d[x] != -1) { continue; } for (int y = x; y <= mx; y += x) { if (d[y] == -1) { d[y] = j; } } } vector<int> ans(groups.size()); for (int i = 0; i < groups.size(); ++i) { ans[i] = d[groups[i]]; } return ans; } };
3,447
Assign Elements to Groups with Constraints
Medium
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p> <p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p> <ul> <li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li> <li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li> <li>If no element satisfies the condition for a group, assign -1 to that group.</li> </ul> <p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p> <p><strong>Note</strong>: An element may be assigned to more than one group.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li> <li><code>elements[1] = 2</code> is assigned to group 3.</li> <li>Group 2 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[1] = 3</code> is assigned to group 1.</li> <li><code>elements[0] = 5</code> is assigned to group 2.</li> <li>Groups 0 and 3 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p> <p><strong>Explanation:</strong></p> <p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= groups.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= groups[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Go
func assignElements(groups []int, elements []int) (ans []int) { mx := slices.Max(groups) d := make([]int, mx+1) for i := range d { d[i] = -1 } for j, x := range elements { if x > mx || d[x] != -1 { continue } for y := x; y <= mx; y += x { if d[y] == -1 { d[y] = j } } } for _, x := range groups { ans = append(ans, d[x]) } return }
3,447
Assign Elements to Groups with Constraints
Medium
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p> <p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p> <ul> <li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li> <li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li> <li>If no element satisfies the condition for a group, assign -1 to that group.</li> </ul> <p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p> <p><strong>Note</strong>: An element may be assigned to more than one group.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li> <li><code>elements[1] = 2</code> is assigned to group 3.</li> <li>Group 2 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[1] = 3</code> is assigned to group 1.</li> <li><code>elements[0] = 5</code> is assigned to group 2.</li> <li>Groups 0 and 3 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p> <p><strong>Explanation:</strong></p> <p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= groups.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= groups[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Java
class Solution { public int[] assignElements(int[] groups, int[] elements) { int mx = Arrays.stream(groups).max().getAsInt(); int[] d = new int[mx + 1]; Arrays.fill(d, -1); for (int j = 0; j < elements.length; ++j) { int x = elements[j]; if (x > mx || d[x] != -1) { continue; } for (int y = x; y <= mx; y += x) { if (d[y] == -1) { d[y] = j; } } } int n = groups.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = d[groups[i]]; } return ans; } }
3,447
Assign Elements to Groups with Constraints
Medium
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p> <p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p> <ul> <li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li> <li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li> <li>If no element satisfies the condition for a group, assign -1 to that group.</li> </ul> <p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p> <p><strong>Note</strong>: An element may be assigned to more than one group.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li> <li><code>elements[1] = 2</code> is assigned to group 3.</li> <li>Group 2 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[1] = 3</code> is assigned to group 1.</li> <li><code>elements[0] = 5</code> is assigned to group 2.</li> <li>Groups 0 and 3 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p> <p><strong>Explanation:</strong></p> <p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= groups.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= groups[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
Python
class Solution: def assignElements(self, groups: List[int], elements: List[int]) -> List[int]: mx = max(groups) d = [-1] * (mx + 1) for j, x in enumerate(elements): if x > mx or d[x] != -1: continue for y in range(x, mx + 1, x): if d[y] == -1: d[y] = j return [d[x] for x in groups]
3,447
Assign Elements to Groups with Constraints
Medium
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p> <p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p> <ul> <li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li> <li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li> <li>If no element satisfies the condition for a group, assign -1 to that group.</li> </ul> <p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p> <p><strong>Note</strong>: An element may be assigned to more than one group.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li> <li><code>elements[1] = 2</code> is assigned to group 3.</li> <li>Group 2 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>elements[1] = 3</code> is assigned to group 1.</li> <li><code>elements[0] = 5</code> is assigned to group 2.</li> <li>Groups 0 and 3 cannot be assigned any element.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p> <p><strong>Explanation:</strong></p> <p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= groups.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= groups[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= elements[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table
TypeScript
function assignElements(groups: number[], elements: number[]): number[] { const mx = Math.max(...groups); const d: number[] = Array(mx + 1).fill(-1); for (let j = 0; j < elements.length; ++j) { const x = elements[j]; if (x > mx || d[x] !== -1) { continue; } for (let y = x; y <= mx; y += x) { if (d[y] === -1) { d[y] = j; } } } return groups.map(x => d[x]); }
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int maxStudentsOnBench(vector<vector<int>>& students) { unordered_map<int, unordered_set<int>> d; for (const auto& e : students) { int studentId = e[0], benchId = e[1]; d[benchId].insert(studentId); } int ans = 0; for (const auto& s : d) { ans = max(ans, (int) s.second.size()); } return ans; } };
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
Go
func maxStudentsOnBench(students [][]int) (ans int) { d := make(map[int]map[int]struct{}) for _, e := range students { studentId, benchId := e[0], e[1] if _, exists := d[benchId]; !exists { d[benchId] = make(map[int]struct{}) } d[benchId][studentId] = struct{}{} } for _, s := range d { ans = max(ans, len(s)) } return }
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
Java
class Solution { public int maxStudentsOnBench(int[][] students) { Map<Integer, Set<Integer>> d = new HashMap<>(); for (var e : students) { int studentId = e[0], benchId = e[1]; d.computeIfAbsent(benchId, k -> new HashSet<>()).add(studentId); } int ans = 0; for (var s : d.values()) { ans = Math.max(ans, s.size()); } return ans; } }
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
Python
class Solution: def maxStudentsOnBench(self, students: List[List[int]]) -> int: if not students: return 0 d = defaultdict(set) for student_id, bench_id in students: d[bench_id].add(student_id) return max(map(len, d.values()))
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
Rust
use std::collections::{HashMap, HashSet}; impl Solution { pub fn max_students_on_bench(students: Vec<Vec<i32>>) -> i32 { let mut d: HashMap<i32, HashSet<i32>> = HashMap::new(); for e in students { let student_id = e[0]; let bench_id = e[1]; d.entry(bench_id) .or_insert_with(HashSet::new) .insert(student_id); } let mut ans = 0; for s in d.values() { ans = ans.max(s.len() as i32); } ans } }
3,450
Maximum Students on a Single Bench
Easy
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p> <p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p> <p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 2 has two unique students: <code>[1, 2]</code>.</li> <li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li> <li>Bench 2 has two unique students: <code>[4, 5]</code>.</li> <li>The maximum number of unique students on a single bench is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The maximum number of unique students on a single bench is 1.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">students = []</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no students are present, the output is 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= students.length &lt;= 100</code></li> <li><code>students[i] = [student_id, bench_id]</code></li> <li><code>1 &lt;= student_id &lt;= 100</code></li> <li><code>1 &lt;= bench_id &lt;= 100</code></li> </ul>
Array; Hash Table
TypeScript
function maxStudentsOnBench(students: number[][]): number { const d: Map<number, Set<number>> = new Map(); for (const [studentId, benchId] of students) { if (!d.has(benchId)) { d.set(benchId, new Set()); } d.get(benchId)?.add(studentId); } let ans = 0; for (const s of d.values()) { ans = Math.max(ans, s.size); } return ans; }
3,451
Find Invalid IP Addresses
Hard
<p>Table: <code> logs</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | log_id | int | | ip | varchar | | status_code | int | +-------------+---------+ log_id is the unique key for this table. Each row contains server access log information including IP address and HTTP status code. </pre> <p>Write a solution to find <strong>invalid IP addresses</strong>. An IPv4 address is invalid if it meets any of these conditions:</p> <ul> <li>Contains numbers <strong>greater than</strong> <code>255</code> in any octet</li> <li>Has <strong>leading zeros</strong> in any octet (like <code>01.02.03.04</code>)</li> <li>Has <strong>less or more</strong> than <code>4</code> octets</li> </ul> <p>Return <em>the result table </em><em>ordered by</em> <code>invalid_count</code>,&nbsp;<code>ip</code>&nbsp;<em>in <strong>descending</strong> order respectively</em>.&nbsp;</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>logs table:</p> <pre class="example-io"> +--------+---------------+-------------+ | log_id | ip | status_code | +--------+---------------+-------------+ | 1 | 192.168.1.1 | 200 | | 2 | 256.1.2.3 | 404 | | 3 | 192.168.001.1 | 200 | | 4 | 192.168.1.1 | 200 | | 5 | 192.168.1 | 500 | | 6 | 256.1.2.3 | 404 | | 7 | 192.168.001.1 | 200 | +--------+---------------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------------+--------------+ | ip | invalid_count| +---------------+--------------+ | 256.1.2.3 | 2 | | 192.168.001.1 | 2 | | 192.168.1 | 1 | +---------------+--------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>256.1.2.3&nbsp;is invalid because 256 &gt; 255</li> <li>192.168.001.1&nbsp;is invalid because of leading zeros</li> <li>192.168.1&nbsp;is invalid because it has only 3 octets</li> </ul> <p>The output table is ordered by invalid_count, ip in descending order respectively.</p> </div>
Database
Python
import pandas as pd def find_invalid_ips(logs: pd.DataFrame) -> pd.DataFrame: def is_valid_ip(ip: str) -> bool: octets = ip.split(".") if len(octets) != 4: return False for octet in octets: if not octet.isdigit(): return False value = int(octet) if not 0 <= value <= 255 or octet != str(value): return False return True logs["is_valid"] = logs["ip"].apply(is_valid_ip) invalid_ips = logs[~logs["is_valid"]] invalid_count = invalid_ips["ip"].value_counts().reset_index() invalid_count.columns = ["ip", "invalid_count"] result = invalid_count.sort_values( by=["invalid_count", "ip"], ascending=[False, False] ) return result
3,451
Find Invalid IP Addresses
Hard
<p>Table: <code> logs</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | log_id | int | | ip | varchar | | status_code | int | +-------------+---------+ log_id is the unique key for this table. Each row contains server access log information including IP address and HTTP status code. </pre> <p>Write a solution to find <strong>invalid IP addresses</strong>. An IPv4 address is invalid if it meets any of these conditions:</p> <ul> <li>Contains numbers <strong>greater than</strong> <code>255</code> in any octet</li> <li>Has <strong>leading zeros</strong> in any octet (like <code>01.02.03.04</code>)</li> <li>Has <strong>less or more</strong> than <code>4</code> octets</li> </ul> <p>Return <em>the result table </em><em>ordered by</em> <code>invalid_count</code>,&nbsp;<code>ip</code>&nbsp;<em>in <strong>descending</strong> order respectively</em>.&nbsp;</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>logs table:</p> <pre class="example-io"> +--------+---------------+-------------+ | log_id | ip | status_code | +--------+---------------+-------------+ | 1 | 192.168.1.1 | 200 | | 2 | 256.1.2.3 | 404 | | 3 | 192.168.001.1 | 200 | | 4 | 192.168.1.1 | 200 | | 5 | 192.168.1 | 500 | | 6 | 256.1.2.3 | 404 | | 7 | 192.168.001.1 | 200 | +--------+---------------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------------+--------------+ | ip | invalid_count| +---------------+--------------+ | 256.1.2.3 | 2 | | 192.168.001.1 | 2 | | 192.168.1 | 1 | +---------------+--------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>256.1.2.3&nbsp;is invalid because 256 &gt; 255</li> <li>192.168.001.1&nbsp;is invalid because of leading zeros</li> <li>192.168.1&nbsp;is invalid because it has only 3 octets</li> </ul> <p>The output table is ordered by invalid_count, ip in descending order respectively.</p> </div>
Database
SQL
SELECT ip, COUNT(*) AS invalid_count FROM logs WHERE LENGTH(ip) - LENGTH(REPLACE(ip, '.', '')) != 3 OR SUBSTRING_INDEX(ip, '.', 1) REGEXP '^0[0-9]' OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 2), '.', -1) REGEXP '^0[0-9]' OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 3), '.', -1) REGEXP '^0[0-9]' OR SUBSTRING_INDEX(ip, '.', -1) REGEXP '^0[0-9]' OR SUBSTRING_INDEX(ip, '.', 1) > 255 OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 2), '.', -1) > 255 OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 3), '.', -1) > 255 OR SUBSTRING_INDEX(ip, '.', -1) > 255 GROUP BY 1 ORDER BY 2 DESC, 1 DESC;
3,452
Sum of Good Numbers
Easy
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p> <p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= floor(nums.length / 2)</code></li> </ul>
Array
C++
class Solution { public: int sumOfGoodNumbers(vector<int>& nums, int k) { int ans = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { if (i >= k && nums[i] <= nums[i - k]) { continue; } if (i + k < n && nums[i] <= nums[i + k]) { continue; } ans += nums[i]; } return ans; } };
3,452
Sum of Good Numbers
Easy
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p> <p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= floor(nums.length / 2)</code></li> </ul>
Array
Go
func sumOfGoodNumbers(nums []int, k int) (ans int) { for i, x := range nums { if i >= k && x <= nums[i-k] { continue } if i+k < len(nums) && x <= nums[i+k] { continue } ans += x } return }
3,452
Sum of Good Numbers
Easy
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p> <p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= floor(nums.length / 2)</code></li> </ul>
Array
Java
class Solution { public int sumOfGoodNumbers(int[] nums, int k) { int ans = 0; int n = nums.length; for (int i = 0; i < n; ++i) { if (i >= k && nums[i] <= nums[i - k]) { continue; } if (i + k < n && nums[i] <= nums[i + k]) { continue; } ans += nums[i]; } return ans; } }