id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,010
Divide an Array Into Subarrays With Minimum Cost I
Easy
<p>You are given an array of integers <code>nums</code> of length <code>n</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>3</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Return <em>the <strong>minimum</strong> possible <strong>sum</strong> of the cost of these subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,12] <strong>Output:</strong> 6 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. The other possible ways to form 3 subarrays are: - [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. - [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,3,1,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration; Sorting
Go
func minimumCost(nums []int) int { a, b, c := nums[0], 100, 100 for _, x := range nums[1:] { if x < b { b, c = x, b } else if x < c { c = x } } return a + b + c }
3,010
Divide an Array Into Subarrays With Minimum Cost I
Easy
<p>You are given an array of integers <code>nums</code> of length <code>n</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>3</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Return <em>the <strong>minimum</strong> possible <strong>sum</strong> of the cost of these subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,12] <strong>Output:</strong> 6 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. The other possible ways to form 3 subarrays are: - [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. - [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,3,1,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration; Sorting
Java
class Solution { public int minimumCost(int[] nums) { int a = nums[0], b = 100, c = 100; for (int i = 1; i < nums.length; ++i) { if (nums[i] < b) { c = b; b = nums[i]; } else if (nums[i] < c) { c = nums[i]; } } return a + b + c; } }
3,010
Divide an Array Into Subarrays With Minimum Cost I
Easy
<p>You are given an array of integers <code>nums</code> of length <code>n</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>3</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Return <em>the <strong>minimum</strong> possible <strong>sum</strong> of the cost of these subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,12] <strong>Output:</strong> 6 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. The other possible ways to form 3 subarrays are: - [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. - [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,3,1,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration; Sorting
Python
class Solution: def minimumCost(self, nums: List[int]) -> int: a, b, c = nums[0], inf, inf for x in nums[1:]: if x < b: c, b = b, x elif x < c: c = x return a + b + c
3,010
Divide an Array Into Subarrays With Minimum Cost I
Easy
<p>You are given an array of integers <code>nums</code> of length <code>n</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>3</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Return <em>the <strong>minimum</strong> possible <strong>sum</strong> of the cost of these subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,12] <strong>Output:</strong> 6 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. The other possible ways to form 3 subarrays are: - [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. - [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,3,1,1] <strong>Output:</strong> 12 <strong>Explanation:</strong> The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. It can be shown that 12 is the minimum cost achievable. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Enumeration; Sorting
TypeScript
function minimumCost(nums: number[]): number { let [a, b, c] = [nums[0], 100, 100]; for (const x of nums.slice(1)) { if (x < b) { [b, c] = [x, b]; } else if (x < c) { c = x; } } return a + b + c; }
3,011
Find if Array Can Be Sorted
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>In one <strong>operation</strong>, you can swap any two <strong>adjacent</strong> elements if they have the <strong>same</strong> number of <span data-keyword="set-bit">set bits</span>. You are allowed to do this operation <strong>any</strong> number of times (<strong>including zero</strong>).</p> <p>Return <code>true</code> <em>if you can sort the array in ascending order, else return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [8,4,2,30,15] <strong>Output:</strong> true <strong>Explanation:</strong> Let&#39;s look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation &quot;10&quot;, &quot;100&quot;, and &quot;1000&quot; respectively. The numbers 15 and 30 have four set bits each with binary representation &quot;1111&quot; and &quot;11110&quot;. We can sort the array using 4 operations: - Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. - Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. - Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. - Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array is already sorted, hence we return true. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,16,8,4,2] <strong>Output:</strong> false <strong>Explanation:</strong> It can be shown that it is not possible to sort the input array using any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 2<sup>8</sup></code></li> </ul>
Bit Manipulation; Array; Sorting
C++
class Solution { public: bool canSortArray(vector<int>& nums) { int preMx = 0; int i = 0, n = nums.size(); while (i < n) { int cnt = __builtin_popcount(nums[i]); int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && __builtin_popcount(nums[j]) == cnt) { mi = min(mi, nums[j]); mx = max(mx, nums[j]); j++; } if (preMx > mi) { return false; } preMx = mx; i = j; } return true; } };
3,011
Find if Array Can Be Sorted
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>In one <strong>operation</strong>, you can swap any two <strong>adjacent</strong> elements if they have the <strong>same</strong> number of <span data-keyword="set-bit">set bits</span>. You are allowed to do this operation <strong>any</strong> number of times (<strong>including zero</strong>).</p> <p>Return <code>true</code> <em>if you can sort the array in ascending order, else return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [8,4,2,30,15] <strong>Output:</strong> true <strong>Explanation:</strong> Let&#39;s look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation &quot;10&quot;, &quot;100&quot;, and &quot;1000&quot; respectively. The numbers 15 and 30 have four set bits each with binary representation &quot;1111&quot; and &quot;11110&quot;. We can sort the array using 4 operations: - Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. - Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. - Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. - Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array is already sorted, hence we return true. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,16,8,4,2] <strong>Output:</strong> false <strong>Explanation:</strong> It can be shown that it is not possible to sort the input array using any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 2<sup>8</sup></code></li> </ul>
Bit Manipulation; Array; Sorting
Go
func canSortArray(nums []int) bool { preMx := 0 i, n := 0, len(nums) for i < n { cnt := bits.OnesCount(uint(nums[i])) j := i + 1 mi, mx := nums[i], nums[i] for j < n && bits.OnesCount(uint(nums[j])) == cnt { mi = min(mi, nums[j]) mx = max(mx, nums[j]) j++ } if preMx > mi { return false } preMx = mx i = j } return true }
3,011
Find if Array Can Be Sorted
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>In one <strong>operation</strong>, you can swap any two <strong>adjacent</strong> elements if they have the <strong>same</strong> number of <span data-keyword="set-bit">set bits</span>. You are allowed to do this operation <strong>any</strong> number of times (<strong>including zero</strong>).</p> <p>Return <code>true</code> <em>if you can sort the array in ascending order, else return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [8,4,2,30,15] <strong>Output:</strong> true <strong>Explanation:</strong> Let&#39;s look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation &quot;10&quot;, &quot;100&quot;, and &quot;1000&quot; respectively. The numbers 15 and 30 have four set bits each with binary representation &quot;1111&quot; and &quot;11110&quot;. We can sort the array using 4 operations: - Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. - Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. - Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. - Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array is already sorted, hence we return true. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,16,8,4,2] <strong>Output:</strong> false <strong>Explanation:</strong> It can be shown that it is not possible to sort the input array using any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 2<sup>8</sup></code></li> </ul>
Bit Manipulation; Array; Sorting
Java
class Solution { public boolean canSortArray(int[] nums) { int preMx = 0; int i = 0, n = nums.length; while (i < n) { int cnt = Integer.bitCount(nums[i]); int j = i + 1; int mi = nums[i], mx = nums[i]; while (j < n && Integer.bitCount(nums[j]) == cnt) { mi = Math.min(mi, nums[j]); mx = Math.max(mx, nums[j]); j++; } if (preMx > mi) { return false; } preMx = mx; i = j; } return true; } }
3,011
Find if Array Can Be Sorted
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>In one <strong>operation</strong>, you can swap any two <strong>adjacent</strong> elements if they have the <strong>same</strong> number of <span data-keyword="set-bit">set bits</span>. You are allowed to do this operation <strong>any</strong> number of times (<strong>including zero</strong>).</p> <p>Return <code>true</code> <em>if you can sort the array in ascending order, else return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [8,4,2,30,15] <strong>Output:</strong> true <strong>Explanation:</strong> Let&#39;s look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation &quot;10&quot;, &quot;100&quot;, and &quot;1000&quot; respectively. The numbers 15 and 30 have four set bits each with binary representation &quot;1111&quot; and &quot;11110&quot;. We can sort the array using 4 operations: - Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. - Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. - Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. - Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array is already sorted, hence we return true. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,16,8,4,2] <strong>Output:</strong> false <strong>Explanation:</strong> It can be shown that it is not possible to sort the input array using any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 2<sup>8</sup></code></li> </ul>
Bit Manipulation; Array; Sorting
Python
class Solution: def canSortArray(self, nums: List[int]) -> bool: pre_mx = 0 i, n = 0, len(nums) while i < n: cnt = nums[i].bit_count() j = i + 1 mi = mx = nums[i] while j < n and nums[j].bit_count() == cnt: mi = min(mi, nums[j]) mx = max(mx, nums[j]) j += 1 if pre_mx > mi: return False pre_mx = mx i = j return True
3,011
Find if Array Can Be Sorted
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>In one <strong>operation</strong>, you can swap any two <strong>adjacent</strong> elements if they have the <strong>same</strong> number of <span data-keyword="set-bit">set bits</span>. You are allowed to do this operation <strong>any</strong> number of times (<strong>including zero</strong>).</p> <p>Return <code>true</code> <em>if you can sort the array in ascending order, else return </em><code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [8,4,2,30,15] <strong>Output:</strong> true <strong>Explanation:</strong> Let&#39;s look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation &quot;10&quot;, &quot;100&quot;, and &quot;1000&quot; respectively. The numbers 15 and 30 have four set bits each with binary representation &quot;1111&quot; and &quot;11110&quot;. We can sort the array using 4 operations: - Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15]. - Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15]. - Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15]. - Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30]. The array has become sorted, hence we return true. Note that there may be other sequences of operations which also sort the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> The array is already sorted, hence we return true. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,16,8,4,2] <strong>Output:</strong> false <strong>Explanation:</strong> It can be shown that it is not possible to sort the input array using any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 2<sup>8</sup></code></li> </ul>
Bit Manipulation; Array; Sorting
TypeScript
function canSortArray(nums: number[]): boolean { let preMx = 0; const n = nums.length; for (let i = 0; i < n; ) { const cnt = bitCount(nums[i]); let j = i + 1; let [mi, mx] = [nums[i], nums[i]]; while (j < n && bitCount(nums[j]) === cnt) { mi = Math.min(mi, nums[j]); mx = Math.max(mx, nums[j]); j++; } if (preMx > mi) { return false; } preMx = mx; i = j; } return true; } function bitCount(i: number): number { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
3,012
Minimize Length of Array Using Operations
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <strong>positive</strong> integers.</p> <p>Your task is to <strong>minimize</strong> the length of <code>nums</code> by performing the following operations <strong>any</strong> number of times (including zero):</p> <ul> <li>Select <strong>two</strong> <strong>distinct</strong> indices <code>i</code> and <code>j</code> from <code>nums</code>, such that <code>nums[i] &gt; 0</code> and <code>nums[j] &gt; 0</code>.</li> <li>Insert the result of <code>nums[i] % nums[j]</code> at the end of <code>nums</code>.</li> <li>Delete the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>minimum</strong> <strong>length</strong> of </em><code>nums</code><em> after performing the operation any number of times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,10,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
C++
class Solution { public: int minimumArrayLength(vector<int>& nums) { int mi = *min_element(nums.begin(), nums.end()); int cnt = 0; for (int x : nums) { if (x % mi) { return 1; } cnt += x == mi; } return (cnt + 1) / 2; } };
3,012
Minimize Length of Array Using Operations
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <strong>positive</strong> integers.</p> <p>Your task is to <strong>minimize</strong> the length of <code>nums</code> by performing the following operations <strong>any</strong> number of times (including zero):</p> <ul> <li>Select <strong>two</strong> <strong>distinct</strong> indices <code>i</code> and <code>j</code> from <code>nums</code>, such that <code>nums[i] &gt; 0</code> and <code>nums[j] &gt; 0</code>.</li> <li>Insert the result of <code>nums[i] % nums[j]</code> at the end of <code>nums</code>.</li> <li>Delete the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>minimum</strong> <strong>length</strong> of </em><code>nums</code><em> after performing the operation any number of times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,10,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Go
func minimumArrayLength(nums []int) int { mi := slices.Min(nums) cnt := 0 for _, x := range nums { if x%mi != 0 { return 1 } if x == mi { cnt++ } } return (cnt + 1) / 2 }
3,012
Minimize Length of Array Using Operations
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <strong>positive</strong> integers.</p> <p>Your task is to <strong>minimize</strong> the length of <code>nums</code> by performing the following operations <strong>any</strong> number of times (including zero):</p> <ul> <li>Select <strong>two</strong> <strong>distinct</strong> indices <code>i</code> and <code>j</code> from <code>nums</code>, such that <code>nums[i] &gt; 0</code> and <code>nums[j] &gt; 0</code>.</li> <li>Insert the result of <code>nums[i] % nums[j]</code> at the end of <code>nums</code>.</li> <li>Delete the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>minimum</strong> <strong>length</strong> of </em><code>nums</code><em> after performing the operation any number of times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,10,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Java
class Solution { public int minimumArrayLength(int[] nums) { int mi = Arrays.stream(nums).min().getAsInt(); int cnt = 0; for (int x : nums) { if (x % mi != 0) { return 1; } if (x == mi) { ++cnt; } } return (cnt + 1) / 2; } }
3,012
Minimize Length of Array Using Operations
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <strong>positive</strong> integers.</p> <p>Your task is to <strong>minimize</strong> the length of <code>nums</code> by performing the following operations <strong>any</strong> number of times (including zero):</p> <ul> <li>Select <strong>two</strong> <strong>distinct</strong> indices <code>i</code> and <code>j</code> from <code>nums</code>, such that <code>nums[i] &gt; 0</code> and <code>nums[j] &gt; 0</code>.</li> <li>Insert the result of <code>nums[i] % nums[j]</code> at the end of <code>nums</code>.</li> <li>Delete the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>minimum</strong> <strong>length</strong> of </em><code>nums</code><em> after performing the operation any number of times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,10,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
Python
class Solution: def minimumArrayLength(self, nums: List[int]) -> int: mi = min(nums) if any(x % mi for x in nums): return 1 return (nums.count(mi) + 1) // 2
3,012
Minimize Length of Array Using Operations
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> containing <strong>positive</strong> integers.</p> <p>Your task is to <strong>minimize</strong> the length of <code>nums</code> by performing the following operations <strong>any</strong> number of times (including zero):</p> <ul> <li>Select <strong>two</strong> <strong>distinct</strong> indices <code>i</code> and <code>j</code> from <code>nums</code>, such that <code>nums[i] &gt; 0</code> and <code>nums[j] &gt; 0</code>.</li> <li>Insert the result of <code>nums[i] % nums[j]</code> at the end of <code>nums</code>.</li> <li>Delete the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>minimum</strong> <strong>length</strong> of </em><code>nums</code><em> after performing the operation any number of times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,3,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1. nums becomes [1,1,3]. Operation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2. nums becomes [1,1]. Operation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0. nums becomes [0]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,10,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3. nums becomes [5,5,5,5]. Operation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. nums becomes [5,5,0]. Operation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1. nums becomes [0,0]. The length of nums cannot be reduced further. Hence, the answer is 2. It can be shown that 2 is the minimum achievable length. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> One way to minimize the length of the array is as follows: Operation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2. nums becomes [2,3]. Operation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0. nums becomes [1]. The length of nums cannot be reduced further. Hence, the answer is 1. It can be shown that 1 is the minimum achievable length.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory
TypeScript
function minimumArrayLength(nums: number[]): number { const mi = Math.min(...nums); let cnt = 0; for (const x of nums) { if (x % mi) { return 1; } if (x === mi) { ++cnt; } } return (cnt + 1) >> 1; }
3,013
Divide an Array Into Subarrays With Minimum Cost II
Hard
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>, and two <strong>positive</strong> integers <code>k</code> and <code>dist</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>k</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>, such that the difference between the starting index of the <strong>second</strong> subarray and the starting index of the <code>kth</code> subarray should be <strong>less than or equal to</strong> <code>dist</code>. In other words, if you divide <code>nums</code> into the subarrays <code>nums[0..(i<sub>1</sub> - 1)], nums[i<sub>1</sub>..(i<sub>2</sub> - 1)], ..., nums[i<sub>k-1</sub>..(n - 1)]</code>, then <code>i<sub>k-1</sub> - i<sub>1</sub> &lt;= dist</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of the cost of these</em> <em>subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,6,4,2], k = 3, dist = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,2,2,1], k = 4, dist = 3 <strong>Output:</strong> 15 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. The division [10], [1], [2,2,2], and [1] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 5 - 1 = 4, which is greater than dist. It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,8,18,9], k = 3, dist = 1 <strong>Output:</strong> 36 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. The division [10], [8,18], and [9] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 3 - 1 = 2, which is greater than dist. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= k &lt;= n</code></li> <li><code>k - 2 &lt;= dist &lt;= n - 2</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
C++
class Solution { public: long long minimumCost(vector<int>& nums, int k, int dist) { --k; multiset<int> l(nums.begin() + 1, nums.begin() + dist + 2), r; long long s = accumulate(nums.begin(), nums.begin() + dist + 2, 0LL); while (l.size() > k) { int x = *l.rbegin(); l.erase(l.find(x)); s -= x; r.insert(x); } long long ans = s; for (int i = dist + 2; i < nums.size(); ++i) { int x = nums[i - dist - 1]; auto it = l.find(x); if (it != l.end()) { l.erase(it); s -= x; } else { r.erase(r.find(x)); } int y = nums[i]; if (y < *l.rbegin()) { l.insert(y); s += y; } else { r.insert(y); } while (l.size() == k - 1) { int x = *r.begin(); r.erase(r.find(x)); l.insert(x); s += x; } while (l.size() == k + 1) { int x = *l.rbegin(); l.erase(l.find(x)); s -= x; r.insert(x); } ans = min(ans, s); } return ans; } };
3,013
Divide an Array Into Subarrays With Minimum Cost II
Hard
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>, and two <strong>positive</strong> integers <code>k</code> and <code>dist</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>k</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>, such that the difference between the starting index of the <strong>second</strong> subarray and the starting index of the <code>kth</code> subarray should be <strong>less than or equal to</strong> <code>dist</code>. In other words, if you divide <code>nums</code> into the subarrays <code>nums[0..(i<sub>1</sub> - 1)], nums[i<sub>1</sub>..(i<sub>2</sub> - 1)], ..., nums[i<sub>k-1</sub>..(n - 1)]</code>, then <code>i<sub>k-1</sub> - i<sub>1</sub> &lt;= dist</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of the cost of these</em> <em>subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,6,4,2], k = 3, dist = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,2,2,1], k = 4, dist = 3 <strong>Output:</strong> 15 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. The division [10], [1], [2,2,2], and [1] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 5 - 1 = 4, which is greater than dist. It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,8,18,9], k = 3, dist = 1 <strong>Output:</strong> 36 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. The division [10], [8,18], and [9] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 3 - 1 = 2, which is greater than dist. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= k &lt;= n</code></li> <li><code>k - 2 &lt;= dist &lt;= n - 2</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
Go
func minimumCost(nums []int, k int, dist int) int64 { k-- l := redblacktree.New[int, int]() r := redblacktree.New[int, int]() merge := func(st *redblacktree.Tree[int, int], x, v int) { c, _ := st.Get(x) if c+v == 0 { st.Remove(x) } else { st.Put(x, c+v) } } s := nums[0] for _, x := range nums[1 : dist+2] { s += x merge(l, x, 1) } size := dist + 1 l2r := func() { x := l.Right().Key merge(l, x, -1) s -= x size-- merge(r, x, 1) } r2l := func() { x := r.Left().Key merge(r, x, -1) merge(l, x, 1) s += x size++ } for size > k { l2r() } ans := s for i := dist + 2; i < len(nums); i++ { x := nums[i-dist-1] if _, ok := l.Get(x); ok { merge(l, x, -1) s -= x size-- } else { merge(r, x, -1) } y := nums[i] if y < l.Right().Key { merge(l, y, 1) s += y size++ } else { merge(r, y, 1) } for size < k { r2l() } for size > k { l2r() } ans = min(ans, s) } return int64(ans) }
3,013
Divide an Array Into Subarrays With Minimum Cost II
Hard
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>, and two <strong>positive</strong> integers <code>k</code> and <code>dist</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>k</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>, such that the difference between the starting index of the <strong>second</strong> subarray and the starting index of the <code>kth</code> subarray should be <strong>less than or equal to</strong> <code>dist</code>. In other words, if you divide <code>nums</code> into the subarrays <code>nums[0..(i<sub>1</sub> - 1)], nums[i<sub>1</sub>..(i<sub>2</sub> - 1)], ..., nums[i<sub>k-1</sub>..(n - 1)]</code>, then <code>i<sub>k-1</sub> - i<sub>1</sub> &lt;= dist</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of the cost of these</em> <em>subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,6,4,2], k = 3, dist = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,2,2,1], k = 4, dist = 3 <strong>Output:</strong> 15 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. The division [10], [1], [2,2,2], and [1] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 5 - 1 = 4, which is greater than dist. It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,8,18,9], k = 3, dist = 1 <strong>Output:</strong> 36 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. The division [10], [8,18], and [9] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 3 - 1 = 2, which is greater than dist. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= k &lt;= n</code></li> <li><code>k - 2 &lt;= dist &lt;= n - 2</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
Java
class Solution { private final TreeMap<Integer, Integer> l = new TreeMap<>(); private final TreeMap<Integer, Integer> r = new TreeMap<>(); private long s; private int size; public long minimumCost(int[] nums, int k, int dist) { --k; s = nums[0]; for (int i = 1; i < dist + 2; ++i) { s += nums[i]; l.merge(nums[i], 1, Integer::sum); } size = dist + 1; while (size > k) { l2r(); } long ans = s; for (int i = dist + 2; i < nums.length; ++i) { int x = nums[i - dist - 1]; if (l.containsKey(x)) { if (l.merge(x, -1, Integer::sum) == 0) { l.remove(x); } s -= x; --size; } else if (r.merge(x, -1, Integer::sum) == 0) { r.remove(x); } int y = nums[i]; if (y < l.lastKey()) { l.merge(y, 1, Integer::sum); ++size; s += y; } else { r.merge(y, 1, Integer::sum); } while (size < k) { r2l(); } while (size > k) { l2r(); } ans = Math.min(ans, s); } return ans; } private void l2r() { int x = l.lastKey(); s -= x; if (l.merge(x, -1, Integer::sum) == 0) { l.remove(x); } --size; r.merge(x, 1, Integer::sum); } private void r2l() { int x = r.firstKey(); if (r.merge(x, -1, Integer::sum) == 0) { r.remove(x); } l.merge(x, 1, Integer::sum); s += x; ++size; } }
3,013
Divide an Array Into Subarrays With Minimum Cost II
Hard
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>, and two <strong>positive</strong> integers <code>k</code> and <code>dist</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>k</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>, such that the difference between the starting index of the <strong>second</strong> subarray and the starting index of the <code>kth</code> subarray should be <strong>less than or equal to</strong> <code>dist</code>. In other words, if you divide <code>nums</code> into the subarrays <code>nums[0..(i<sub>1</sub> - 1)], nums[i<sub>1</sub>..(i<sub>2</sub> - 1)], ..., nums[i<sub>k-1</sub>..(n - 1)]</code>, then <code>i<sub>k-1</sub> - i<sub>1</sub> &lt;= dist</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of the cost of these</em> <em>subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,6,4,2], k = 3, dist = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,2,2,1], k = 4, dist = 3 <strong>Output:</strong> 15 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. The division [10], [1], [2,2,2], and [1] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 5 - 1 = 4, which is greater than dist. It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,8,18,9], k = 3, dist = 1 <strong>Output:</strong> 36 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. The division [10], [8,18], and [9] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 3 - 1 = 2, which is greater than dist. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= k &lt;= n</code></li> <li><code>k - 2 &lt;= dist &lt;= n - 2</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
Python
class Solution: def minimumCost(self, nums: List[int], k: int, dist: int) -> int: def l2r(): nonlocal s x = l.pop() s -= x r.add(x) def r2l(): nonlocal s x = r.pop(0) l.add(x) s += x k -= 1 s = sum(nums[: dist + 2]) l = SortedList(nums[1 : dist + 2]) r = SortedList() while len(l) > k: l2r() ans = s for i in range(dist + 2, len(nums)): x = nums[i - dist - 1] if x in l: l.remove(x) s -= x else: r.remove(x) y = nums[i] if y < l[-1]: l.add(y) s += y else: r.add(y) while len(l) < k: r2l() while len(l) > k: l2r() ans = min(ans, s) return ans
3,013
Divide an Array Into Subarrays With Minimum Cost II
Hard
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>, and two <strong>positive</strong> integers <code>k</code> and <code>dist</code>.</p> <p>The <strong>cost</strong> of an array is the value of its <strong>first</strong> element. For example, the cost of <code>[1,2,3]</code> is <code>1</code> while the cost of <code>[3,4,1]</code> is <code>3</code>.</p> <p>You need to divide <code>nums</code> into <code>k</code> <strong>disjoint contiguous </strong><span data-keyword="subarray-nonempty">subarrays</span>, such that the difference between the starting index of the <strong>second</strong> subarray and the starting index of the <code>kth</code> subarray should be <strong>less than or equal to</strong> <code>dist</code>. In other words, if you divide <code>nums</code> into the subarrays <code>nums[0..(i<sub>1</sub> - 1)], nums[i<sub>1</sub>..(i<sub>2</sub> - 1)], ..., nums[i<sub>k-1</sub>..(n - 1)]</code>, then <code>i<sub>k-1</sub> - i<sub>1</sub> &lt;= dist</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of the cost of these</em> <em>subarrays</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,6,4,2], k = 3, dist = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,2,2,1], k = 4, dist = 3 <strong>Output:</strong> 15 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15. The division [10], [1], [2,2,2], and [1] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 5 - 1 = 4, which is greater than dist. It can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,8,18,9], k = 3, dist = 1 <strong>Output:</strong> 36 <strong>Explanation:</strong> The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because i<sub>k-1</sub> - i<sub>1</sub> is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36. The division [10], [8,18], and [9] is not valid, because the difference between i<sub>k-1</sub> and i<sub>1</sub> is 3 - 1 = 2, which is greater than dist. It can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= k &lt;= n</code></li> <li><code>k - 2 &lt;= dist &lt;= n - 2</code></li> </ul>
Array; Hash Table; Sliding Window; Heap (Priority Queue)
TypeScript
function minimumCost(nums: number[], k: number, dist: number): number { --k; const l = new TreapMultiSet<number>((a, b) => a - b); const r = new TreapMultiSet<number>((a, b) => a - b); let s = nums[0]; for (let i = 1; i < dist + 2; ++i) { s += nums[i]; l.add(nums[i]); } const l2r = () => { const x = l.pop()!; s -= x; r.add(x); }; const r2l = () => { const x = r.shift()!; l.add(x); s += x; }; while (l.size > k) { l2r(); } let ans = s; for (let i = dist + 2; i < nums.length; ++i) { const x = nums[i - dist - 1]; if (l.has(x)) { l.delete(x); s -= x; } else { r.delete(x); } const y = nums[i]; if (y < l.last()!) { l.add(y); s += y; } else { r.add(y); } while (l.size < k) { r2l(); } while (l.size > k) { l2r(); } ans = Math.min(ans, s); } return ans; } type CompareFunction<T, R extends 'number' | 'boolean'> = ( a: T, b: T, ) => R extends 'number' ? number : boolean; interface ITreapMultiSet<T> extends Iterable<T> { add: (...value: T[]) => this; has: (value: T) => boolean; delete: (value: T) => void; bisectLeft: (value: T) => number; bisectRight: (value: T) => number; indexOf: (value: T) => number; lastIndexOf: (value: T) => number; at: (index: number) => T | undefined; first: () => T | undefined; last: () => T | undefined; lower: (value: T) => T | undefined; higher: (value: T) => T | undefined; floor: (value: T) => T | undefined; ceil: (value: T) => T | undefined; shift: () => T | undefined; pop: (index?: number) => T | undefined; count: (value: T) => number; keys: () => IterableIterator<T>; values: () => IterableIterator<T>; rvalues: () => IterableIterator<T>; entries: () => IterableIterator<[number, T]>; readonly size: number; } class TreapNode<T = number> { value: T; count: number; size: number; priority: number; left: TreapNode<T> | null; right: TreapNode<T> | null; constructor(value: T) { this.value = value; this.count = 1; this.size = 1; this.priority = Math.random(); this.left = null; this.right = null; } static getSize(node: TreapNode<any> | null): number { return node?.size ?? 0; } static getFac(node: TreapNode<any> | null): number { return node?.priority ?? 0; } pushUp(): void { let tmp = this.count; tmp += TreapNode.getSize(this.left); tmp += TreapNode.getSize(this.right); this.size = tmp; } rotateRight(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const left = node.left; node.left = left?.right ?? null; left && (left.right = node); left && (node = left); node.right?.pushUp(); node.pushUp(); return node; } rotateLeft(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const right = node.right; node.right = right?.left ?? null; right && (right.left = node); right && (node = right); node.left?.pushUp(); node.pushUp(); return node; } } class TreapMultiSet<T = number> implements ITreapMultiSet<T> { private readonly root: TreapNode<T>; private readonly compareFn: CompareFunction<T, 'number'>; private readonly leftBound: T; private readonly rightBound: T; constructor(compareFn?: CompareFunction<T, 'number'>); constructor(compareFn: CompareFunction<T, 'number'>, leftBound: T, rightBound: T); constructor( compareFn: CompareFunction<T, any> = (a: any, b: any) => a - b, leftBound: any = -Infinity, rightBound: any = Infinity, ) { this.root = new TreapNode<T>(rightBound); this.root.priority = Infinity; this.root.left = new TreapNode<T>(leftBound); this.root.left.priority = -Infinity; this.root.pushUp(); this.leftBound = leftBound; this.rightBound = rightBound; this.compareFn = compareFn; } get size(): number { return this.root.size - 2; } get height(): number { const getHeight = (node: TreapNode<T> | null): number => { if (node == null) return 0; return 1 + Math.max(getHeight(node.left), getHeight(node.right)); }; return getHeight(this.root); } /** * * @complexity `O(logn)` * @description Returns true if value is a member. */ has(value: T): boolean { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): boolean => { if (node == null) return false; if (compare(node.value, value) === 0) return true; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } /** * * @complexity `O(logn)` * @description Add value to sorted set. */ add(...values: T[]): this { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { node.count++; node.pushUp(); } else if (compare(node.value, value) > 0) { if (node.left) { dfs(node.left, value, node, 'left'); } else { node.left = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.left) > node.priority) { parent[direction] = node.rotateRight(); } } else if (compare(node.value, value) < 0) { if (node.right) { dfs(node.right, value, node, 'right'); } else { node.right = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.right) > node.priority) { parent[direction] = node.rotateLeft(); } } parent.pushUp(); }; values.forEach(value => dfs(this.root.left, value, this.root, 'left')); return this; } /** * * @complexity `O(logn)` * @description Remove value from sorted set if it is a member. * If value is not a member, do nothing. */ delete(value: T): void { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { if (node.count > 1) { node.count--; node?.pushUp(); } else if (node.left == null && node.right == null) { parent[direction] = null; } else { // 旋到根节点 if ( node.right == null || TreapNode.getFac(node.left) > TreapNode.getFac(node.right) ) { parent[direction] = node.rotateRight(); dfs(parent[direction]?.right ?? null, value, parent[direction]!, 'right'); } else { parent[direction] = node.rotateLeft(); dfs(parent[direction]?.left ?? null, value, parent[direction]!, 'left'); } } } else if (compare(node.value, value) > 0) { dfs(node.left, value, node, 'left'); } else if (compare(node.value, value) < 0) { dfs(node.right, value, node, 'right'); } parent?.pushUp(); }; dfs(this.root.left, value, this.root, 'left'); } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the left of) any existing values. */ bisectLeft(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the right of) any existing values. */ bisectRight(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left) + node.count; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. */ indexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. */ lastIndexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left) + node.count - 1; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. */ at(index: number): T | undefined { if (index < 0) index += this.size; if (index < 0 || index >= this.size) return undefined; const dfs = (node: TreapNode<T> | null, rank: number): T | undefined => { if (node == null) return undefined; if (TreapNode.getSize(node.left) >= rank) { return dfs(node.left, rank); } else if (TreapNode.getSize(node.left) + node.count >= rank) { return node.value; } else { return dfs(node.right, rank - TreapNode.getSize(node.left) - node.count); } }; const res = dfs(this.root, index + 2); return ([this.leftBound, this.rightBound] as any[]).includes(res) ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than `val`, return `undefined` if no such element found. */ lower(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than `val`, return `undefined` if no such element found. */ higher(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. */ floor(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. */ ceil(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned. */ first(): T | undefined { const iter = this.inOrder(); iter.next(); const res = iter.next().value; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned . */ last(): T | undefined { const iter = this.reverseInOrder(); iter.next(); const res = iter.next().value; return res === this.leftBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Removes the first element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } /** * @complexity `O(logn)` * @description * Removes the last element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ pop(index?: number): T | undefined { if (index == null) { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } const toDelete = this.at(index); if (toDelete == null) return; this.delete(toDelete); return toDelete; } /** * * @complexity `O(logn)` * @description * Returns number of occurrences of value in the sorted set. */ count(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) return node.count; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } *[Symbol.iterator](): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of keys in the set. */ *keys(): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of values in the set. */ *values(): Generator<T, any, any> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns a generator for reversed order traversing the set. */ *rvalues(): Generator<T, any, any> { const iter = this.reverseInOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns an iterable of key, value pairs for every entry in the set. */ *entries(): IterableIterator<[number, T]> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let i = 0; i < steps; i++) { yield [i, iter.next().value]; } } private *inOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.inOrder(root.left); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.inOrder(root.right); } private *reverseInOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.reverseInOrder(root.right); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.reverseInOrder(root.left); } }
3,014
Minimum Number of Pushes to Type Word I
Easy
<p>You are given a string <code>word</code> containing <strong>distinct</strong> lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xycdefghij&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; two pushes on key 2 &quot;c&quot; -&gt; one push on key 3 &quot;d&quot; -&gt; two pushes on key 3 &quot;e&quot; -&gt; one push on key 4 &quot;f&quot; -&gt; one push on key 5 &quot;g&quot; -&gt; one push on key 6 &quot;h&quot; -&gt; one push on key 7 &quot;i&quot; -&gt; one push on key 8 &quot;j&quot; -&gt; one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 26</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>All letters in <code>word</code> are distinct.</li> </ul>
Greedy; Math; String
C++
class Solution { public: int minimumPushes(string word) { int n = word.size(); int ans = 0, k = 1; for (int i = 0; i < n / 8; ++i) { ans += k * 8; ++k; } ans += k * (n % 8); return ans; } };
3,014
Minimum Number of Pushes to Type Word I
Easy
<p>You are given a string <code>word</code> containing <strong>distinct</strong> lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xycdefghij&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; two pushes on key 2 &quot;c&quot; -&gt; one push on key 3 &quot;d&quot; -&gt; two pushes on key 3 &quot;e&quot; -&gt; one push on key 4 &quot;f&quot; -&gt; one push on key 5 &quot;g&quot; -&gt; one push on key 6 &quot;h&quot; -&gt; one push on key 7 &quot;i&quot; -&gt; one push on key 8 &quot;j&quot; -&gt; one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 26</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>All letters in <code>word</code> are distinct.</li> </ul>
Greedy; Math; String
Go
func minimumPushes(word string) (ans int) { n := len(word) k := 1 for i := 0; i < n/8; i++ { ans += k * 8 k++ } ans += k * (n % 8) return }
3,014
Minimum Number of Pushes to Type Word I
Easy
<p>You are given a string <code>word</code> containing <strong>distinct</strong> lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xycdefghij&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; two pushes on key 2 &quot;c&quot; -&gt; one push on key 3 &quot;d&quot; -&gt; two pushes on key 3 &quot;e&quot; -&gt; one push on key 4 &quot;f&quot; -&gt; one push on key 5 &quot;g&quot; -&gt; one push on key 6 &quot;h&quot; -&gt; one push on key 7 &quot;i&quot; -&gt; one push on key 8 &quot;j&quot; -&gt; one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 26</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>All letters in <code>word</code> are distinct.</li> </ul>
Greedy; Math; String
Java
class Solution { public int minimumPushes(String word) { int n = word.length(); int ans = 0, k = 1; for (int i = 0; i < n / 8; ++i) { ans += k * 8; ++k; } ans += k * (n % 8); return ans; } }
3,014
Minimum Number of Pushes to Type Word I
Easy
<p>You are given a string <code>word</code> containing <strong>distinct</strong> lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xycdefghij&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; two pushes on key 2 &quot;c&quot; -&gt; one push on key 3 &quot;d&quot; -&gt; two pushes on key 3 &quot;e&quot; -&gt; one push on key 4 &quot;f&quot; -&gt; one push on key 5 &quot;g&quot; -&gt; one push on key 6 &quot;h&quot; -&gt; one push on key 7 &quot;i&quot; -&gt; one push on key 8 &quot;j&quot; -&gt; one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 26</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>All letters in <code>word</code> are distinct.</li> </ul>
Greedy; Math; String
Python
class Solution: def minimumPushes(self, word: str) -> int: n = len(word) ans, k = 0, 1 for _ in range(n // 8): ans += k * 8 k += 1 ans += k * (n % 8) return ans
3,014
Minimum Number of Pushes to Type Word I
Easy
<p>You are given a string <code>word</code> containing <strong>distinct</strong> lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3014.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20I/images/keypadv1e2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xycdefghij&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; two pushes on key 2 &quot;c&quot; -&gt; one push on key 3 &quot;d&quot; -&gt; two pushes on key 3 &quot;e&quot; -&gt; one push on key 4 &quot;f&quot; -&gt; one push on key 5 &quot;g&quot; -&gt; one push on key 6 &quot;h&quot; -&gt; one push on key 7 &quot;i&quot; -&gt; one push on key 8 &quot;j&quot; -&gt; one push on key 9 Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 26</code></li> <li><code>word</code> consists of lowercase English letters.</li> <li>All letters in <code>word</code> are distinct.</li> </ul>
Greedy; Math; String
TypeScript
function minimumPushes(word: string): number { const n = word.length; let ans = 0; let k = 1; for (let i = 0; i < ((n / 8) | 0); ++i) { ans += k * 8; ++k; } ans += k * (n % 8); return ans; }
3,015
Count the Number of Houses at a Certain Distance I
Medium
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Breadth-First Search; Graph; Prefix Sum
C++
class Solution { public: vector<int> countOfPairs(int n, int x, int y) { vector<int> ans(n); x--; y--; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int a = j - i; int b = abs(x - i) + abs(y - j) + 1; int c = abs(y - i) + abs(x - j) + 1; ans[min({a, b, c}) - 1] += 2; } } return ans; } };
3,015
Count the Number of Houses at a Certain Distance I
Medium
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Breadth-First Search; Graph; Prefix Sum
Go
func countOfPairs(n int, x int, y int) []int { ans := make([]int, n) x, y = x-1, y-1 for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { a := j - i b := abs(x-i) + abs(y-j) + 1 c := abs(x-j) + abs(y-i) + 1 ans[min(a, min(b, c))-1] += 2 } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
3,015
Count the Number of Houses at a Certain Distance I
Medium
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Breadth-First Search; Graph; Prefix Sum
Java
class Solution { public int[] countOfPairs(int n, int x, int y) { int[] ans = new int[n]; x--; y--; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int a = j - i; int b = Math.abs(i - x) + 1 + Math.abs(j - y); int c = Math.abs(i - y) + 1 + Math.abs(j - x); ans[Math.min(a, Math.min(b, c)) - 1] += 2; } } return ans; } }
3,015
Count the Number of Houses at a Certain Distance I
Medium
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Breadth-First Search; Graph; Prefix Sum
Python
class Solution: def countOfPairs(self, n: int, x: int, y: int) -> List[int]: x, y = x - 1, y - 1 ans = [0] * n for i in range(n): for j in range(i + 1, n): a = j - i b = abs(i - x) + 1 + abs(j - y) c = abs(i - y) + 1 + abs(j - x) ans[min(a, b, c) - 1] += 2 return ans
3,015
Count the Number of Houses at a Certain Distance I
Medium
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3015.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20I/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Breadth-First Search; Graph; Prefix Sum
TypeScript
function countOfPairs(n: number, x: number, y: number): number[] { const ans: number[] = Array(n).fill(0); x--; y--; for (let i = 0; i < n; ++i) { for (let j = i + 1; j < n; ++j) { const a = j - i; const b = Math.abs(x - i) + Math.abs(y - j) + 1; const c = Math.abs(y - i) + Math.abs(x - j) + 1; ans[Math.min(a, b, c) - 1] += 2; } } return ans; }
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
C++
class Solution { public: int minimumPushes(string word) { vector<int> cnt(26); for (char& c : word) { ++cnt[c - 'a']; } sort(cnt.rbegin(), cnt.rend()); int ans = 0; for (int i = 0; i < 26; ++i) { ans += (i / 8 + 1) * cnt[i]; } return ans; } };
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Go
func minimumPushes(word string) (ans int) { cnt := make([]int, 26) for _, c := range word { cnt[c-'a']++ } sort.Ints(cnt) for i := 0; i < 26; i++ { ans += (i/8 + 1) * cnt[26-i-1] } return }
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Java
class Solution { public int minimumPushes(String word) { int[] cnt = new int[26]; for (int i = 0; i < word.length(); ++i) { ++cnt[word.charAt(i) - 'a']; } Arrays.sort(cnt); int ans = 0; for (int i = 0; i < 26; ++i) { ans += (i / 8 + 1) * cnt[26 - i - 1]; } return ans; } }
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
JavaScript
function minimumPushes(word) { const cnt = Array(26).fill(0); for (const c of word) { ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } cnt.sort((a, b) => b - a); let ans = 0; for (let i = 0; i < 26; ++i) { ans += (((i / 8) | 0) + 1) * cnt[i]; } return ans; }
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Python
class Solution: def minimumPushes(self, word: str) -> int: cnt = Counter(word) ans = 0 for i, x in enumerate(sorted(cnt.values(), reverse=True)): ans += (i // 8 + 1) * x return ans
3,016
Minimum Number of Pushes to Type Word II
Medium
<p>You are given a string <code>word</code> containing lowercase English letters.</p> <p>Telephone keypads have keys mapped with <strong>distinct</strong> collections of lowercase English letters, which can be used to form words by pushing them. For example, the key <code>2</code> is mapped with <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code>, we need to push the key one time to type <code>&quot;a&quot;</code>, two times to type <code>&quot;b&quot;</code>, and three times to type <code>&quot;c&quot;</code> <em>.</em></p> <p>It is allowed to remap the keys numbered <code>2</code> to <code>9</code> to <strong>distinct</strong> collections of letters. The keys can be remapped to <strong>any</strong> amount of letters, but each letter <strong>must</strong> be mapped to <strong>exactly</strong> one key. You need to find the <strong>minimum</strong> number of times the keys will be pushed to type the string <code>word</code>.</p> <p>Return <em>the <strong>minimum</strong> number of pushes needed to type </em><code>word</code> <em>after remapping the keys</em>.</p> <p>An example mapping of letters to keys on a telephone keypad is given below. Note that <code>1</code>, <code>*</code>, <code>#</code>, and <code>0</code> do <strong>not</strong> map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypaddesc.png" style="width: 329px; height: 313px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv1e1.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;abcde&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/edited.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;xyzxyzxyzxyz&quot; <strong>Output:</strong> 12 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;x&quot; -&gt; one push on key 2 &quot;y&quot; -&gt; one push on key 3 &quot;z&quot; -&gt; one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3016.Minimum%20Number%20of%20Pushes%20to%20Type%20Word%20II/images/keypadv2.png" style="width: 329px; height: 313px;" /> <pre> <strong>Input:</strong> word = &quot;aabbccddeeffgghhiiiiii&quot; <strong>Output:</strong> 24 <strong>Explanation:</strong> The remapped keypad given in the image provides the minimum cost. &quot;a&quot; -&gt; one push on key 2 &quot;b&quot; -&gt; one push on key 3 &quot;c&quot; -&gt; one push on key 4 &quot;d&quot; -&gt; one push on key 5 &quot;e&quot; -&gt; one push on key 6 &quot;f&quot; -&gt; one push on key 7 &quot;g&quot; -&gt; one push on key 8 &quot;h&quot; -&gt; two pushes on key 9 &quot;i&quot; -&gt; one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
TypeScript
function minimumPushes(word: string): number { const cnt: number[] = Array(26).fill(0); for (const c of word) { ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } cnt.sort((a, b) => b - a); let ans = 0; for (let i = 0; i < 26; ++i) { ans += (((i / 8) | 0) + 1) * cnt[i]; } return ans; }
3,017
Count the Number of Houses at a Certain Distance II
Hard
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Graph; Prefix Sum
C++
class Solution { public: vector<long long> countOfPairs(int n, int x, int y) { --x, --y; if (x > y) { swap(x, y); } vector<long long> diff(n); for (int i = 0; i < n; ++i) { diff[0] += 1 + 1; ++diff[min(abs(i - x), abs(i - y) + 1)]; ++diff[min(abs(i - y), abs(i - x) + 1)]; --diff[min(abs(i - 0), abs(i - y) + 1 + abs(x - 0))]; --diff[min(abs(i - (n - 1)), abs(i - x) + 1 + abs(y - (n - 1)))]; --diff[max(x - i, 0) + max(i - y, 0) + ((y - x) + 0) / 2]; --diff[max(x - i, 0) + max(i - y, 0) + ((y - x) + 1) / 2]; } for (int i = 0; i + 1 < n; ++i) { diff[i + 1] += diff[i]; } return diff; } };
3,017
Count the Number of Houses at a Certain Distance II
Hard
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Graph; Prefix Sum
Go
func countOfPairs(n int, x int, y int) []int64 { if x > y { x, y = y, x } A := make([]int64, n) for i := 1; i <= n; i++ { A[0] += 2 A[min(int64(i-1), int64(math.Abs(float64(i-y)))+int64(x))] -= 1 A[min(int64(n-i), int64(math.Abs(float64(i-x)))+1+int64(n-y))] -= 1 A[min(int64(math.Abs(float64(i-x))), int64(math.Abs(float64(y-i)))+1)] += 1 A[min(int64(math.Abs(float64(i-x)))+1, int64(math.Abs(float64(y-i))))] += 1 r := max(int64(x-i), 0) + max(int64(i-y), 0) A[r+int64((y-x+0)/2)] -= 1 A[r+int64((y-x+1)/2)] -= 1 } for i := 1; i < n; i++ { A[i] += A[i-1] } return A }
3,017
Count the Number of Houses at a Certain Distance II
Hard
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Graph; Prefix Sum
Java
class Solution { public long[] countOfPairs(int n, int x, int y) { --x; --y; if (x > y) { int temp = x; x = y; y = temp; } long[] diff = new long[n]; for (int i = 0; i < n; ++i) { diff[0] += 1 + 1; ++diff[Math.min(Math.abs(i - x), Math.abs(i - y) + 1)]; ++diff[Math.min(Math.abs(i - y), Math.abs(i - x) + 1)]; --diff[Math.min(Math.abs(i - 0), Math.abs(i - y) + 1 + Math.abs(x - 0))]; --diff[Math.min(Math.abs(i - (n - 1)), Math.abs(i - x) + 1 + Math.abs(y - (n - 1)))]; --diff[Math.max(x - i, 0) + Math.max(i - y, 0) + ((y - x) + 0) / 2]; --diff[Math.max(x - i, 0) + Math.max(i - y, 0) + ((y - x) + 1) / 2]; } for (int i = 0; i + 1 < n; ++i) { diff[i + 1] += diff[i]; } return diff; } }
3,017
Count the Number of Houses at a Certain Distance II
Hard
<p>You are given three <strong>positive</strong> integers <code>n</code>, <code>x</code>, and <code>y</code>.</p> <p>In a city, there exist houses numbered <code>1</code> to <code>n</code> connected by <code>n</code> streets. There is a street connecting the house numbered <code>i</code> with the house numbered <code>i + 1</code> for all <code>1 &lt;= i &lt;= n - 1</code> . An additional street connects the house numbered <code>x</code> with the house numbered <code>y</code>.</p> <p>For each <code>k</code>, such that <code>1 &lt;= k &lt;= n</code>, you need to find the number of <strong>pairs of houses</strong> <code>(house<sub>1</sub>, house<sub>2</sub>)</code> such that the <strong>minimum</strong> number of streets that need to be traveled to reach <code>house<sub>2</sub></code> from <code>house<sub>1</sub></code> is <code>k</code>.</p> <p>Return <em>a <strong>1-indexed</strong> array </em><code>result</code><em> of length </em><code>n</code><em> where </em><code>result[k]</code><em> represents the <strong>total</strong> number of pairs of houses such that the <strong>minimum</strong> streets required to reach one house from the other is </em><code>k</code>.</p> <p><strong>Note</strong> that <code>x</code> and <code>y</code> can be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example2.png" style="width: 474px; height: 197px;" /> <pre> <strong>Input:</strong> n = 3, x = 1, y = 3 <strong>Output:</strong> [6,0,0] <strong>Explanation:</strong> Let&#39;s look at each pair of houses: - For the pair (1, 2), we can go from house 1 to house 2 directly. - For the pair (2, 1), we can go from house 2 to house 1 directly. - For the pair (1, 3), we can go from house 1 to house 3 directly. - For the pair (3, 1), we can go from house 3 to house 1 directly. - For the pair (2, 3), we can go from house 2 to house 3 directly. - For the pair (3, 2), we can go from house 3 to house 2 directly. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example3.png" style="width: 668px; height: 174px;" /> <pre> <strong>Input:</strong> n = 5, x = 2, y = 4 <strong>Output:</strong> [10,8,2,0,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4). - For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3). - For k == 3, the pairs are (1, 5), and (5, 1). - For k == 4 and k == 5, there are no pairs. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3017.Count%20the%20Number%20of%20Houses%20at%20a%20Certain%20Distance%20II/images/example5.png" style="width: 544px; height: 130px;" /> <pre> <strong>Input:</strong> n = 4, x = 1, y = 1 <strong>Output:</strong> [6,4,2,0] <strong>Explanation:</strong> For each distance k the pairs are: - For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3). - For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2). - For k == 3, the pairs are (1, 4), and (4, 1). - For k == 4, there are no pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> </ul>
Graph; Prefix Sum
Python
class Solution: def countOfPairs(self, n: int, x: int, y: int) -> List[int]: if abs(x - y) <= 1: return [2 * x for x in reversed(range(n))] cycle_len = abs(x - y) + 1 n2 = n - cycle_len + 2 res = [2 * x for x in reversed(range(n2))] while len(res) < n: res.append(0) res2 = [cycle_len * 2] * (cycle_len >> 1) if not cycle_len & 1: res2[-1] = cycle_len res2[0] -= 2 for i in range(len(res2)): res[i] += res2[i] if x > y: x, y = y, x tail1 = x - 1 tail2 = n - y for tail in (tail1, tail2): if not tail: continue i_mx = tail + (cycle_len >> 1) val_mx = 4 * min((cycle_len - 3) >> 1, tail) i_mx2 = i_mx - (1 - (cycle_len & 1)) res3 = [val_mx] * i_mx res3[0] = 0 res3[1] = 0 if not cycle_len & 1: res3[-1] = 0 for i, j in enumerate(range(4, val_mx, 4)): res3[i + 2] = j res3[i_mx2 - i - 1] = j for i in range(1, tail + 1): res3[i] += 2 if not cycle_len & 1: mn = cycle_len >> 1 for i in range(mn, mn + tail): res3[i] += 2 for i in range(len(res3)): res[i] += res3[i] return res
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int maximumProcessableQueries(vector<int>& nums, vector<int>& queries) { int n = nums.size(); int f[n][n]; memset(f, 0, sizeof(f)); int m = queries.size(); for (int i = 0; i < n; ++i) { for (int j = n - 1; j >= i; --j) { if (i > 0) { f[i][j] = max(f[i][j], f[i - 1][j] + (nums[i - 1] >= queries[f[i - 1][j]] ? 1 : 0)); } if (j + 1 < n) { f[i][j] = max(f[i][j], f[i][j + 1] + (nums[j + 1] >= queries[f[i][j + 1]] ? 1 : 0)); } if (f[i][j] == m) { return m; } } } int ans = 0; for (int i = 0; i < n; ++i) { ans = max(ans, f[i][i] + (nums[i] >= queries[f[i][i]] ? 1 : 0)); } return ans; } };
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maximumProcessableQueries(nums []int, queries []int) (ans int) { n := len(nums) f := make([][]int, n) for i := range f { f[i] = make([]int, n) } m := len(queries) for i := 0; i < n; i++ { for j := n - 1; j >= i; j-- { if i > 0 { t := 0 if nums[i-1] >= queries[f[i-1][j]] { t = 1 } f[i][j] = max(f[i][j], f[i-1][j]+t) } if j+1 < n { t := 0 if nums[j+1] >= queries[f[i][j+1]] { t = 1 } f[i][j] = max(f[i][j], f[i][j+1]+t) } if f[i][j] == m { return m } } } for i := 0; i < n; i++ { t := 0 if nums[i] >= queries[f[i][i]] { t = 1 } ans = max(ans, f[i][i]+t) } return }
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int maximumProcessableQueries(int[] nums, int[] queries) { int n = nums.length; int[][] f = new int[n][n]; int m = queries.length; for (int i = 0; i < n; ++i) { for (int j = n - 1; j >= i; --j) { if (i > 0) { f[i][j] = Math.max( f[i][j], f[i - 1][j] + (nums[i - 1] >= queries[f[i - 1][j]] ? 1 : 0)); } if (j + 1 < n) { f[i][j] = Math.max( f[i][j], f[i][j + 1] + (nums[j + 1] >= queries[f[i][j + 1]] ? 1 : 0)); } if (f[i][j] == m) { return m; } } } int ans = 0; for (int i = 0; i < n; ++i) { ans = Math.max(ans, f[i][i] + (nums[i] >= queries[f[i][i]] ? 1 : 0)); } return ans; } }
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumProcessableQueries(self, nums: List[int], queries: List[int]) -> int: n = len(nums) f = [[0] * n for _ in range(n)] m = len(queries) for i in range(n): for j in range(n - 1, i - 1, -1): if i: f[i][j] = max( f[i][j], f[i - 1][j] + (nums[i - 1] >= queries[f[i - 1][j]]) ) if j + 1 < n: f[i][j] = max( f[i][j], f[i][j + 1] + (nums[j + 1] >= queries[f[i][j + 1]]) ) if f[i][j] == m: return m return max(f[i][i] + (nums[i] >= queries[f[i][i]]) for i in range(n))
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_processable_queries(nums: Vec<i32>, queries: Vec<i32>) -> i32 { let n = nums.len(); let m = queries.len(); let mut f = vec![vec![0; n]; n]; for i in 0..n { for j in (i..n).rev() { if i > 0 { let idx = f[i - 1][j] as usize; if idx < m { f[i][j] = f[i][j] .max(f[i - 1][j] + if nums[i - 1] >= queries[idx] { 1 } else { 0 }); } } if j + 1 < n { let idx = f[i][j + 1] as usize; if idx < m { f[i][j] = f[i][j] .max(f[i][j + 1] + if nums[j + 1] >= queries[idx] { 1 } else { 0 }); } } if f[i][j] as usize == m { return m as i32; } } } let mut ans = 0; for i in 0..n { let idx = f[i][i] as usize; if idx < m { ans = ans.max(f[i][i] + if nums[i] >= queries[idx] { 1 } else { 0 }); } else { ans = ans.max(f[i][i]); } } ans } }
3,018
Maximum Number of Removal Queries That Can Be Processed I
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and a <strong>0-indexed</strong> array <code>queries</code>.</p> <p>You can do the following operation at the beginning <strong>at most once</strong>:</p> <ul> <li>Replace <code>nums</code> with a <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code>.</li> </ul> <p>We start processing queries in the given order; for each query, we do the following:</p> <ul> <li>If the first <strong>and</strong> the last element of <code>nums</code> is <strong>less than</strong> <code>queries[i]</code>, the processing of queries <strong>ends</strong>.</li> <li>Otherwise, we choose either the first <strong>or</strong> the last element of <code>nums</code> if it is <strong>greater than or equal to</strong> <code>queries[i]</code>, and we <strong>remove</strong> the chosen element from <code>nums</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of queries that can be processed by doing the operation optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], queries = [1,2,3,4,6] <strong>Output:</strong> 4 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 1 &lt;= 1, then nums becomes [2,3,4,5]. 2- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,4,5]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes [4,5]. 4- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [5]. 5- We can not choose any elements from nums since they are not greater than or equal to 5. Hence, the answer is 4. It can be shown that we can&#39;t process more than 4 queries. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,2], queries = [2,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> We don&#39;t do any operation and process the queries as follows: 1- We choose and remove nums[0] since 2 &lt;= 2, then nums becomes [3,2]. 2- We choose and remove nums[1] since 2 &lt;= 2, then nums becomes [3]. 3- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. Hence, the answer is 3. It can be shown that we can&#39;t process more than 3 queries. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,3], queries = [4,3,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> First we replace nums with the subsequence of nums [4,3]. Then we can process the queries as follows: 1- We choose and remove nums[0] since 4 &lt;= 4, then nums becomes [3]. 2- We choose and remove nums[0] since 3 &lt;= 3, then nums becomes []. 3- We can not process any more queries since nums is empty. Hence, the answer is 2. It can be shown that we can&#39;t process more than 2 queries. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= queries.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumProcessableQueries(nums: number[], queries: number[]): number { const n = nums.length; const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); const m = queries.length; for (let i = 0; i < n; ++i) { for (let j = n - 1; j >= i; --j) { if (i > 0) { f[i][j] = Math.max( f[i][j], f[i - 1][j] + (nums[i - 1] >= queries[f[i - 1][j]] ? 1 : 0), ); } if (j + 1 < n) { f[i][j] = Math.max( f[i][j], f[i][j + 1] + (nums[j + 1] >= queries[f[i][j + 1]] ? 1 : 0), ); } if (f[i][j] == m) { return m; } } } let ans = 0; for (let i = 0; i < n; ++i) { ans = Math.max(ans, f[i][i] + (nums[i] >= queries[f[i][i]] ? 1 : 0)); } return ans; }
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
C++
class Solution { public: int countKeyChanges(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); int ans = 0; for (int i = 1; i < s.size(); ++i) { ans += s[i] != s[i - 1]; } return ans; } };
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
Go
func countKeyChanges(s string) (ans int) { s = strings.ToLower(s) for i, c := range s[1:] { if byte(c) != s[i] { ans++ } } return }
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
Java
class Solution { public int countKeyChanges(String s) { int ans = 0; for (int i = 1; i < s.length(); ++i) { if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i - 1))) { ++ans; } } return ans; } }
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
Python
class Solution: def countKeyChanges(self, s: str) -> int: return sum(a != b for a, b in pairwise(s.lower()))
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
Rust
impl Solution { pub fn count_key_changes(s: String) -> i32 { let s = s.to_lowercase(); let bytes = s.as_bytes(); let mut ans = 0; for i in 1..bytes.len() { if bytes[i] != bytes[i - 1] { ans += 1; } } ans } }
3,019
Number of Changing Keys
Easy
<p>You are given a <strong>0-indexed </strong>string <code>s</code> typed by a user. Changing a key is defined as using a key different from the last used key. For example, <code>s = &quot;ab&quot;</code> has a change of a key while <code>s = &quot;bBBb&quot;</code> does not have any.</p> <p>Return <em>the number of times the user had to change the key. </em></p> <p><strong>Note: </strong>Modifiers like <code>shift</code> or <code>caps lock</code> won&#39;t be counted in changing the key that is if a user typed the letter <code>&#39;a&#39;</code> and then the letter <code>&#39;A&#39;</code> then it will not be considered as a changing of key.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aAbBcC&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> From s[0] = &#39;a&#39; to s[1] = &#39;A&#39;, there is no change of key as caps lock or shift is not counted. From s[1] = &#39;A&#39; to s[2] = &#39;b&#39;, there is a change of key. From s[2] = &#39;b&#39; to s[3] = &#39;B&#39;, there is no change of key as caps lock or shift is not counted. From s[3] = &#39;B&#39; to s[4] = &#39;c&#39;, there is a change of key. From s[4] = &#39;c&#39; to s[5] = &#39;C&#39;, there is no change of key as caps lock or shift is not counted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;AaAaAaaA&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no change of key since only the letters &#39;a&#39; and &#39;A&#39; are<!-- notionvc: 8849fe75-f31e-41dc-a2e0-b7d33d8427d2 --> pressed which does not require change of key. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of only upper case and lower case English letters.</li> </ul>
String
TypeScript
function countKeyChanges(s: string): number { s = s.toLowerCase(); let ans = 0; for (let i = 1; i < s.length; ++i) { if (s[i] !== s[i - 1]) { ++ans; } } return ans; }
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
C++
class Solution { public: int maximumLength(vector<int>& nums) { unordered_map<long long, int> cnt; for (int x : nums) { ++cnt[x]; } int ans = cnt[1] - (cnt[1] % 2 ^ 1); cnt.erase(1); for (auto [v, _] : cnt) { int t = 0; long long x = v; while (cnt.count(x) && cnt[x] > 1) { x = x * x; t += 2; } t += cnt.count(x) ? 1 : -1; ans = max(ans, t); } return ans; } };
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
Go
func maximumLength(nums []int) (ans int) { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } ans = cnt[1] - (cnt[1]%2 ^ 1) delete(cnt, 1) for x := range cnt { t := 0 for cnt[x] > 1 { x = x * x t += 2 } if cnt[x] > 0 { t += 1 } else { t -= 1 } ans = max(ans, t) } return }
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
Java
class Solution { public int maximumLength(int[] nums) { Map<Long, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge((long) x, 1, Integer::sum); } Integer t = cnt.remove(1L); int ans = t == null ? 0 : t - (t % 2 ^ 1); for (long x : cnt.keySet()) { t = 0; while (cnt.getOrDefault(x, 0) > 1) { x = x * x; t += 2; } t += cnt.getOrDefault(x, -1); ans = Math.max(ans, t); } return ans; } }
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
Python
class Solution: def maximumLength(self, nums: List[int]) -> int: cnt = Counter(nums) ans = cnt[1] - (cnt[1] % 2 ^ 1) del cnt[1] for x in cnt: t = 0 while cnt[x] > 1: x = x * x t += 2 t += 1 if cnt[x] else -1 ans = max(ans, t) return ans
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
Rust
use std::collections::HashMap; impl Solution { pub fn maximum_length(nums: Vec<i32>) -> i32 { let mut cnt: HashMap<i64, i32> = HashMap::new(); for &x in &nums { *cnt.entry(x as i64).or_insert(0) += 1; } let mut ans = 0; if let Some(t) = cnt.remove(&1) { ans = t - ((t % 2) ^ 1); } for &key in cnt.keys() { let mut x = key; let mut t = 0; while *cnt.get(&x).unwrap_or(&0) > 1 { x = x * x; t += 2; } t += cnt.get(&x).unwrap_or(&-1); ans = ans.max(t); } ans } }
3,020
Find the Maximum Number of Elements in Subset
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p> <ul> <li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,1,2,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Enumeration
TypeScript
function maximumLength(nums: number[]): number { const cnt: Map<number, number> = new Map(); for (const x of nums) { cnt.set(x, (cnt.get(x) ?? 0) + 1); } let ans = cnt.has(1) ? cnt.get(1)! - (cnt.get(1)! % 2 ^ 1) : 0; cnt.delete(1); for (let [x, _] of cnt) { let t = 0; while (cnt.has(x) && cnt.get(x)! > 1) { x = x * x; t += 2; } t += cnt.has(x) ? 1 : -1; ans = Math.max(ans, t); } return ans; }
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
C++
class Solution { public: long long flowerGame(int n, int m) { long long a1 = (n + 1) / 2; long long b1 = (m + 1) / 2; long long a2 = n / 2; long long b2 = m / 2; return a1 * b2 + a2 * b1; } };
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
Go
func flowerGame(n int, m int) int64 { a1, b1 := (n+1)/2, (m+1)/2 a2, b2 := n/2, m/2 return int64(a1*b2 + a2*b1) }
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
Java
class Solution { public long flowerGame(int n, int m) { long a1 = (n + 1) / 2; long b1 = (m + 1) / 2; long a2 = n / 2; long b2 = m / 2; return a1 * b2 + a2 * b1; } }
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
JavaScript
/** * @param {number} n * @param {number} m * @return {number} */ var flowerGame = function (n, m) { const [a1, b1] = [(n + 1) >> 1, (m + 1) >> 1]; const [a2, b2] = [n >> 1, m >> 1]; return a1 * b2 + a2 * b1; };
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
Python
class Solution: def flowerGame(self, n: int, m: int) -> int: a1 = (n + 1) // 2 b1 = (m + 1) // 2 a2 = n // 2 b2 = m // 2 return a1 * b2 + a2 * b1
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
Rust
impl Solution { pub fn flower_game(n: i32, m: i32) -> i64 { let a1 = ((n + 1) / 2) as i64; let b1 = ((m + 1) / 2) as i64; let a2 = (n / 2) as i64; let b2 = (m / 2) as i64; a1 * b2 + a2 * b1 } }
3,021
Alice and Bob Playing Flower Game
Medium
<p>Alice and Bob are playing a turn-based game on a field, with two lanes of flowers between them. There are <code>x</code> flowers in the first lane between Alice and Bob, and <code>y</code> flowers in the second lane between them.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3021.Alice%20and%20Bob%20Playing%20Flower%20Game/images/3021.png" style="width: 300px; height: 150px;" /></p> <p>The game proceeds as follows:</p> <ol> <li>Alice takes the first turn.</li> <li>In each turn, a player must choose either one of the lane&nbsp;and pick one flower from that side.</li> <li>At the end of the turn, if there are no flowers left at all in either lane, the <strong>current</strong> player captures their opponent and wins the game.</li> </ol> <p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p> <ul> <li>Alice must win the game according to the described rules.</li> <li>The number of flowers <code>x</code> in the first lane must be in the range <code>[1,n]</code>.</li> <li>The number of flowers <code>y</code> in the second lane must be in the range <code>[1,m]</code>.</li> </ul> <p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, m = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, m = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> No pairs satisfy the conditions described in the statement. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> </ul>
Math
TypeScript
function flowerGame(n: number, m: number): number { const [a1, b1] = [(n + 1) >> 1, (m + 1) >> 1]; const [a2, b2] = [n >> 1, m >> 1]; return a1 * b2 + a2 * b1; }
3,022
Minimize OR of Remaining Elements Using Operations
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 &lt;= i &lt; nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] &amp; nums[i + 1]</code>, where <code>&amp;</code> represents the bitwise <code>AND</code> operator.</p> <p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,3,2,7], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [1,3,2,7]. 2. Replace nums[2] and nums[3] with (nums[2] &amp; nums[3]) so that nums becomes equal to [1,3,2]. The bitwise-or of the final array is 3. It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,15,14,2,8]. 2. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,14,2,8]. 3. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [2,2,8]. 4. Replace nums[1] and nums[2] with (nums[1] &amp; nums[2]) so that nums becomes equal to [2,0]. The bitwise-or of the final array is 2. It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1 <strong>Output:</strong> 15 <strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15. It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; 2<sup>30</sup></code></li> <li><code>0 &lt;= k &lt; nums.length</code></li> </ul>
Greedy; Bit Manipulation; Array
C++
class Solution { public: int minOrAfterOperations(vector<int>& nums, int k) { int ans = 0, rans = 0; for (int i = 29; i >= 0; i--) { int test = ans + (1 << i); int cnt = 0; int val = 0; for (auto it : nums) { if (val == 0) { val = test & it; } else { val &= test & it; } if (val) { cnt++; } } if (cnt > k) { rans += (1 << i); } else { ans += (1 << i); } } return rans; } };
3,022
Minimize OR of Remaining Elements Using Operations
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 &lt;= i &lt; nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] &amp; nums[i + 1]</code>, where <code>&amp;</code> represents the bitwise <code>AND</code> operator.</p> <p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,3,2,7], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [1,3,2,7]. 2. Replace nums[2] and nums[3] with (nums[2] &amp; nums[3]) so that nums becomes equal to [1,3,2]. The bitwise-or of the final array is 3. It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,15,14,2,8]. 2. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,14,2,8]. 3. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [2,2,8]. 4. Replace nums[1] and nums[2] with (nums[1] &amp; nums[2]) so that nums becomes equal to [2,0]. The bitwise-or of the final array is 2. It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1 <strong>Output:</strong> 15 <strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15. It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; 2<sup>30</sup></code></li> <li><code>0 &lt;= k &lt; nums.length</code></li> </ul>
Greedy; Bit Manipulation; Array
Go
func minOrAfterOperations(nums []int, k int) int { ans := 0 rans := 0 for i := 29; i >= 0; i-- { test := ans + (1 << i) cnt := 0 val := 0 for _, num := range nums { if val == 0 { val = test & num } else { val &= test & num } if val != 0 { cnt++ } } if cnt > k { rans += (1 << i) } else { ans += (1 << i) } } return rans }
3,022
Minimize OR of Remaining Elements Using Operations
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 &lt;= i &lt; nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] &amp; nums[i + 1]</code>, where <code>&amp;</code> represents the bitwise <code>AND</code> operator.</p> <p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,3,2,7], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [1,3,2,7]. 2. Replace nums[2] and nums[3] with (nums[2] &amp; nums[3]) so that nums becomes equal to [1,3,2]. The bitwise-or of the final array is 3. It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,15,14,2,8]. 2. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,14,2,8]. 3. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [2,2,8]. 4. Replace nums[1] and nums[2] with (nums[1] &amp; nums[2]) so that nums becomes equal to [2,0]. The bitwise-or of the final array is 2. It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1 <strong>Output:</strong> 15 <strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15. It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; 2<sup>30</sup></code></li> <li><code>0 &lt;= k &lt; nums.length</code></li> </ul>
Greedy; Bit Manipulation; Array
Java
class Solution { public int minOrAfterOperations(int[] nums, int k) { int ans = 0, rans = 0; for (int i = 29; i >= 0; i--) { int test = ans + (1 << i); int cnt = 0; int val = 0; for (int num : nums) { if (val == 0) { val = test & num; } else { val &= test & num; } if (val != 0) { cnt++; } } if (cnt > k) { rans += (1 << i); } else { ans += (1 << i); } } return rans; } }
3,022
Minimize OR of Remaining Elements Using Operations
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 &lt;= i &lt; nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] &amp; nums[i + 1]</code>, where <code>&amp;</code> represents the bitwise <code>AND</code> operator.</p> <p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,3,2,7], k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [1,3,2,7]. 2. Replace nums[2] and nums[3] with (nums[2] &amp; nums[3]) so that nums becomes equal to [1,3,2]. The bitwise-or of the final array is 3. It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> Let&#39;s do the following operations: 1. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,15,14,2,8]. 2. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [3,14,2,8]. 3. Replace nums[0] and nums[1] with (nums[0] &amp; nums[1]) so that nums becomes equal to [2,2,8]. 4. Replace nums[1] and nums[2] with (nums[1] &amp; nums[2]) so that nums becomes equal to [2,0]. The bitwise-or of the final array is 2. It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1 <strong>Output:</strong> 15 <strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15. It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; 2<sup>30</sup></code></li> <li><code>0 &lt;= k &lt; nums.length</code></li> </ul>
Greedy; Bit Manipulation; Array
Python
class Solution: def minOrAfterOperations(self, nums: List[int], k: int) -> int: ans = 0 rans = 0 for i in range(29, -1, -1): test = ans + (1 << i) cnt = 0 val = 0 for num in nums: if val == 0: val = test & num else: val &= test & num if val: cnt += 1 if cnt > k: rans += 1 << i else: ans += 1 << i return rans
3,023
Find Pattern in Infinite Stream I
Medium
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p> <p>The class <code>InfiniteStream</code> contains the following function:</p> <ul> <li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li> </ul> <p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0] <strong>Output:</strong> 0 <strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 100</code></li> <li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li> <li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li> <li>The input is generated such that the pattern&#39;s start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li> </ul>
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
C++
/** * Definition for an infinite stream. * class InfiniteStream { * public: * InfiniteStream(vector<int> bits); * int next(); * }; */ class Solution { public: int findPattern(InfiniteStream* stream, vector<int>& pattern) { long long a = 0, b = 0; int m = pattern.size(); int half = m >> 1; long long mask1 = (1LL << half) - 1; long long mask2 = (1LL << (m - half)) - 1; for (int i = 0; i < half; ++i) { a |= (long long) pattern[i] << (half - 1 - i); } for (int i = half; i < m; ++i) { b |= (long long) pattern[i] << (m - 1 - i); } long x = 0, y = 0; for (int i = 1;; ++i) { int v = stream->next(); y = y << 1 | v; v = (int) ((y >> (m - half)) & 1); y &= mask2; x = x << 1 | v; x &= mask1; if (i >= m && a == x && b == y) { return i - m; } } } };
3,023
Find Pattern in Infinite Stream I
Medium
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p> <p>The class <code>InfiniteStream</code> contains the following function:</p> <ul> <li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li> </ul> <p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0] <strong>Output:</strong> 0 <strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 100</code></li> <li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li> <li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li> <li>The input is generated such that the pattern&#39;s start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li> </ul>
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
Go
/** * Definition for an infinite stream. * type InfiniteStream interface { * Next() int * } */ func findPattern(stream InfiniteStream, pattern []int) int { a, b := 0, 0 m := len(pattern) half := m >> 1 mask1 := (1 << half) - 1 mask2 := (1 << (m - half)) - 1 for i := 0; i < half; i++ { a |= pattern[i] << (half - 1 - i) } for i := half; i < m; i++ { b |= pattern[i] << (m - 1 - i) } x, y := 0, 0 for i := 1; ; i++ { v := stream.Next() y = y<<1 | v v = (y >> (m - half)) & 1 y &= mask2 x = x<<1 | v x &= mask1 if i >= m && a == x && b == y { return i - m } } }
3,023
Find Pattern in Infinite Stream I
Medium
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p> <p>The class <code>InfiniteStream</code> contains the following function:</p> <ul> <li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li> </ul> <p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0] <strong>Output:</strong> 0 <strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 100</code></li> <li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li> <li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li> <li>The input is generated such that the pattern&#39;s start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li> </ul>
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
Java
/** * Definition for an infinite stream. * class InfiniteStream { * public InfiniteStream(int[] bits); * public int next(); * } */ class Solution { public int findPattern(InfiniteStream infiniteStream, int[] pattern) { long a = 0, b = 0; int m = pattern.length; int half = m >> 1; long mask1 = (1L << half) - 1; long mask2 = (1L << (m - half)) - 1; for (int i = 0; i < half; ++i) { a |= (long) pattern[i] << (half - 1 - i); } for (int i = half; i < m; ++i) { b |= (long) pattern[i] << (m - 1 - i); } long x = 0, y = 0; for (int i = 1;; ++i) { int v = infiniteStream.next(); y = y << 1 | v; v = (int) ((y >> (m - half)) & 1); y &= mask2; x = x << 1 | v; x &= mask1; if (i >= m && a == x && b == y) { return i - m; } } } }
3,023
Find Pattern in Infinite Stream I
Medium
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p> <p>The class <code>InfiniteStream</code> contains the following function:</p> <ul> <li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li> </ul> <p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0] <strong>Output:</strong> 0 <strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= pattern.length &lt;= 100</code></li> <li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li> <li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li> <li>The input is generated such that the pattern&#39;s start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li> </ul>
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
Python
# Definition for an infinite stream. # class InfiniteStream: # def next(self) -> int: # pass class Solution: def findPattern( self, stream: Optional["InfiniteStream"], pattern: List[int] ) -> int: a = b = 0 m = len(pattern) half = m >> 1 mask1 = (1 << half) - 1 mask2 = (1 << (m - half)) - 1 for i in range(half): a |= pattern[i] << (half - 1 - i) for i in range(half, m): b |= pattern[i] << (m - 1 - i) x = y = 0 for i in count(1): v = stream.next() y = y << 1 | v v = y >> (m - half) & 1 y &= mask2 x = x << 1 | v x &= mask1 if i >= m and a == x and b == y: return i - m
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
C++
class Solution { public: string triangleType(vector<int>& nums) { sort(nums.begin(), nums.end()); if (nums[0] + nums[1] <= nums[2]) { return "none"; } if (nums[0] == nums[2]) { return "equilateral"; } if (nums[0] == nums[1] || nums[1] == nums[2]) { return "isosceles"; } return "scalene"; } };
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
C#
public class Solution { public string TriangleType(int[] nums) { Array.Sort(nums); if (nums[0] + nums[1] <= nums[2]) { return "none"; } if (nums[0] == nums[2]) { return "equilateral"; } if (nums[0] == nums[1] || nums[1] == nums[2]) { return "isosceles"; } return "scalene"; } }
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
Go
func triangleType(nums []int) string { sort.Ints(nums) if nums[0]+nums[1] <= nums[2] { return "none" } if nums[0] == nums[2] { return "equilateral" } if nums[0] == nums[1] || nums[1] == nums[2] { return "isosceles" } return "scalene" }
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
Java
class Solution { public String triangleType(int[] nums) { Arrays.sort(nums); if (nums[0] + nums[1] <= nums[2]) { return "none"; } if (nums[0] == nums[2]) { return "equilateral"; } if (nums[0] == nums[1] || nums[1] == nums[2]) { return "isosceles"; } return "scalene"; } }
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
Python
class Solution: def triangleType(self, nums: List[int]) -> str: nums.sort() if nums[0] + nums[1] <= nums[2]: return "none" if nums[0] == nums[2]: return "equilateral" if nums[0] == nums[1] or nums[1] == nums[2]: return "isosceles" return "scalene"
3,024
Type of Triangle
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p> <ul> <li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li> <li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li> <li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li> </ul> <p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>&quot;none&quot;</code><em> if it <strong>cannot</strong> form a triangle.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3] <strong>Output:</strong> &quot;equilateral&quot; <strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5] <strong>Output:</strong> &quot;scalene&quot; <strong>Explanation:</strong> nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5. nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4. nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. As all the sides are of different lengths, it will form a scalene triangle. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums.length == 3</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Sorting
TypeScript
function triangleType(nums: number[]): string { nums.sort((a, b) => a - b); if (nums[0] + nums[1] <= nums[2]) { return 'none'; } if (nums[0] === nums[2]) { return 'equilateral'; } if (nums[0] === nums[1] || nums[1] === nums[2]) { return 'isosceles'; } return 'scalene'; }
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
C++
class Solution { public: int numberOfPairs(vector<vector<int>>& points) { sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]); }); int n = points.size(); int ans = 0; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = INT_MIN; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } };
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
C#
public class Solution { public int NumberOfPairs(int[][] points) { Array.Sort(points, (a, b) => a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); int ans = 0; int n = points.Length; int inf = 1 << 30; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = -inf; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } }
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Go
func numberOfPairs(points [][]int) (ans int) { sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] || points[i][0] == points[j][0] && points[j][1] < points[i][1] }) for i, p1 := range points { y1 := p1[1] maxY := math.MinInt32 for _, p2 := range points[i+1:] { y2 := p2[1] if maxY < y2 && y2 <= y1 { maxY = y2 ans++ } } } return }
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Java
class Solution { public int numberOfPairs(int[][] points) { Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); int ans = 0; int n = points.length; final int inf = 1 << 30; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = -inf; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } }
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Python
class Solution: def numberOfPairs(self, points: List[List[int]]) -> int: points.sort(key=lambda x: (x[0], -x[1])) ans = 0 for i, (_, y1) in enumerate(points): max_y = -inf for _, y2 in points[i + 1 :]: if max_y < y2 <= y1: max_y = y2 ans += 1 return ans
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Rust
impl Solution { pub fn number_of_pairs(mut points: Vec<Vec<i32>>) -> i32 { points.sort_by(|a, b| { if a[0] == b[0] { b[1].cmp(&a[1]) } else { a[0].cmp(&b[0]) } }); let n = points.len(); let mut ans = 0; for i in 0..n { let y1 = points[i][1]; let mut max_y = i32::MIN; for j in (i + 1)..n { let y2 = points[j][1]; if max_y < y2 && y2 <= y1 { max_y = y2; ans += 1; } } } ans } }
3,025
Find the Number of Ways to Place People I
Medium
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>Count the number of pairs of points <code>(A, B)</code>, where</p> <ul> <li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li> <li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>), except for the points <code>A</code> and <code>B</code>.</li> </ul> <p>Return the count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p> <p>There is no way to choose <code>A</code> and <code>B</code> such that&nbsp;<code>A</code> is on the upper left side of <code>B</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p> <ul> <li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li> <li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li> <li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it&#39;s not a valid pair.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p> <ul> <li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li> <li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li> <li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 50</code></li> <li><code>points[i].length == 2</code></li> <li><code>0 &lt;= points[i][0], points[i][1] &lt;= 50</code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
TypeScript
function numberOfPairs(points: number[][]): number { points.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const n = points.length; let ans = 0; for (let i = 0; i < n; ++i) { const [_, y1] = points[i]; let maxY = -Infinity; for (let j = i + 1; j < n; ++j) { const [_, y2] = points[j]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; }
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: long long maximumSubarraySum(vector<int>& nums, int k) { unordered_map<int, long long> p; p[nums[0]] = 0; long long s = 0; const int n = nums.size(); long long ans = LONG_LONG_MIN; for (int i = 0;; ++i) { s += nums[i]; auto it = p.find(nums[i] - k); if (it != p.end()) { ans = max(ans, s - it->second); } it = p.find(nums[i] + k); if (it != p.end()) { ans = max(ans, s - it->second); } if (i + 1 == n) { break; } it = p.find(nums[i + 1]); if (it == p.end() || it->second > s) { p[nums[i + 1]] = s; } } return ans == LONG_LONG_MIN ? 0 : ans; } };
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
C#
public class Solution { public long MaximumSubarraySum(int[] nums, int k) { Dictionary<int, long> p = new Dictionary<int, long>(); p[nums[0]] = 0L; long s = 0; int n = nums.Length; long ans = long.MinValue; for (int i = 0; i < n; ++i) { s += nums[i]; if (p.ContainsKey(nums[i] - k)) { ans = Math.Max(ans, s - p[nums[i] - k]); } if (p.ContainsKey(nums[i] + k)) { ans = Math.Max(ans, s - p[nums[i] + k]); } if (i + 1 < n && (!p.ContainsKey(nums[i + 1]) || p[nums[i + 1]] > s)) { p[nums[i + 1]] = s; } } return ans == long.MinValue ? 0 : ans; } }
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Go
func maximumSubarraySum(nums []int, k int) int64 { p := map[int]int64{nums[0]: 0} var s int64 = 0 n := len(nums) var ans int64 = math.MinInt64 for i, x := range nums { s += int64(x) if t, ok := p[nums[i]-k]; ok { ans = max(ans, s-t) } if t, ok := p[nums[i]+k]; ok { ans = max(ans, s-t) } if i+1 == n { break } if t, ok := p[nums[i+1]]; !ok || s < t { p[nums[i+1]] = s } } if ans == math.MinInt64 { return 0 } return ans }
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public long maximumSubarraySum(int[] nums, int k) { Map<Integer, Long> p = new HashMap<>(); p.put(nums[0], 0L); long s = 0; int n = nums.length; long ans = Long.MIN_VALUE; for (int i = 0; i < n; ++i) { s += nums[i]; if (p.containsKey(nums[i] - k)) { ans = Math.max(ans, s - p.get(nums[i] - k)); } if (p.containsKey(nums[i] + k)) { ans = Math.max(ans, s - p.get(nums[i] + k)); } if (i + 1 < n && (!p.containsKey(nums[i + 1]) || p.get(nums[i + 1]) > s)) { p.put(nums[i + 1], s); } } return ans == Long.MIN_VALUE ? 0 : ans; } }
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def maximumSubarraySum(self, nums: List[int], k: int) -> int: ans = -inf p = {nums[0]: 0} s, n = 0, len(nums) for i, x in enumerate(nums): s += x if x - k in p: ans = max(ans, s - p[x - k]) if x + k in p: ans = max(ans, s - p[x + k]) if i + 1 < n and (nums[i + 1] not in p or p[nums[i + 1]] > s): p[nums[i + 1]] = s return 0 if ans == -inf else ans
3,026
Maximum Good Subarray Sum
Medium
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p> <p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,4,5], k = 3 <strong>Output:</strong> 11 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2 <strong>Output:</strong> -6 <strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3]. </pre> <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>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum
TypeScript
function maximumSubarraySum(nums: number[], k: number): number { const p: Map<number, number> = new Map(); p.set(nums[0], 0); let ans: number = -Infinity; let s: number = 0; const n: number = nums.length; for (let i = 0; i < n; ++i) { s += nums[i]; if (p.has(nums[i] - k)) { ans = Math.max(ans, s - p.get(nums[i] - k)!); } if (p.has(nums[i] + k)) { ans = Math.max(ans, s - p.get(nums[i] + k)!); } if (i + 1 < n && (!p.has(nums[i + 1]) || p.get(nums[i + 1])! > s)) { p.set(nums[i + 1], s); } } return ans === -Infinity ? 0 : ans; }
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
C++
class Solution { public: int numberOfPairs(vector<vector<int>>& points) { sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]); }); int n = points.size(); int ans = 0; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = INT_MIN; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } };
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
C#
public class Solution { public int NumberOfPairs(int[][] points) { Array.Sort(points, (a, b) => a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); int ans = 0; int n = points.Length; int inf = 1 << 30; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = -inf; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } }
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Go
func numberOfPairs(points [][]int) (ans int) { sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] || points[i][0] == points[j][0] && points[j][1] < points[i][1] }) for i, p1 := range points { y1 := p1[1] maxY := math.MinInt32 for _, p2 := range points[i+1:] { y2 := p2[1] if maxY < y2 && y2 <= y1 { maxY = y2 ans++ } } } return }
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Java
class Solution { public int numberOfPairs(int[][] points) { Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); int ans = 0; int n = points.length; final int inf = 1 << 30; for (int i = 0; i < n; ++i) { int y1 = points[i][1]; int maxY = -inf; for (int j = i + 1; j < n; ++j) { int y2 = points[j][1]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; } }
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Python
class Solution: def numberOfPairs(self, points: List[List[int]]) -> int: points.sort(key=lambda x: (x[0], -x[1])) ans = 0 for i, (_, y1) in enumerate(points): max_y = -inf for _, y2 in points[i + 1 :]: if max_y < y2 <= y1: max_y = y2 ans += 1 return ans
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
Rust
impl Solution { pub fn number_of_pairs(mut points: Vec<Vec<i32>>) -> i32 { points.sort_by(|a, b| { if a[0] == b[0] { b[1].cmp(&a[1]) } else { a[0].cmp(&b[0]) } }); let n = points.len(); let mut ans = 0; for i in 0..n { let y1 = points[i][1]; let mut max_y = i32::MIN; for j in (i + 1)..n { let y2 = points[j][1]; if max_y < y2 && y2 <= y1 { max_y = y2; ans += 1; } } } ans } }
3,027
Find the Number of Ways to Place People II
Hard
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p> <p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice&#39;s position as the <strong>upper left corner</strong> and Bob&#39;s position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p> <p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p> <p><strong>Note</strong> that Alice can only build a fence with Alice&#39;s position as the upper left corner, and Bob&#39;s position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p> <ul> <li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice&#39;s position is not the upper left corner and Bob&#39;s position is not the lower right corner of the fence.</li> <li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>&nbsp;(as the rectangle shown in the image instead of a line),&nbsp;Bob&#39;s position is not the lower right corner of the fence.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice&#39;s position as the upper left corner and Bob&#39;s position as the lower right corner. Hence we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[6,2],[4,4],[2,6]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (4, 4) and Bob at (6, 2). - Place Alice at (2, 6) and Bob at (4, 4). You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <pre> <strong>Input:</strong> points = [[3,1],[1,3],[1,1]] <strong>Output:</strong> 2 <strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad: - Place Alice at (1, 1) and Bob at (3, 1). - Place Alice at (1, 3) and Bob at (1, 1). You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence. Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>9</sup> &lt;= points[i][0], points[i][1] &lt;= 10<sup>9</sup></code></li> <li>All <code>points[i]</code> are distinct.</li> </ul>
Geometry; Array; Math; Enumeration; Sorting
TypeScript
function numberOfPairs(points: number[][]): number { points.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const n = points.length; let ans = 0; for (let i = 0; i < n; ++i) { const [_, y1] = points[i]; let maxY = -Infinity; for (let j = i + 1; j < n; ++j) { const [_, y2] = points[j]; if (maxY < y2 && y2 <= y1) { maxY = y2; ++ans; } } } return ans; }
3,028
Ant on the Boundary
Easy
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p> <p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p> <ul> <li>If <code>nums[i] &lt; 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li> <li>If <code>nums[i] &gt; 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li> </ul> <p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p> <p><strong>Notes:</strong></p> <ul> <li>There is an infinite space on both sides of the boundary.</li> <li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,-5] <strong>Output:</strong> 1 <strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is on the boundary. So the answer is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,-3,-4] <strong>Output:</strong> 0 <strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. The ant never returned to the boundary, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li><code>nums[i] != 0</code></li> </ul>
Array; Prefix Sum; Simulation
C++
class Solution { public: int returnToBoundaryCount(vector<int>& nums) { int ans = 0, s = 0; for (int x : nums) { s += x; ans += s == 0; } return ans; } };
3,028
Ant on the Boundary
Easy
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p> <p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p> <ul> <li>If <code>nums[i] &lt; 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li> <li>If <code>nums[i] &gt; 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li> </ul> <p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p> <p><strong>Notes:</strong></p> <ul> <li>There is an infinite space on both sides of the boundary.</li> <li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,-5] <strong>Output:</strong> 1 <strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is on the boundary. So the answer is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,-3,-4] <strong>Output:</strong> 0 <strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. The ant never returned to the boundary, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li><code>nums[i] != 0</code></li> </ul>
Array; Prefix Sum; Simulation
Go
func returnToBoundaryCount(nums []int) (ans int) { s := 0 for _, x := range nums { s += x if s == 0 { ans++ } } return }