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
2,962
Count Subarrays Where Max Element Appears at Least K Times
Medium
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p> <p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,3,3], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,2,1], k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> No subarray contains the element 4 at least 3 times. </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>6</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Sliding Window
TypeScript
function countSubarrays(nums: number[], k: number): number { const mx = Math.max(...nums); const n = nums.length; let [cnt, j] = [0, 0]; let ans = 0; for (const x of nums) { for (; j < n && cnt < k; ++j) { cnt += nums[j] === mx ? 1 : 0; } if (cnt < k) { break; } ans += n - j + 1; cnt -= x === mx ? 1 : 0; } return ans; }
2,963
Count the Number of Good Partitions
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers.</p> <p>A partition of an array into one or more <strong>contiguous</strong> subarrays is called <strong>good</strong> if no two subarrays contain the same number.</p> <p>Return <em>the <strong>total number</strong> of good partitions of </em><code>nums</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The only possible good partition is: ([1,1,1,1]). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]). </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>
Array; Hash Table; Math; Combinatorics
C++
class Solution { public: int numberOfGoodPartitions(vector<int>& nums) { unordered_map<int, int> last; int n = nums.size(); for (int i = 0; i < n; ++i) { last[nums[i]] = i; } const int mod = 1e9 + 7; int j = -1, k = 0; for (int i = 0; i < n; ++i) { j = max(j, last[nums[i]]); k += i == j; } auto qpow = [&](long long a, int n, int mod) { long long ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; }; return qpow(2, k - 1, mod); } };
2,963
Count the Number of Good Partitions
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers.</p> <p>A partition of an array into one or more <strong>contiguous</strong> subarrays is called <strong>good</strong> if no two subarrays contain the same number.</p> <p>Return <em>the <strong>total number</strong> of good partitions of </em><code>nums</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The only possible good partition is: ([1,1,1,1]). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]). </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>
Array; Hash Table; Math; Combinatorics
Go
func numberOfGoodPartitions(nums []int) int { qpow := func(a, n, mod int) int { ans := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { ans = ans * a % mod } a = a * a % mod } return ans } last := map[int]int{} for i, x := range nums { last[x] = i } const mod int = 1e9 + 7 j, k := -1, 0 for i, x := range nums { j = max(j, last[x]) if i == j { k++ } } return qpow(2, k-1, mod) }
2,963
Count the Number of Good Partitions
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers.</p> <p>A partition of an array into one or more <strong>contiguous</strong> subarrays is called <strong>good</strong> if no two subarrays contain the same number.</p> <p>Return <em>the <strong>total number</strong> of good partitions of </em><code>nums</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The only possible good partition is: ([1,1,1,1]). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]). </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>
Array; Hash Table; Math; Combinatorics
Java
class Solution { public int numberOfGoodPartitions(int[] nums) { Map<Integer, Integer> last = new HashMap<>(); int n = nums.length; for (int i = 0; i < n; ++i) { last.put(nums[i], i); } final int mod = (int) 1e9 + 7; int j = -1; int k = 0; for (int i = 0; i < n; ++i) { j = Math.max(j, last.get(nums[i])); k += i == j ? 1 : 0; } return qpow(2, k - 1, mod); } private int qpow(long a, int n, int mod) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; } }
2,963
Count the Number of Good Partitions
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers.</p> <p>A partition of an array into one or more <strong>contiguous</strong> subarrays is called <strong>good</strong> if no two subarrays contain the same number.</p> <p>Return <em>the <strong>total number</strong> of good partitions of </em><code>nums</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The only possible good partition is: ([1,1,1,1]). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]). </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>
Array; Hash Table; Math; Combinatorics
Python
class Solution: def numberOfGoodPartitions(self, nums: List[int]) -> int: last = {x: i for i, x in enumerate(nums)} mod = 10**9 + 7 j, k = -1, 0 for i, x in enumerate(nums): j = max(j, last[x]) k += i == j return pow(2, k - 1, mod)
2,963
Count the Number of Good Partitions
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers.</p> <p>A partition of an array into one or more <strong>contiguous</strong> subarrays is called <strong>good</strong> if no two subarrays contain the same number.</p> <p>Return <em>the <strong>total number</strong> of good partitions of </em><code>nums</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 8 <strong>Explanation:</strong> The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> The only possible good partition is: ([1,1,1,1]). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]). </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>
Array; Hash Table; Math; Combinatorics
TypeScript
function numberOfGoodPartitions(nums: number[]): number { const qpow = (a: number, n: number, mod: number) => { let ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = Number((BigInt(ans) * BigInt(a)) % BigInt(mod)); } a = Number((BigInt(a) * BigInt(a)) % BigInt(mod)); } return ans; }; const last: Map<number, number> = new Map(); const n = nums.length; for (let i = 0; i < n; ++i) { last.set(nums[i], i); } const mod = 1e9 + 7; let [j, k] = [-1, 0]; for (let i = 0; i < n; ++i) { j = Math.max(j, last.get(nums[i])!); if (i === j) { ++k; } } return qpow(2, k - 1, mod); }
2,964
Number of Divisible Triplet Sums
Medium
Given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>d</code>, return <em>the number of triplets</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>(nums[i] + nums[j] + nums[k]) % d == 0</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,4,7,8], d = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4). It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 6 <strong>Output:</strong> 0 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
C++
class Solution { public: int divisibleTripletCount(vector<int>& nums, int d) { unordered_map<int, int> cnt; int ans = 0, n = nums.size(); for (int j = 0; j < n; ++j) { for (int k = j + 1; k < n; ++k) { int x = (d - (nums[j] + nums[k]) % d) % d; ans += cnt[x]; } cnt[nums[j] % d]++; } return ans; } };
2,964
Number of Divisible Triplet Sums
Medium
Given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>d</code>, return <em>the number of triplets</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>(nums[i] + nums[j] + nums[k]) % d == 0</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,4,7,8], d = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4). It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 6 <strong>Output:</strong> 0 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Go
func divisibleTripletCount(nums []int, d int) (ans int) { n := len(nums) cnt := map[int]int{} for j := 0; j < n; j++ { for k := j + 1; k < n; k++ { x := (d - (nums[j]+nums[k])%d) % d ans += cnt[x] } cnt[nums[j]%d]++ } return }
2,964
Number of Divisible Triplet Sums
Medium
Given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>d</code>, return <em>the number of triplets</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>(nums[i] + nums[j] + nums[k]) % d == 0</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,4,7,8], d = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4). It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 6 <strong>Output:</strong> 0 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Java
class Solution { public int divisibleTripletCount(int[] nums, int d) { Map<Integer, Integer> cnt = new HashMap<>(); int ans = 0, n = nums.length; for (int j = 0; j < n; ++j) { for (int k = j + 1; k < n; ++k) { int x = (d - (nums[j] + nums[k]) % d) % d; ans += cnt.getOrDefault(x, 0); } cnt.merge(nums[j] % d, 1, Integer::sum); } return ans; } }
2,964
Number of Divisible Triplet Sums
Medium
Given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>d</code>, return <em>the number of triplets</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>(nums[i] + nums[j] + nums[k]) % d == 0</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,4,7,8], d = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4). It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 6 <strong>Output:</strong> 0 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Python
class Solution: def divisibleTripletCount(self, nums: List[int], d: int) -> int: cnt = defaultdict(int) ans, n = 0, len(nums) for j in range(n): for k in range(j + 1, n): x = (d - (nums[j] + nums[k]) % d) % d ans += cnt[x] cnt[nums[j] % d] += 1 return ans
2,964
Number of Divisible Triplet Sums
Medium
Given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>d</code>, return <em>the number of triplets</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>(nums[i] + nums[j] + nums[k]) % d == 0</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,4,7,8], d = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The triplets which are divisible by 5 are: (0, 1, 2), (0, 2, 4), (1, 2, 4). It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is divisible by 3. Hence, the answer is the total number of triplets which is 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], d = 6 <strong>Output:</strong> 0 <strong>Explanation:</strong> Any triplet chosen here has a sum of 9, which is not divisible by 6. Hence, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
TypeScript
function divisibleTripletCount(nums: number[], d: number): number { const n = nums.length; const cnt: Map<number, number> = new Map(); let ans = 0; for (let j = 0; j < n; ++j) { for (let k = j + 1; k < n; ++k) { const x = (d - ((nums[j] + nums[k]) % d)) % d; ans += cnt.get(x) || 0; } cnt.set(nums[j] % d, (cnt.get(nums[j] % d) || 0) + 1); } return ans; }
2,965
Find Missing and Repeated Values
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code> of size <code>n * n</code> with values in the range <code>[1, n<sup>2</sup>]</code>. Each integer appears <strong>exactly once</strong> except <code>a</code> which appears <strong>twice</strong> and <code>b</code> which is <strong>missing</strong>. The task is to find the repeating and missing numbers <code>a</code> and <code>b</code>.</p> <p>Return <em>a <strong>0-indexed </strong>integer array </em><code>ans</code><em> of size </em><code>2</code><em> where </em><code>ans[0]</code><em> equals to </em><code>a</code><em> and </em><code>ans[1]</code><em> equals to </em><code>b</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1,3],[2,2]] <strong>Output:</strong> [2,4] <strong>Explanation:</strong> Number 2 is repeated and number 4 is missing so the answer is [2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[9,1,7],[8,9,2],[3,4,6]] <strong>Output:</strong> [9,5] <strong>Explanation:</strong> Number 9 is repeated and number 5 is missing so the answer is [9,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= n * n</code></li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is not equal to any of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is equal to exactly two of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> except two of them there is exactly one pair of <code>i, j</code> that <code>0 &lt;= i, j &lt;= n - 1</code> and <code>grid[i][j] == x</code>.</li> </ul>
Array; Hash Table; Math; Matrix
C++
class Solution { public: vector<int> findMissingAndRepeatedValues(vector<vector<int>>& grid) { int n = grid.size(); vector<int> cnt(n * n + 1); vector<int> ans(2); for (auto& row : grid) { for (int x : row) { if (++cnt[x] == 2) { ans[0] = x; } } } for (int x = 1;; ++x) { if (cnt[x] == 0) { ans[1] = x; return ans; } } } };
2,965
Find Missing and Repeated Values
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code> of size <code>n * n</code> with values in the range <code>[1, n<sup>2</sup>]</code>. Each integer appears <strong>exactly once</strong> except <code>a</code> which appears <strong>twice</strong> and <code>b</code> which is <strong>missing</strong>. The task is to find the repeating and missing numbers <code>a</code> and <code>b</code>.</p> <p>Return <em>a <strong>0-indexed </strong>integer array </em><code>ans</code><em> of size </em><code>2</code><em> where </em><code>ans[0]</code><em> equals to </em><code>a</code><em> and </em><code>ans[1]</code><em> equals to </em><code>b</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1,3],[2,2]] <strong>Output:</strong> [2,4] <strong>Explanation:</strong> Number 2 is repeated and number 4 is missing so the answer is [2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[9,1,7],[8,9,2],[3,4,6]] <strong>Output:</strong> [9,5] <strong>Explanation:</strong> Number 9 is repeated and number 5 is missing so the answer is [9,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= n * n</code></li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is not equal to any of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is equal to exactly two of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> except two of them there is exactly one pair of <code>i, j</code> that <code>0 &lt;= i, j &lt;= n - 1</code> and <code>grid[i][j] == x</code>.</li> </ul>
Array; Hash Table; Math; Matrix
Go
func findMissingAndRepeatedValues(grid [][]int) []int { n := len(grid) ans := make([]int, 2) cnt := make([]int, n*n+1) for _, row := range grid { for _, x := range row { cnt[x]++ if cnt[x] == 2 { ans[0] = x } } } for x := 1; ; x++ { if cnt[x] == 0 { ans[1] = x return ans } } }
2,965
Find Missing and Repeated Values
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code> of size <code>n * n</code> with values in the range <code>[1, n<sup>2</sup>]</code>. Each integer appears <strong>exactly once</strong> except <code>a</code> which appears <strong>twice</strong> and <code>b</code> which is <strong>missing</strong>. The task is to find the repeating and missing numbers <code>a</code> and <code>b</code>.</p> <p>Return <em>a <strong>0-indexed </strong>integer array </em><code>ans</code><em> of size </em><code>2</code><em> where </em><code>ans[0]</code><em> equals to </em><code>a</code><em> and </em><code>ans[1]</code><em> equals to </em><code>b</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1,3],[2,2]] <strong>Output:</strong> [2,4] <strong>Explanation:</strong> Number 2 is repeated and number 4 is missing so the answer is [2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[9,1,7],[8,9,2],[3,4,6]] <strong>Output:</strong> [9,5] <strong>Explanation:</strong> Number 9 is repeated and number 5 is missing so the answer is [9,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= n * n</code></li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is not equal to any of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is equal to exactly two of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> except two of them there is exactly one pair of <code>i, j</code> that <code>0 &lt;= i, j &lt;= n - 1</code> and <code>grid[i][j] == x</code>.</li> </ul>
Array; Hash Table; Math; Matrix
Java
class Solution { public int[] findMissingAndRepeatedValues(int[][] grid) { int n = grid.length; int[] cnt = new int[n * n + 1]; int[] ans = new int[2]; for (int[] row : grid) { for (int x : row) { if (++cnt[x] == 2) { ans[0] = x; } } } for (int x = 1;; ++x) { if (cnt[x] == 0) { ans[1] = x; return ans; } } } }
2,965
Find Missing and Repeated Values
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code> of size <code>n * n</code> with values in the range <code>[1, n<sup>2</sup>]</code>. Each integer appears <strong>exactly once</strong> except <code>a</code> which appears <strong>twice</strong> and <code>b</code> which is <strong>missing</strong>. The task is to find the repeating and missing numbers <code>a</code> and <code>b</code>.</p> <p>Return <em>a <strong>0-indexed </strong>integer array </em><code>ans</code><em> of size </em><code>2</code><em> where </em><code>ans[0]</code><em> equals to </em><code>a</code><em> and </em><code>ans[1]</code><em> equals to </em><code>b</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1,3],[2,2]] <strong>Output:</strong> [2,4] <strong>Explanation:</strong> Number 2 is repeated and number 4 is missing so the answer is [2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[9,1,7],[8,9,2],[3,4,6]] <strong>Output:</strong> [9,5] <strong>Explanation:</strong> Number 9 is repeated and number 5 is missing so the answer is [9,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= n * n</code></li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is not equal to any of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is equal to exactly two of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> except two of them there is exactly one pair of <code>i, j</code> that <code>0 &lt;= i, j &lt;= n - 1</code> and <code>grid[i][j] == x</code>.</li> </ul>
Array; Hash Table; Math; Matrix
Python
class Solution: def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: n = len(grid) cnt = [0] * (n * n + 1) for row in grid: for v in row: cnt[v] += 1 ans = [0] * 2 for i in range(1, n * n + 1): if cnt[i] == 2: ans[0] = i if cnt[i] == 0: ans[1] = i return ans
2,965
Find Missing and Repeated Values
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code> of size <code>n * n</code> with values in the range <code>[1, n<sup>2</sup>]</code>. Each integer appears <strong>exactly once</strong> except <code>a</code> which appears <strong>twice</strong> and <code>b</code> which is <strong>missing</strong>. The task is to find the repeating and missing numbers <code>a</code> and <code>b</code>.</p> <p>Return <em>a <strong>0-indexed </strong>integer array </em><code>ans</code><em> of size </em><code>2</code><em> where </em><code>ans[0]</code><em> equals to </em><code>a</code><em> and </em><code>ans[1]</code><em> equals to </em><code>b</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> grid = [[1,3],[2,2]] <strong>Output:</strong> [2,4] <strong>Explanation:</strong> Number 2 is repeated and number 4 is missing so the answer is [2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[9,1,7],[8,9,2],[3,4,6]] <strong>Output:</strong> [9,5] <strong>Explanation:</strong> Number 9 is repeated and number 5 is missing so the answer is [9,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= n * n</code></li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is not equal to any of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> there is exactly one <code>x</code> that is equal to exactly two of the grid members.</li> <li>For all <code>x</code> that <code>1 &lt;= x &lt;= n * n</code> except two of them there is exactly one pair of <code>i, j</code> that <code>0 &lt;= i, j &lt;= n - 1</code> and <code>grid[i][j] == x</code>.</li> </ul>
Array; Hash Table; Math; Matrix
TypeScript
function findMissingAndRepeatedValues(grid: number[][]): number[] { const n = grid.length; const cnt: number[] = Array(n * n + 1).fill(0); const ans: number[] = Array(2).fill(0); for (const row of grid) { for (const x of row) { if (++cnt[x] === 2) { ans[0] = x; } } } for (let x = 1; ; ++x) { if (cnt[x] === 0) { ans[1] = x; return ans; } } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: vector<vector<int>> divideArray(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); vector<vector<int>> ans; int n = nums.size(); for (int i = 0; i < n; i += 3) { vector<int> t = {nums[i], nums[i + 1], nums[i + 2]}; if (t[2] - t[0] > k) { return {}; } ans.emplace_back(t); } return ans; } };
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
C#
public class Solution { public int[][] DivideArray(int[] nums, int k) { Array.Sort(nums); List<int[]> ans = new List<int[]>(); for (int i = 0; i < nums.Length; i += 3) { if (i + 2 >= nums.Length) { return new int[0][]; } int[] t = new int[] { nums[i], nums[i + 1], nums[i + 2] }; if (t[2] - t[0] > k) { return new int[0][]; } ans.Add(t); } return ans.ToArray(); } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Dart
class Solution { List<List<int>> divideArray(List<int> nums, int k) { nums.sort(); List<List<int>> ans = []; for (int i = 0; i < nums.length; i += 3) { if (i + 2 >= nums.length) { return []; } List<int> t = nums.sublist(i, i + 3); if (t[2] - t[0] > k) { return []; } ans.add(t); } return ans; } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func divideArray(nums []int, k int) [][]int { sort.Ints(nums) ans := [][]int{} for i := 0; i < len(nums); i += 3 { t := slices.Clone(nums[i : i+3]) if t[2]-t[0] > k { return [][]int{} } ans = append(ans, t) } return ans }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int[][] divideArray(int[] nums, int k) { Arrays.sort(nums); int n = nums.length; int[][] ans = new int[n / 3][]; for (int i = 0; i < n; i += 3) { int[] t = Arrays.copyOfRange(nums, i, i + 3); if (t[2] - t[0] > k) { return new int[][] {}; } ans[i / 3] = t; } return ans; } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def divideArray(self, nums: List[int], k: int) -> List[List[int]]: nums.sort() ans = [] n = len(nums) for i in range(0, n, 3): t = nums[i : i + 3] if t[2] - t[0] > k: return [] ans.append(t) return ans
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Rust
impl Solution { pub fn divide_array(mut nums: Vec<i32>, k: i32) -> Vec<Vec<i32>> { nums.sort(); let mut ans = Vec::new(); let n = nums.len(); for i in (0..n).step_by(3) { if i + 2 >= n { return vec![]; } let t = &nums[i..i + 3]; if t[2] - t[0] > k { return vec![]; } ans.push(t.to_vec()); } ans } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
Swift
class Solution { func divideArray(_ nums: [Int], _ k: Int) -> [[Int]] { var sortedNums = nums.sorted() var ans: [[Int]] = [] for i in stride(from: 0, to: sortedNums.count, by: 3) { if i + 2 >= sortedNums.count { return [] } let t = Array(sortedNums[i..<i+3]) if t[2] - t[0] > k { return [] } ans.append(t) } return ans } }
2,966
Divide Array Into Arrays With Max Difference
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is a multiple of 3 and a positive integer <code>k</code>.</p> <p>Divide the array <code>nums</code> into <code>n / 3</code> arrays of size <strong>3</strong> satisfying the following condition:</p> <ul> <li>The difference between <strong>any</strong> two elements in one array is <strong>less than or equal</strong> to <code>k</code>.</li> </ul> <p>Return a <strong>2D</strong> array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return <strong>any</strong> of them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,4,8,7,9,3,5,1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,1,3],[3,4,5],[7,8,9]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,2,2,5,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>Different ways to divide <code>nums</code> into 2 arrays of size 3 are:</p> <ul> <li>[[2,2,2],[2,4,5]] (and its permutations)</li> <li>[[2,2,4],[2,2,5]] (and its permutations)</li> </ul> <p>Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since <code>5 - 2 = 3 &gt; k</code>, the condition is not satisfied and so there is no valid division.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14</span></p> <p><strong>Output:</strong> <span class="example-io">[[2,2,2],[4,5,5],[5,5,7],[7,8,8],[9,9,10],[11,12,12]]</span></p> <p><strong>Explanation:</strong></p> <p>The difference between any two elements in each array is less than or equal to 14.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n </code>is a multiple of 3</li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function divideArray(nums: number[], k: number): number[][] { nums.sort((a, b) => a - b); const ans: number[][] = []; for (let i = 0; i < nums.length; i += 3) { const t = nums.slice(i, i + 3); if (t[2] - t[0] > k) { return []; } ans.push(t); } return ans; }
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
C++
using ll = long long; ll ps[2 * 100000]; int init = [] { for (int i = 1; i <= 100000; i++) { string s = to_string(i); string t1 = s; reverse(t1.begin(), t1.end()); string t2 = s.substr(0, s.length() - 1); reverse(t2.begin(), t2.end()); ps[2 * i - 2] = stoll(s + t1); ps[2 * i - 1] = stoll(s + t2); } sort(ps, ps + 2 * 100000); return 0; }(); class Solution { public: long long minimumCost(vector<int>& nums) { sort(nums.begin(), nums.end()); int i = lower_bound(ps, ps + 2 * 100000, nums[nums.size() / 2]) - ps; auto f = [&](ll x) { ll ans = 0; for (int& v : nums) { ans += abs(v - x); } return ans; }; ll ans = LLONG_MAX; for (int j = i - 1; j <= i + 1; j++) { if (0 <= j && j < 2 * 100000) { ans = min(ans, f(ps[j])); } } return ans; } };
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
Go
var ps [2 * 100000]int64 func init() { for i := 1; i <= 100000; i++ { s := strconv.Itoa(i) t1 := reverseString(s) t2 := reverseString(s[:len(s)-1]) ps[2*i-2], _ = strconv.ParseInt(s+t1, 10, 64) ps[2*i-1], _ = strconv.ParseInt(s+t2, 10, 64) } sort.Slice(ps[:], func(i, j int) bool { return ps[i] < ps[j] }) } func reverseString(s string) string { cs := []rune(s) for i, j := 0, len(cs)-1; i < j; i, j = i+1, j-1 { cs[i], cs[j] = cs[j], cs[i] } return string(cs) } func minimumCost(nums []int) int64 { sort.Ints(nums) i := sort.Search(len(ps), func(i int) bool { return ps[i] >= int64(nums[len(nums)/2]) }) f := func(x int64) int64 { var ans int64 for _, v := range nums { ans += int64(abs(int(x - int64(v)))) } return ans } ans := int64(math.MaxInt64) for j := i - 1; j <= i+1; j++ { if 0 <= j && j < len(ps) { ans = min(ans, f(ps[j])) } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
Java
public class Solution { private static long[] ps; private int[] nums; static { ps = new long[2 * (int) 1e5]; for (int i = 1; i <= 1e5; i++) { String s = Integer.toString(i); String t1 = new StringBuilder(s).reverse().toString(); String t2 = new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString(); ps[2 * i - 2] = Long.parseLong(s + t1); ps[2 * i - 1] = Long.parseLong(s + t2); } Arrays.sort(ps); } public long minimumCost(int[] nums) { this.nums = nums; Arrays.sort(nums); int i = Arrays.binarySearch(ps, nums[nums.length / 2]); i = i < 0 ? -i - 1 : i; long ans = 1L << 60; for (int j = i - 1; j <= i + 1; j++) { if (0 <= j && j < ps.length) { ans = Math.min(ans, f(ps[j])); } } return ans; } private long f(long x) { long ans = 0; for (int v : nums) { ans += Math.abs(v - x); } return ans; } }
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
Python
ps = [] for i in range(1, 10**5 + 1): s = str(i) t1 = s[::-1] t2 = s[:-1][::-1] ps.append(int(s + t1)) ps.append(int(s + t2)) ps.sort() class Solution: def minimumCost(self, nums: List[int]) -> int: def f(x: int) -> int: return sum(abs(v - x) for v in nums) nums.sort() i = bisect_left(ps, nums[len(nums) // 2]) return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps))
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
Rust
impl Solution { pub fn minimum_cost(nums: Vec<i32>) -> i64 { use std::cmp::min; use std::sync::Once; static INIT: Once = Once::new(); static mut PS: Vec<i64> = Vec::new(); INIT.call_once(|| { let mut ps_local = Vec::with_capacity(2 * 100_000); for i in 1..=100_000 { let s = i.to_string(); let mut t1 = s.clone(); t1 = t1.chars().rev().collect(); ps_local.push(format!("{}{}", s, t1).parse::<i64>().unwrap()); let mut t2 = s[0..s.len() - 1].to_string(); t2 = t2.chars().rev().collect(); ps_local.push(format!("{}{}", s, t2).parse::<i64>().unwrap()); } ps_local.sort(); unsafe { PS = ps_local; } }); let mut nums = nums; nums.sort(); let mid = nums[nums.len() / 2] as i64; let i = unsafe { match PS.binary_search(&mid) { Ok(i) => i, Err(i) => i, } }; let f = |x: i64| -> i64 { nums.iter().map(|&v| (v as i64 - x).abs()).sum() }; let mut ans = i64::MAX; for j in i.saturating_sub(1)..=(i + 1).min(2 * 100_000 - 1) { let x = unsafe { PS[j] }; ans = min(ans, f(x)); } ans } }
2,967
Minimum Cost to Make Array Equalindromic
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>.</p> <p>You are allowed to perform a special move <strong>any</strong> number of times (<strong>including zero</strong>) on <code>nums</code>. In one <strong>special</strong> <strong>move</strong> you perform the following steps <strong>in order</strong>:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and a <strong>positive</strong> integer <code>x</code>.</li> <li>Add <code>|nums[i] - x|</code> to the total cost.</li> <li>Change the value of <code>nums[i]</code> to <code>x</code>.</li> </ul> <p>A <strong>palindromic number</strong> is a positive integer that remains the same when its digits are reversed. For example, <code>121</code>, <code>2552</code> and <code>65756</code> are palindromic numbers whereas <code>24</code>, <code>46</code>, <code>235</code> are not palindromic numbers.</p> <p>An array is considered <strong>equalindromic</strong> if all the elements in the array are equal to an integer <code>y</code>, where <code>y</code> is a <strong>palindromic number</strong> less than <code>10<sup>9</sup></code>.</p> <p>Return <em>an integer denoting the <strong>minimum</strong> possible total cost to make </em><code>nums</code><em> <strong>equalindromic</strong> by performing any number of special moves.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6. It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10,12,13,14,15] <strong>Output:</strong> 11 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [22,33,22,33,22] <strong>Output:</strong> 22 <strong>Explanation:</strong> We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Sorting
TypeScript
const ps = Array(2e5).fill(0); const init = (() => { for (let i = 1; i <= 1e5; ++i) { const s: string = i.toString(); const t1: string = s.split('').reverse().join(''); const t2: string = s.slice(0, -1).split('').reverse().join(''); ps[2 * i - 2] = parseInt(s + t1, 10); ps[2 * i - 1] = parseInt(s + t2, 10); } ps.sort((a, b) => a - b); })(); function minimumCost(nums: number[]): number { const search = (x: number): number => { let [l, r] = [0, ps.length]; while (l < r) { const mid = (l + r) >> 1; if (ps[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; const f = (x: number): number => { return nums.reduce((acc, v) => acc + Math.abs(v - x), 0); }; nums.sort((a, b) => a - b); const i: number = search(nums[nums.length >> 1]); let ans: number = Number.MAX_SAFE_INTEGER; for (let j = i - 1; j <= i + 1; j++) { if (j >= 0 && j < ps.length) { ans = Math.min(ans, f(ps[j])); } } return ans; }
2,968
Apply Operations to Maximize Frequency Score
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You can perform the following operation on the array <strong>at most</strong> <code>k</code> times:</p> <ul> <li>Choose any index <code>i</code> from the array and <strong>increase</strong> or <strong>decrease</strong> <code>nums[i]</code> by <code>1</code>.</li> </ul> <p>The score of the final array is the <strong>frequency</strong> of the most frequent element in the array.</p> <p>Return <em>the <strong>maximum</strong> score you can achieve</em>.</p> <p>The frequency of an element is the number of occurences of that element in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,6,4], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2]. The element 2 is the most frequent in the final array so our score is 3. It can be shown that we cannot achieve a better score. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,2,4], k = 0 <strong>Output:</strong> 3 <strong>Explanation:</strong> We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3. </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> <li><code>0 &lt;= k &lt;= 10<sup>14</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
C++
class Solution { public: int maxFrequencyScore(vector<int>& nums, long long k) { sort(nums.begin(), nums.end()); int n = nums.size(); vector<long long> s(n + 1, 0); for (int i = 1; i <= n; i++) { s[i] = s[i - 1] + nums[i - 1]; } int l = 0, r = n; while (l < r) { int mid = (l + r + 1) >> 1; bool ok = false; for (int i = 0; i <= n - mid; i++) { int j = i + mid; int x = nums[(i + j) / 2]; long long left = ((i + j) / 2 - i) * (long long) x - (s[(i + j) / 2] - s[i]); long long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long long) x); if (left + right <= k) { ok = true; break; } } if (ok) { l = mid; } else { r = mid - 1; } } return l; } };
2,968
Apply Operations to Maximize Frequency Score
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You can perform the following operation on the array <strong>at most</strong> <code>k</code> times:</p> <ul> <li>Choose any index <code>i</code> from the array and <strong>increase</strong> or <strong>decrease</strong> <code>nums[i]</code> by <code>1</code>.</li> </ul> <p>The score of the final array is the <strong>frequency</strong> of the most frequent element in the array.</p> <p>Return <em>the <strong>maximum</strong> score you can achieve</em>.</p> <p>The frequency of an element is the number of occurences of that element in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,6,4], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2]. The element 2 is the most frequent in the final array so our score is 3. It can be shown that we cannot achieve a better score. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,2,4], k = 0 <strong>Output:</strong> 3 <strong>Explanation:</strong> We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3. </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> <li><code>0 &lt;= k &lt;= 10<sup>14</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Go
func maxFrequencyScore(nums []int, k int64) int { sort.Ints(nums) n := len(nums) s := make([]int64, n+1) for i := 1; i <= n; i++ { s[i] = s[i-1] + int64(nums[i-1]) } l, r := 0, n for l < r { mid := (l + r + 1) >> 1 ok := false for i := 0; i <= n-mid; i++ { j := i + mid x := int64(nums[(i+j)/2]) left := (int64((i+j)/2-i) * x) - (s[(i+j)/2] - s[i]) right := (s[j] - s[(i+j)/2]) - (int64(j-(i+j)/2) * x) if left+right <= k { ok = true break } } if ok { l = mid } else { r = mid - 1 } } return l }
2,968
Apply Operations to Maximize Frequency Score
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You can perform the following operation on the array <strong>at most</strong> <code>k</code> times:</p> <ul> <li>Choose any index <code>i</code> from the array and <strong>increase</strong> or <strong>decrease</strong> <code>nums[i]</code> by <code>1</code>.</li> </ul> <p>The score of the final array is the <strong>frequency</strong> of the most frequent element in the array.</p> <p>Return <em>the <strong>maximum</strong> score you can achieve</em>.</p> <p>The frequency of an element is the number of occurences of that element in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,6,4], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2]. The element 2 is the most frequent in the final array so our score is 3. It can be shown that we cannot achieve a better score. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,2,4], k = 0 <strong>Output:</strong> 3 <strong>Explanation:</strong> We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3. </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> <li><code>0 &lt;= k &lt;= 10<sup>14</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Java
class Solution { public int maxFrequencyScore(int[] nums, long k) { Arrays.sort(nums); int n = nums.length; long[] s = new long[n + 1]; for (int i = 1; i <= n; i++) { s[i] = s[i - 1] + nums[i - 1]; } int l = 0, r = n; while (l < r) { int mid = (l + r + 1) >> 1; boolean ok = false; for (int i = 0; i <= n - mid; i++) { int j = i + mid; int x = nums[(i + j) / 2]; long left = ((i + j) / 2 - i) * (long) x - (s[(i + j) / 2] - s[i]); long right = (s[j] - s[(i + j) / 2]) - ((j - (i + j) / 2) * (long) x); if (left + right <= k) { ok = true; break; } } if (ok) { l = mid; } else { r = mid - 1; } } return l; } }
2,968
Apply Operations to Maximize Frequency Score
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You can perform the following operation on the array <strong>at most</strong> <code>k</code> times:</p> <ul> <li>Choose any index <code>i</code> from the array and <strong>increase</strong> or <strong>decrease</strong> <code>nums[i]</code> by <code>1</code>.</li> </ul> <p>The score of the final array is the <strong>frequency</strong> of the most frequent element in the array.</p> <p>Return <em>the <strong>maximum</strong> score you can achieve</em>.</p> <p>The frequency of an element is the number of occurences of that element in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,6,4], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2]. The element 2 is the most frequent in the final array so our score is 3. It can be shown that we cannot achieve a better score. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,2,4], k = 0 <strong>Output:</strong> 3 <strong>Explanation:</strong> We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3. </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> <li><code>0 &lt;= k &lt;= 10<sup>14</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
Python
class Solution: def maxFrequencyScore(self, nums: List[int], k: int) -> int: nums.sort() s = list(accumulate(nums, initial=0)) n = len(nums) l, r = 0, n while l < r: mid = (l + r + 1) >> 1 ok = False for i in range(n - mid + 1): j = i + mid x = nums[(i + j) // 2] left = ((i + j) // 2 - i) * x - (s[(i + j) // 2] - s[i]) right = (s[j] - s[(i + j) // 2]) - ((j - (i + j) // 2) * x) if left + right <= k: ok = True break if ok: l = mid else: r = mid - 1 return l
2,968
Apply Operations to Maximize Frequency Score
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You can perform the following operation on the array <strong>at most</strong> <code>k</code> times:</p> <ul> <li>Choose any index <code>i</code> from the array and <strong>increase</strong> or <strong>decrease</strong> <code>nums[i]</code> by <code>1</code>.</li> </ul> <p>The score of the final array is the <strong>frequency</strong> of the most frequent element in the array.</p> <p>Return <em>the <strong>maximum</strong> score you can achieve</em>.</p> <p>The frequency of an element is the number of occurences of that element in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,6,4], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3]. - Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2]. The element 2 is the most frequent in the final array so our score is 3. It can be shown that we cannot achieve a better score. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,2,4], k = 0 <strong>Output:</strong> 3 <strong>Explanation:</strong> We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3. </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> <li><code>0 &lt;= k &lt;= 10<sup>14</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting; Sliding Window
TypeScript
function maxFrequencyScore(nums: number[], k: number): number { nums.sort((a, b) => a - b); const n = nums.length; const s: number[] = Array(n + 1).fill(0); for (let i = 1; i <= n; i++) { s[i] = s[i - 1] + nums[i - 1]; } let l: number = 0; let r: number = n; while (l < r) { const mid: number = (l + r + 1) >> 1; let ok: boolean = false; for (let i = 0; i <= n - mid; i++) { const j = i + mid; const x = nums[Math.floor((i + j) / 2)]; const left = (Math.floor((i + j) / 2) - i) * x - (s[Math.floor((i + j) / 2)] - s[i]); const right = s[j] - s[Math.floor((i + j) / 2)] - (j - Math.floor((i + j) / 2)) * x; if (left + right <= k) { ok = true; break; } } if (ok) { l = mid; } else { r = mid - 1; } } return l; }
2,969
Minimum Number of Coins for Fruits II
Hard
<p>You are at a fruit market with different types of exotic fruits on display.</p> <p>You are given a <strong>1-indexed</strong> array <code>prices</code>, where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>i<sup>th</sup></code> fruit.</p> <p>The fruit market has the following offer:</p> <ul> <li>If you purchase the <code>i<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j]</code> coins to receive a new offer.</p> <p>Return <em>the <strong>minimum</strong> number of coins needed to acquire all the fruits</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,1,2] <strong>Output:</strong> 4 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 3 coins, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Purchase the 2<sup>nd</sup> fruit with 1 coin, and you are allowed to take the 3<sup>rd</sup> fruit for free. - Take the 3<sup>rd</sup> fruit for free. Note that even though you were allowed to take the 2<sup>nd</sup> fruit for free, you purchased it because it is more optimal. It can be proven that 4 is the minimum number of coins needed to acquire all the fruits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,10,1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 1 coin, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Take the 2<sup>nd</sup> fruit for free. - Purchase the 3<sup>rd</sup> fruit for 1 coin, and you are allowed to take the 4<sup>th</sup> fruit for free. - Take the 4<sup>t</sup><sup>h</sup> fruit for free. It can be proven that 2 is the minimum number of coins needed to acquire all the fruits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
C++
class Solution { public: int minimumCoins(vector<int>& prices) { int n = prices.size(); deque<int> q; for (int i = n; i; --i) { while (q.size() && q.front() > i * 2 + 1) { q.pop_front(); } if (i <= (n - 1) / 2) { prices[i - 1] += prices[q.front() - 1]; } while (q.size() && prices[q.back() - 1] >= prices[i - 1]) { q.pop_back(); } q.push_back(i); } return prices[0]; } };
2,969
Minimum Number of Coins for Fruits II
Hard
<p>You are at a fruit market with different types of exotic fruits on display.</p> <p>You are given a <strong>1-indexed</strong> array <code>prices</code>, where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>i<sup>th</sup></code> fruit.</p> <p>The fruit market has the following offer:</p> <ul> <li>If you purchase the <code>i<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j]</code> coins to receive a new offer.</p> <p>Return <em>the <strong>minimum</strong> number of coins needed to acquire all the fruits</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,1,2] <strong>Output:</strong> 4 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 3 coins, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Purchase the 2<sup>nd</sup> fruit with 1 coin, and you are allowed to take the 3<sup>rd</sup> fruit for free. - Take the 3<sup>rd</sup> fruit for free. Note that even though you were allowed to take the 2<sup>nd</sup> fruit for free, you purchased it because it is more optimal. It can be proven that 4 is the minimum number of coins needed to acquire all the fruits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,10,1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 1 coin, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Take the 2<sup>nd</sup> fruit for free. - Purchase the 3<sup>rd</sup> fruit for 1 coin, and you are allowed to take the 4<sup>th</sup> fruit for free. - Take the 4<sup>t</sup><sup>h</sup> fruit for free. It can be proven that 2 is the minimum number of coins needed to acquire all the fruits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Go
func minimumCoins(prices []int) int { n := len(prices) q := Deque{} for i := n; i > 0; i-- { for q.Size() > 0 && q.Front() > i*2+1 { q.PopFront() } if i <= (n-1)/2 { prices[i-1] += prices[q.Front()-1] } for q.Size() > 0 && prices[q.Back()-1] >= prices[i-1] { q.PopBack() } q.PushBack(i) } return prices[0] } // template type Deque struct{ l, r []int } func (q Deque) Empty() bool { return len(q.l) == 0 && len(q.r) == 0 } func (q Deque) Size() int { return len(q.l) + len(q.r) } func (q *Deque) PushFront(v int) { q.l = append(q.l, v) } func (q *Deque) PushBack(v int) { q.r = append(q.r, v) } func (q *Deque) PopFront() (v int) { if len(q.l) > 0 { q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1] } else { v, q.r = q.r[0], q.r[1:] } return } func (q *Deque) PopBack() (v int) { if len(q.r) > 0 { q.r, v = q.r[:len(q.r)-1], q.r[len(q.r)-1] } else { v, q.l = q.l[0], q.l[1:] } return } func (q Deque) Front() int { if len(q.l) > 0 { return q.l[len(q.l)-1] } return q.r[0] } func (q Deque) Back() int { if len(q.r) > 0 { return q.r[len(q.r)-1] } return q.l[0] } func (q Deque) Get(i int) int { if i < len(q.l) { return q.l[len(q.l)-1-i] } return q.r[i-len(q.l)] }
2,969
Minimum Number of Coins for Fruits II
Hard
<p>You are at a fruit market with different types of exotic fruits on display.</p> <p>You are given a <strong>1-indexed</strong> array <code>prices</code>, where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>i<sup>th</sup></code> fruit.</p> <p>The fruit market has the following offer:</p> <ul> <li>If you purchase the <code>i<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j]</code> coins to receive a new offer.</p> <p>Return <em>the <strong>minimum</strong> number of coins needed to acquire all the fruits</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,1,2] <strong>Output:</strong> 4 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 3 coins, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Purchase the 2<sup>nd</sup> fruit with 1 coin, and you are allowed to take the 3<sup>rd</sup> fruit for free. - Take the 3<sup>rd</sup> fruit for free. Note that even though you were allowed to take the 2<sup>nd</sup> fruit for free, you purchased it because it is more optimal. It can be proven that 4 is the minimum number of coins needed to acquire all the fruits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,10,1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 1 coin, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Take the 2<sup>nd</sup> fruit for free. - Purchase the 3<sup>rd</sup> fruit for 1 coin, and you are allowed to take the 4<sup>th</sup> fruit for free. - Take the 4<sup>t</sup><sup>h</sup> fruit for free. It can be proven that 2 is the minimum number of coins needed to acquire all the fruits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Java
class Solution { public int minimumCoins(int[] prices) { int n = prices.length; Deque<Integer> q = new ArrayDeque<>(); for (int i = n; i > 0; --i) { while (!q.isEmpty() && q.peek() > i * 2 + 1) { q.poll(); } if (i <= (n - 1) / 2) { prices[i - 1] += prices[q.peek() - 1]; } while (!q.isEmpty() && prices[q.peekLast() - 1] >= prices[i - 1]) { q.pollLast(); } q.offer(i); } return prices[0]; } }
2,969
Minimum Number of Coins for Fruits II
Hard
<p>You are at a fruit market with different types of exotic fruits on display.</p> <p>You are given a <strong>1-indexed</strong> array <code>prices</code>, where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>i<sup>th</sup></code> fruit.</p> <p>The fruit market has the following offer:</p> <ul> <li>If you purchase the <code>i<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j]</code> coins to receive a new offer.</p> <p>Return <em>the <strong>minimum</strong> number of coins needed to acquire all the fruits</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,1,2] <strong>Output:</strong> 4 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 3 coins, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Purchase the 2<sup>nd</sup> fruit with 1 coin, and you are allowed to take the 3<sup>rd</sup> fruit for free. - Take the 3<sup>rd</sup> fruit for free. Note that even though you were allowed to take the 2<sup>nd</sup> fruit for free, you purchased it because it is more optimal. It can be proven that 4 is the minimum number of coins needed to acquire all the fruits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,10,1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 1 coin, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Take the 2<sup>nd</sup> fruit for free. - Purchase the 3<sup>rd</sup> fruit for 1 coin, and you are allowed to take the 4<sup>th</sup> fruit for free. - Take the 4<sup>t</sup><sup>h</sup> fruit for free. It can be proven that 2 is the minimum number of coins needed to acquire all the fruits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Python
class Solution: def minimumCoins(self, prices: List[int]) -> int: n = len(prices) q = deque() for i in range(n, 0, -1): while q and q[0] > i * 2 + 1: q.popleft() if i <= (n - 1) // 2: prices[i - 1] += prices[q[0] - 1] while q and prices[q[-1] - 1] >= prices[i - 1]: q.pop() q.append(i) return prices[0]
2,969
Minimum Number of Coins for Fruits II
Hard
<p>You are at a fruit market with different types of exotic fruits on display.</p> <p>You are given a <strong>1-indexed</strong> array <code>prices</code>, where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>i<sup>th</sup></code> fruit.</p> <p>The fruit market has the following offer:</p> <ul> <li>If you purchase the <code>i<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j]</code> coins to receive a new offer.</p> <p>Return <em>the <strong>minimum</strong> number of coins needed to acquire all the fruits</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [3,1,2] <strong>Output:</strong> 4 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 3 coins, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Purchase the 2<sup>nd</sup> fruit with 1 coin, and you are allowed to take the 3<sup>rd</sup> fruit for free. - Take the 3<sup>rd</sup> fruit for free. Note that even though you were allowed to take the 2<sup>nd</sup> fruit for free, you purchased it because it is more optimal. It can be proven that 4 is the minimum number of coins needed to acquire all the fruits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [1,10,1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> You can acquire the fruits as follows: - Purchase the 1<sup>st</sup> fruit with 1 coin, and you are allowed to take the 2<sup>nd</sup> fruit for free. - Take the 2<sup>nd</sup> fruit for free. - Purchase the 3<sup>rd</sup> fruit for 1 coin, and you are allowed to take the 4<sup>th</sup> fruit for free. - Take the 4<sup>t</sup><sup>h</sup> fruit for free. It can be proven that 2 is the minimum number of coins needed to acquire all the fruits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
TypeScript
function minimumCoins(prices: number[]): number { const n = prices.length; const q = new Deque<number>(); for (let i = n; i; --i) { while (q.getSize() && q.frontValue()! > i * 2 + 1) { q.popFront(); } if (i <= (n - 1) >> 1) { prices[i - 1] += prices[q.frontValue()! - 1]; } while (q.getSize() && prices[q.backValue()! - 1] >= prices[i - 1]) { q.popBack(); } q.pushBack(i); } return prices[0]; } class Node<T> { value: T; next: Node<T> | null; prev: Node<T> | null; constructor(value: T) { this.value = value; this.next = null; this.prev = null; } } class Deque<T> { private front: Node<T> | null; private back: Node<T> | null; private size: number; constructor() { this.front = null; this.back = null; this.size = 0; } pushFront(val: T): void { const newNode = new Node(val); if (this.isEmpty()) { this.front = newNode; this.back = newNode; } else { newNode.next = this.front; this.front!.prev = newNode; this.front = newNode; } this.size++; } pushBack(val: T): void { const newNode = new Node(val); if (this.isEmpty()) { this.front = newNode; this.back = newNode; } else { newNode.prev = this.back; this.back!.next = newNode; this.back = newNode; } this.size++; } popFront(): T | undefined { if (this.isEmpty()) { return undefined; } const value = this.front!.value; this.front = this.front!.next; if (this.front !== null) { this.front.prev = null; } else { this.back = null; } this.size--; return value; } popBack(): T | undefined { if (this.isEmpty()) { return undefined; } const value = this.back!.value; this.back = this.back!.prev; if (this.back !== null) { this.back.next = null; } else { this.front = null; } this.size--; return value; } frontValue(): T | undefined { return this.front?.value; } backValue(): T | undefined { return this.back?.value; } getSize(): number { return this.size; } isEmpty(): boolean { return this.size === 0; } }
2,970
Count the Number of Incremovable Subarrays I
Easy
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Binary Search; Enumeration
C++
class Solution { public: int incremovableSubarrayCount(vector<int>& nums) { int i = 0, n = nums.size(); while (i + 1 < n && nums[i] < nums[i + 1]) { ++i; } if (i == n - 1) { return n * (n + 1) / 2; } int ans = i + 2; for (int j = n - 1; j > 0; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; } };
2,970
Count the Number of Incremovable Subarrays I
Easy
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Binary Search; Enumeration
Go
func incremovableSubarrayCount(nums []int) int { i, n := 0, len(nums) for i+1 < n && nums[i] < nums[i+1] { i++ } if i == n-1 { return n * (n + 1) / 2 } ans := i + 2 for j := n - 1; j > 0; j-- { for i >= 0 && nums[i] >= nums[j] { i-- } ans += i + 2 if nums[j-1] >= nums[j] { break } } return ans }
2,970
Count the Number of Incremovable Subarrays I
Easy
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Binary Search; Enumeration
Java
class Solution { public int incremovableSubarrayCount(int[] nums) { int i = 0, n = nums.length; while (i + 1 < n && nums[i] < nums[i + 1]) { ++i; } if (i == n - 1) { return n * (n + 1) / 2; } int ans = i + 2; for (int j = n - 1; j > 0; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; } }
2,970
Count the Number of Incremovable Subarrays I
Easy
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Binary Search; Enumeration
Python
class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: i, n = 0, len(nums) while i + 1 < n and nums[i] < nums[i + 1]: i += 1 if i == n - 1: return n * (n + 1) // 2 ans = i + 2 j = n - 1 while j: while i >= 0 and nums[i] >= nums[j]: i -= 1 ans += i + 2 if nums[j - 1] >= nums[j]: break j -= 1 return ans
2,970
Count the Number of Incremovable Subarrays I
Easy
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Two Pointers; Binary Search; Enumeration
TypeScript
function incremovableSubarrayCount(nums: number[]): number { const n = nums.length; let i = 0; while (i + 1 < n && nums[i] < nums[i + 1]) { i++; } if (i === n - 1) { return (n * (n + 1)) / 2; } let ans = i + 2; for (let j = n - 1; j; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; }
2,971
Find Polygon With the Largest Perimeter
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p> <p>A <strong>polygon</strong> is a closed plane figure that has at least <code>3</code> sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p> <p>Conversely, if you have <code>k</code> (<code>k &gt;= 3</code>) <strong>positive</strong> real numbers <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code> where <code>a<sub>1</sub> &lt;= a<sub>2</sub> &lt;= a<sub>3</sub> &lt;= ... &lt;= a<sub>k</sub></code> <strong>and</strong> <code>a<sub>1</sub> + a<sub>2</sub> + a<sub>3</sub> + ... + a<sub>k-1</sub> &gt; a<sub>k</sub></code>, then there <strong>always</strong> exists a polygon with <code>k</code> sides whose lengths are <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code>.</p> <p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p> <p>Return <em>the <strong>largest</strong> possible <strong>perimeter</strong> of a <strong>polygon</strong> whose sides can be formed from</em> <code>nums</code>, <em>or</em> <code>-1</code> <em>if it is not possible to create a polygon</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5] <strong>Output:</strong> 15 <strong>Explanation:</strong> The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,1,2,5,50,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,50] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 &gt; 5 + 5. </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> </ul>
Greedy; Array; Prefix Sum; Sorting
C++
class Solution { public: long long largestPerimeter(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); vector<long long> s(n + 1); for (int i = 1; i <= n; ++i) { s[i] = s[i - 1] + nums[i - 1]; } long long ans = -1; for (int k = 3; k <= n; ++k) { if (s[k - 1] > nums[k - 1]) { ans = max(ans, s[k]); } } return ans; } };
2,971
Find Polygon With the Largest Perimeter
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p> <p>A <strong>polygon</strong> is a closed plane figure that has at least <code>3</code> sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p> <p>Conversely, if you have <code>k</code> (<code>k &gt;= 3</code>) <strong>positive</strong> real numbers <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code> where <code>a<sub>1</sub> &lt;= a<sub>2</sub> &lt;= a<sub>3</sub> &lt;= ... &lt;= a<sub>k</sub></code> <strong>and</strong> <code>a<sub>1</sub> + a<sub>2</sub> + a<sub>3</sub> + ... + a<sub>k-1</sub> &gt; a<sub>k</sub></code>, then there <strong>always</strong> exists a polygon with <code>k</code> sides whose lengths are <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code>.</p> <p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p> <p>Return <em>the <strong>largest</strong> possible <strong>perimeter</strong> of a <strong>polygon</strong> whose sides can be formed from</em> <code>nums</code>, <em>or</em> <code>-1</code> <em>if it is not possible to create a polygon</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5] <strong>Output:</strong> 15 <strong>Explanation:</strong> The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,1,2,5,50,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,50] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 &gt; 5 + 5. </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> </ul>
Greedy; Array; Prefix Sum; Sorting
Go
func largestPerimeter(nums []int) int64 { sort.Ints(nums) n := len(nums) s := make([]int, n+1) for i, x := range nums { s[i+1] = s[i] + x } ans := -1 for k := 3; k <= n; k++ { if s[k-1] > nums[k-1] { ans = max(ans, s[k]) } } return int64(ans) }
2,971
Find Polygon With the Largest Perimeter
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p> <p>A <strong>polygon</strong> is a closed plane figure that has at least <code>3</code> sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p> <p>Conversely, if you have <code>k</code> (<code>k &gt;= 3</code>) <strong>positive</strong> real numbers <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code> where <code>a<sub>1</sub> &lt;= a<sub>2</sub> &lt;= a<sub>3</sub> &lt;= ... &lt;= a<sub>k</sub></code> <strong>and</strong> <code>a<sub>1</sub> + a<sub>2</sub> + a<sub>3</sub> + ... + a<sub>k-1</sub> &gt; a<sub>k</sub></code>, then there <strong>always</strong> exists a polygon with <code>k</code> sides whose lengths are <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code>.</p> <p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p> <p>Return <em>the <strong>largest</strong> possible <strong>perimeter</strong> of a <strong>polygon</strong> whose sides can be formed from</em> <code>nums</code>, <em>or</em> <code>-1</code> <em>if it is not possible to create a polygon</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5] <strong>Output:</strong> 15 <strong>Explanation:</strong> The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,1,2,5,50,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,50] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 &gt; 5 + 5. </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> </ul>
Greedy; Array; Prefix Sum; Sorting
Java
class Solution { public long largestPerimeter(int[] nums) { Arrays.sort(nums); int n = nums.length; long[] s = new long[n + 1]; for (int i = 1; i <= n; ++i) { s[i] = s[i - 1] + nums[i - 1]; } long ans = -1; for (int k = 3; k <= n; ++k) { if (s[k - 1] > nums[k - 1]) { ans = Math.max(ans, s[k]); } } return ans; } }
2,971
Find Polygon With the Largest Perimeter
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p> <p>A <strong>polygon</strong> is a closed plane figure that has at least <code>3</code> sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p> <p>Conversely, if you have <code>k</code> (<code>k &gt;= 3</code>) <strong>positive</strong> real numbers <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code> where <code>a<sub>1</sub> &lt;= a<sub>2</sub> &lt;= a<sub>3</sub> &lt;= ... &lt;= a<sub>k</sub></code> <strong>and</strong> <code>a<sub>1</sub> + a<sub>2</sub> + a<sub>3</sub> + ... + a<sub>k-1</sub> &gt; a<sub>k</sub></code>, then there <strong>always</strong> exists a polygon with <code>k</code> sides whose lengths are <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code>.</p> <p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p> <p>Return <em>the <strong>largest</strong> possible <strong>perimeter</strong> of a <strong>polygon</strong> whose sides can be formed from</em> <code>nums</code>, <em>or</em> <code>-1</code> <em>if it is not possible to create a polygon</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5] <strong>Output:</strong> 15 <strong>Explanation:</strong> The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,1,2,5,50,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,50] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 &gt; 5 + 5. </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> </ul>
Greedy; Array; Prefix Sum; Sorting
Python
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() s = list(accumulate(nums, initial=0)) ans = -1 for k in range(3, len(nums) + 1): if s[k - 1] > nums[k - 1]: ans = max(ans, s[k]) return ans
2,971
Find Polygon With the Largest Perimeter
Medium
<p>You are given an array of <strong>positive</strong> integers <code>nums</code> of length <code>n</code>.</p> <p>A <strong>polygon</strong> is a closed plane figure that has at least <code>3</code> sides. The <strong>longest side</strong> of a polygon is <strong>smaller</strong> than the sum of its other sides.</p> <p>Conversely, if you have <code>k</code> (<code>k &gt;= 3</code>) <strong>positive</strong> real numbers <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code> where <code>a<sub>1</sub> &lt;= a<sub>2</sub> &lt;= a<sub>3</sub> &lt;= ... &lt;= a<sub>k</sub></code> <strong>and</strong> <code>a<sub>1</sub> + a<sub>2</sub> + a<sub>3</sub> + ... + a<sub>k-1</sub> &gt; a<sub>k</sub></code>, then there <strong>always</strong> exists a polygon with <code>k</code> sides whose lengths are <code>a<sub>1</sub></code>, <code>a<sub>2</sub></code>, <code>a<sub>3</sub></code>, ..., <code>a<sub>k</sub></code>.</p> <p>The <strong>perimeter</strong> of a polygon is the sum of lengths of its sides.</p> <p>Return <em>the <strong>largest</strong> possible <strong>perimeter</strong> of a <strong>polygon</strong> whose sides can be formed from</em> <code>nums</code>, <em>or</em> <code>-1</code> <em>if it is not possible to create a polygon</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5] <strong>Output:</strong> 15 <strong>Explanation:</strong> The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,12,1,2,5,50,3] <strong>Output:</strong> 12 <strong>Explanation:</strong> The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12. We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them. It can be shown that the largest possible perimeter is 12. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,50] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 &gt; 5 + 5. </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> </ul>
Greedy; Array; Prefix Sum; Sorting
TypeScript
function largestPerimeter(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; const s: number[] = Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } let ans = -1; for (let k = 3; k <= n; ++k) { if (s[k - 1] > nums[k - 1]) { ans = Math.max(ans, s[k]); } } return ans; }
2,972
Count the Number of Incremovable Subarrays II
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </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>
Array; Two Pointers; Binary Search
C++
class Solution { public: long long incremovableSubarrayCount(vector<int>& nums) { int i = 0, n = nums.size(); while (i + 1 < n && nums[i] < nums[i + 1]) { ++i; } if (i == n - 1) { return n * (n + 1LL) / 2; } long long ans = i + 2; for (int j = n - 1; j > 0; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; } };
2,972
Count the Number of Incremovable Subarrays II
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </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>
Array; Two Pointers; Binary Search
Go
func incremovableSubarrayCount(nums []int) int64 { i, n := 0, len(nums) for i+1 < n && nums[i] < nums[i+1] { i++ } if i == n-1 { return int64(n * (n + 1) / 2) } ans := int64(i + 2) for j := n - 1; j > 0; j-- { for i >= 0 && nums[i] >= nums[j] { i-- } ans += int64(i + 2) if nums[j-1] >= nums[j] { break } } return ans }
2,972
Count the Number of Incremovable Subarrays II
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </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>
Array; Two Pointers; Binary Search
Java
class Solution { public long incremovableSubarrayCount(int[] nums) { int i = 0, n = nums.length; while (i + 1 < n && nums[i] < nums[i + 1]) { ++i; } if (i == n - 1) { return n * (n + 1L) / 2; } long ans = i + 2; for (int j = n - 1; j > 0; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; } }
2,972
Count the Number of Incremovable Subarrays II
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </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>
Array; Two Pointers; Binary Search
Python
class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: i, n = 0, len(nums) while i + 1 < n and nums[i] < nums[i + 1]: i += 1 if i == n - 1: return n * (n + 1) // 2 ans = i + 2 j = n - 1 while j: while i >= 0 and nums[i] >= nums[j]: i -= 1 ans += i + 2 if nums[j - 1] >= nums[j]: break j -= 1 return ans
2,972
Count the Number of Incremovable Subarrays II
Hard
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code>.</p> <p>A subarray of <code>nums</code> is called <strong>incremovable</strong> if <code>nums</code> becomes <strong>strictly increasing</strong> on removing the subarray. For example, the subarray <code>[3, 4]</code> is an incremovable subarray of <code>[5, 3, 4, 6, 7]</code> because removing this subarray changes the array <code>[5, 3, 4, 6, 7]</code> to <code>[5, 6, 7]</code> which is strictly increasing.</p> <p>Return <em>the total number of <strong>incremovable</strong> subarrays of</em> <code>nums</code>.</p> <p><strong>Note</strong> that an empty array is considered strictly increasing.</p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 10 <strong>Explanation:</strong> The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,5,7,8] <strong>Output:</strong> 7 <strong>Explanation:</strong> The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8]. It can be shown that there are only 7 incremovable subarrays in nums. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [8,7,6,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing. </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>
Array; Two Pointers; Binary Search
TypeScript
function incremovableSubarrayCount(nums: number[]): number { const n = nums.length; let i = 0; while (i + 1 < n && nums[i] < nums[i + 1]) { i++; } if (i === n - 1) { return (n * (n + 1)) / 2; } let ans = i + 2; for (let j = n - 1; j; --j) { while (i >= 0 && nums[i] >= nums[j]) { --i; } ans += i + 2; if (nums[j - 1] >= nums[j]) { break; } } return ans; }
2,973
Find Number of Coins to Place in Tree Nodes
Hard
<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p> <p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p> <ul> <li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li> <li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li> </ul> <p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6] <strong>Output:</strong> [120,1,1,1,1,1] <strong>Explanation:</strong> For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2] <strong>Output:</strong> [280,140,32,1,1,1,1,1,1] <strong>Explanation:</strong> The coins placed on each node are: - Place 8 * 7 * 5 = 280 coins on node 0. - Place 7 * 5 * 4 = 140 coins on node 1. - Place 8 * 2 * 2 = 32 coins on node 2. - All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2] <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming; Sorting; Heap (Priority Queue)
C++
class Solution { public: vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) { int n = cost.size(); vector<long long> ans(n, 1); vector<int> g[n]; for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } function<vector<int>(int, int)> dfs = [&](int a, int fa) -> vector<int> { vector<int> res = {cost[a]}; for (int b : g[a]) { if (b != fa) { auto t = dfs(b, a); res.insert(res.end(), t.begin(), t.end()); } } sort(res.begin(), res.end()); int m = res.size(); if (m >= 3) { long long x = 1LL * res[m - 1] * res[m - 2] * res[m - 3]; long long y = 1LL * res[0] * res[1] * res[m - 1]; ans[a] = max({0LL, x, y}); } if (m >= 5) { res = {res[0], res[1], res[m - 1], res[m - 2], res[m - 3]}; } return res; }; dfs(0, -1); return ans; } };
2,973
Find Number of Coins to Place in Tree Nodes
Hard
<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p> <p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p> <ul> <li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li> <li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li> </ul> <p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6] <strong>Output:</strong> [120,1,1,1,1,1] <strong>Explanation:</strong> For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2] <strong>Output:</strong> [280,140,32,1,1,1,1,1,1] <strong>Explanation:</strong> The coins placed on each node are: - Place 8 * 7 * 5 = 280 coins on node 0. - Place 7 * 5 * 4 = 140 coins on node 1. - Place 8 * 2 * 2 = 32 coins on node 2. - All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2] <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming; Sorting; Heap (Priority Queue)
Go
func placedCoins(edges [][]int, cost []int) []int64 { n := len(cost) g := make([][]int, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } ans := make([]int64, n) for i := range ans { ans[i] = int64(1) } var dfs func(a, fa int) []int dfs = func(a, fa int) []int { res := []int{cost[a]} for _, b := range g[a] { if b != fa { res = append(res, dfs(b, a)...) } } sort.Ints(res) m := len(res) if m >= 3 { x := res[m-1] * res[m-2] * res[m-3] y := res[0] * res[1] * res[m-1] ans[a] = max(0, int64(x), int64(y)) } if m >= 5 { res = append(res[:2], res[m-3:]...) } return res } dfs(0, -1) return ans }
2,973
Find Number of Coins to Place in Tree Nodes
Hard
<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p> <p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p> <ul> <li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li> <li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li> </ul> <p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6] <strong>Output:</strong> [120,1,1,1,1,1] <strong>Explanation:</strong> For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2] <strong>Output:</strong> [280,140,32,1,1,1,1,1,1] <strong>Explanation:</strong> The coins placed on each node are: - Place 8 * 7 * 5 = 280 coins on node 0. - Place 7 * 5 * 4 = 140 coins on node 1. - Place 8 * 2 * 2 = 32 coins on node 2. - All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2] <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming; Sorting; Heap (Priority Queue)
Java
class Solution { private int[] cost; private List<Integer>[] g; private long[] ans; public long[] placedCoins(int[][] edges, int[] cost) { int n = cost.length; this.cost = cost; ans = new long[n]; g = new List[n]; Arrays.fill(ans, 1); Arrays.setAll(g, i -> new ArrayList<>()); for (int[] e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } dfs(0, -1); return ans; } private List<Integer> dfs(int a, int fa) { List<Integer> res = new ArrayList<>(); res.add(cost[a]); for (int b : g[a]) { if (b != fa) { res.addAll(dfs(b, a)); } } Collections.sort(res); int m = res.size(); if (m >= 3) { long x = (long) res.get(m - 1) * res.get(m - 2) * res.get(m - 3); long y = (long) res.get(0) * res.get(1) * res.get(m - 1); ans[a] = Math.max(0, Math.max(x, y)); } if (m >= 5) { res = List.of(res.get(0), res.get(1), res.get(m - 3), res.get(m - 2), res.get(m - 1)); } return res; } }
2,973
Find Number of Coins to Place in Tree Nodes
Hard
<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p> <p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p> <ul> <li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li> <li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li> </ul> <p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6] <strong>Output:</strong> [120,1,1,1,1,1] <strong>Explanation:</strong> For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2] <strong>Output:</strong> [280,140,32,1,1,1,1,1,1] <strong>Explanation:</strong> The coins placed on each node are: - Place 8 * 7 * 5 = 280 coins on node 0. - Place 7 * 5 * 4 = 140 coins on node 1. - Place 8 * 2 * 2 = 32 coins on node 2. - All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2] <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming; Sorting; Heap (Priority Queue)
Python
class Solution: def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: def dfs(a: int, fa: int) -> List[int]: res = [cost[a]] for b in g[a]: if b != fa: res.extend(dfs(b, a)) res.sort() if len(res) >= 3: ans[a] = max(res[-3] * res[-2] * res[-1], res[0] * res[1] * res[-1], 0) if len(res) > 5: res = res[:2] + res[-3:] return res n = len(cost) g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) ans = [1] * n dfs(0, -1) return ans
2,973
Find Number of Coins to Place in Tree Nodes
Hard
<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p> <p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p> <ul> <li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li> <li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li> </ul> <p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6] <strong>Output:</strong> [120,1,1,1,1,1] <strong>Explanation:</strong> For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2] <strong>Output:</strong> [280,140,32,1,1,1,1,1,1] <strong>Explanation:</strong> The coins placed on each node are: - Place 8 * 7 * 5 = 280 coins on node 0. - Place 7 * 5 * 4 = 140 coins on node 1. - Place 8 * 2 * 2 = 32 coins on node 2. - All other nodes are leaves with subtree of size 1, place 1 coin on each of them. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2973.Find%20Number%20of%20Coins%20to%20Place%20in%20Tree%20Nodes/images/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" /> <pre> <strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2] <strong>Output:</strong> [0,1,1] <strong>Explanation:</strong> Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search; Dynamic Programming; Sorting; Heap (Priority Queue)
TypeScript
function placedCoins(edges: number[][], cost: number[]): number[] { const n = cost.length; const ans: number[] = Array(n).fill(1); const g: number[][] = Array.from({ length: n }, () => []); for (const [a, b] of edges) { g[a].push(b); g[b].push(a); } const dfs = (a: number, fa: number): number[] => { const res: number[] = [cost[a]]; for (const b of g[a]) { if (b !== fa) { res.push(...dfs(b, a)); } } res.sort((a, b) => a - b); const m = res.length; if (m >= 3) { const x = res[m - 1] * res[m - 2] * res[m - 3]; const y = res[0] * res[1] * res[m - 1]; ans[a] = Math.max(0, x, y); } if (m > 5) { res.splice(2, m - 5); } return res; }; dfs(0, -1); return ans; }
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
C++
class Solution { public: vector<int> numberGame(vector<int>& nums) { priority_queue<int, vector<int>, greater<int>> pq; for (int x : nums) { pq.push(x); } vector<int> ans; while (pq.size()) { int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); ans.push_back(b); ans.push_back(a); } return ans; } };
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
Go
func numberGame(nums []int) (ans []int) { pq := &hp{nums} heap.Init(pq) for pq.Len() > 0 { a := heap.Pop(pq).(int) b := heap.Pop(pq).(int) ans = append(ans, b) ans = append(ans, a) } return } type hp struct{ sort.IntSlice } func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } func (h *hp) Pop() interface{} { old := h.IntSlice n := len(old) x := old[n-1] h.IntSlice = old[0 : n-1] return x } func (h *hp) Push(x interface{}) { h.IntSlice = append(h.IntSlice, x.(int)) }
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
Java
class Solution { public int[] numberGame(int[] nums) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int x : nums) { pq.offer(x); } int[] ans = new int[nums.length]; int i = 0; while (!pq.isEmpty()) { int a = pq.poll(); ans[i++] = pq.poll(); ans[i++] = a; } return ans; } }
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
Python
class Solution: def numberGame(self, nums: List[int]) -> List[int]: heapify(nums) ans = [] while nums: a, b = heappop(nums), heappop(nums) ans.append(b) ans.append(a) return ans
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
Rust
use std::cmp::Reverse; use std::collections::BinaryHeap; impl Solution { pub fn number_game(nums: Vec<i32>) -> Vec<i32> { let mut pq = BinaryHeap::new(); for &x in &nums { pq.push(Reverse(x)); } let mut ans = Vec::new(); while let Some(Reverse(a)) = pq.pop() { if let Some(Reverse(b)) = pq.pop() { ans.push(b); ans.push(a); } } ans } }
2,974
Minimum Number Game
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of <strong>even</strong> length and there is also an empty array <code>arr</code>. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:</p> <ul> <li>Every round, first Alice will remove the <strong>minimum</strong> element from <code>nums</code>, and then Bob does the same.</li> <li>Now, first Bob will append the removed element in the array <code>arr</code>, and then Alice does the same.</li> <li>The game continues until <code>nums</code> becomes empty.</li> </ul> <p>Return <em>the resulting array </em><code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,4,2,3] <strong>Output:</strong> [3,2,5,4] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2]. At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,5] <strong>Output:</strong> [5,2] <strong>Explanation:</strong> In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums.length % 2 == 0</code></li> </ul>
Array; Sorting; Simulation; Heap (Priority Queue)
TypeScript
function numberGame(nums: number[]): number[] { const pq = new MinPriorityQueue(); for (const x of nums) { pq.enqueue(x); } const ans: number[] = []; while (pq.size()) { const a = pq.dequeue().element; const b = pq.dequeue().element; ans.push(b, a); } return ans; }
2,975
Maximum Square Area by Removing Fences From a Field
Medium
<p>There is a large <code>(m - 1) x (n - 1)</code> rectangular field with corners at <code>(1, 1)</code> and <code>(m, n)</code> containing some horizontal and vertical fences given in arrays <code>hFences</code> and <code>vFences</code> respectively.</p> <p>Horizontal fences are from the coordinates <code>(hFences[i], 1)</code> to <code>(hFences[i], n)</code> and vertical fences are from the coordinates <code>(1, vFences[i])</code> to <code>(m, vFences[i])</code>.</p> <p>Return <em>the <strong>maximum</strong> area of a <strong>square</strong> field that can be formed by <strong>removing</strong> some fences (<strong>possibly none</strong>) or </em><code>-1</code> <em>if it is impossible to make a square field</em>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p><strong>Note: </strong>The field is surrounded by two horizontal fences from the coordinates <code>(1, 1)</code> to <code>(1, n)</code> and <code>(m, 1)</code> to <code>(m, n)</code> and two vertical fences from the coordinates <code>(1, 1)</code> to <code>(m, 1)</code> and <code>(1, n)</code> to <code>(m, n)</code>. These fences <strong>cannot</strong> be removed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/screenshot-from-2023-11-05-22-40-25.png" /></p> <pre> <strong>Input:</strong> m = 4, n = 3, hFences = [2,3], vFences = [2] <strong>Output:</strong> 4 <strong>Explanation:</strong> Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/maxsquareareaexample1.png" style="width: 285px; height: 242px;" /></p> <pre> <strong>Input:</strong> m = 6, n = 7, hFences = [2], vFences = [4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proved that there is no way to create a square field by removing fences. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= m, n &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">1 &lt;= hF</font>ences<font face="monospace">.length, vFences.length &lt;= 600</font></code></li> <li><code><font face="monospace">1 &lt; hFences[i] &lt; m</font></code></li> <li><code><font face="monospace">1 &lt; vFences[i] &lt; n</font></code></li> <li><code><font face="monospace">hFences</font></code><font face="monospace"> and </font><code><font face="monospace">vFences</font></code><font face="monospace"> are unique.</font></li> </ul>
Array; Hash Table; Enumeration
C++
class Solution { public: int maximizeSquareArea(int m, int n, vector<int>& hFences, vector<int>& vFences) { auto f = [](vector<int>& nums, int k) { nums.push_back(k); nums.push_back(1); sort(nums.begin(), nums.end()); unordered_set<int> s; for (int i = 0; i < nums.size(); ++i) { for (int j = 0; j < i; ++j) { s.insert(nums[i] - nums[j]); } } return s; }; auto hs = f(hFences, m); auto vs = f(vFences, n); int ans = 0; for (int h : hs) { if (vs.count(h)) { ans = max(ans, h); } } const int mod = 1e9 + 7; return ans > 0 ? 1LL * ans * ans % mod : -1; } };
2,975
Maximum Square Area by Removing Fences From a Field
Medium
<p>There is a large <code>(m - 1) x (n - 1)</code> rectangular field with corners at <code>(1, 1)</code> and <code>(m, n)</code> containing some horizontal and vertical fences given in arrays <code>hFences</code> and <code>vFences</code> respectively.</p> <p>Horizontal fences are from the coordinates <code>(hFences[i], 1)</code> to <code>(hFences[i], n)</code> and vertical fences are from the coordinates <code>(1, vFences[i])</code> to <code>(m, vFences[i])</code>.</p> <p>Return <em>the <strong>maximum</strong> area of a <strong>square</strong> field that can be formed by <strong>removing</strong> some fences (<strong>possibly none</strong>) or </em><code>-1</code> <em>if it is impossible to make a square field</em>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p><strong>Note: </strong>The field is surrounded by two horizontal fences from the coordinates <code>(1, 1)</code> to <code>(1, n)</code> and <code>(m, 1)</code> to <code>(m, n)</code> and two vertical fences from the coordinates <code>(1, 1)</code> to <code>(m, 1)</code> and <code>(1, n)</code> to <code>(m, n)</code>. These fences <strong>cannot</strong> be removed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/screenshot-from-2023-11-05-22-40-25.png" /></p> <pre> <strong>Input:</strong> m = 4, n = 3, hFences = [2,3], vFences = [2] <strong>Output:</strong> 4 <strong>Explanation:</strong> Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/maxsquareareaexample1.png" style="width: 285px; height: 242px;" /></p> <pre> <strong>Input:</strong> m = 6, n = 7, hFences = [2], vFences = [4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proved that there is no way to create a square field by removing fences. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= m, n &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">1 &lt;= hF</font>ences<font face="monospace">.length, vFences.length &lt;= 600</font></code></li> <li><code><font face="monospace">1 &lt; hFences[i] &lt; m</font></code></li> <li><code><font face="monospace">1 &lt; vFences[i] &lt; n</font></code></li> <li><code><font face="monospace">hFences</font></code><font face="monospace"> and </font><code><font face="monospace">vFences</font></code><font face="monospace"> are unique.</font></li> </ul>
Array; Hash Table; Enumeration
Go
func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int { f := func(nums []int, k int) map[int]bool { nums = append(nums, 1, k) sort.Ints(nums) s := map[int]bool{} for i := 0; i < len(nums); i++ { for j := 0; j < i; j++ { s[nums[i]-nums[j]] = true } } return s } hs := f(hFences, m) vs := f(vFences, n) ans := 0 for h := range hs { if vs[h] { ans = max(ans, h) } } if ans > 0 { return ans * ans % (1e9 + 7) } return -1 }
2,975
Maximum Square Area by Removing Fences From a Field
Medium
<p>There is a large <code>(m - 1) x (n - 1)</code> rectangular field with corners at <code>(1, 1)</code> and <code>(m, n)</code> containing some horizontal and vertical fences given in arrays <code>hFences</code> and <code>vFences</code> respectively.</p> <p>Horizontal fences are from the coordinates <code>(hFences[i], 1)</code> to <code>(hFences[i], n)</code> and vertical fences are from the coordinates <code>(1, vFences[i])</code> to <code>(m, vFences[i])</code>.</p> <p>Return <em>the <strong>maximum</strong> area of a <strong>square</strong> field that can be formed by <strong>removing</strong> some fences (<strong>possibly none</strong>) or </em><code>-1</code> <em>if it is impossible to make a square field</em>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p><strong>Note: </strong>The field is surrounded by two horizontal fences from the coordinates <code>(1, 1)</code> to <code>(1, n)</code> and <code>(m, 1)</code> to <code>(m, n)</code> and two vertical fences from the coordinates <code>(1, 1)</code> to <code>(m, 1)</code> and <code>(1, n)</code> to <code>(m, n)</code>. These fences <strong>cannot</strong> be removed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/screenshot-from-2023-11-05-22-40-25.png" /></p> <pre> <strong>Input:</strong> m = 4, n = 3, hFences = [2,3], vFences = [2] <strong>Output:</strong> 4 <strong>Explanation:</strong> Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/maxsquareareaexample1.png" style="width: 285px; height: 242px;" /></p> <pre> <strong>Input:</strong> m = 6, n = 7, hFences = [2], vFences = [4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proved that there is no way to create a square field by removing fences. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= m, n &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">1 &lt;= hF</font>ences<font face="monospace">.length, vFences.length &lt;= 600</font></code></li> <li><code><font face="monospace">1 &lt; hFences[i] &lt; m</font></code></li> <li><code><font face="monospace">1 &lt; vFences[i] &lt; n</font></code></li> <li><code><font face="monospace">hFences</font></code><font face="monospace"> and </font><code><font face="monospace">vFences</font></code><font face="monospace"> are unique.</font></li> </ul>
Array; Hash Table; Enumeration
Java
class Solution { public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { Set<Integer> hs = f(hFences, m); Set<Integer> vs = f(vFences, n); hs.retainAll(vs); int ans = -1; final int mod = (int) 1e9 + 7; for (int x : hs) { ans = Math.max(ans, x); } return ans > 0 ? (int) (1L * ans * ans % mod) : -1; } private Set<Integer> f(int[] nums, int k) { int n = nums.length; nums = Arrays.copyOf(nums, n + 2); nums[n] = 1; nums[n + 1] = k; Arrays.sort(nums); Set<Integer> s = new HashSet<>(); for (int i = 0; i < nums.length; ++i) { for (int j = 0; j < i; ++j) { s.add(nums[i] - nums[j]); } } return s; } }
2,975
Maximum Square Area by Removing Fences From a Field
Medium
<p>There is a large <code>(m - 1) x (n - 1)</code> rectangular field with corners at <code>(1, 1)</code> and <code>(m, n)</code> containing some horizontal and vertical fences given in arrays <code>hFences</code> and <code>vFences</code> respectively.</p> <p>Horizontal fences are from the coordinates <code>(hFences[i], 1)</code> to <code>(hFences[i], n)</code> and vertical fences are from the coordinates <code>(1, vFences[i])</code> to <code>(m, vFences[i])</code>.</p> <p>Return <em>the <strong>maximum</strong> area of a <strong>square</strong> field that can be formed by <strong>removing</strong> some fences (<strong>possibly none</strong>) or </em><code>-1</code> <em>if it is impossible to make a square field</em>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p><strong>Note: </strong>The field is surrounded by two horizontal fences from the coordinates <code>(1, 1)</code> to <code>(1, n)</code> and <code>(m, 1)</code> to <code>(m, n)</code> and two vertical fences from the coordinates <code>(1, 1)</code> to <code>(m, 1)</code> and <code>(1, n)</code> to <code>(m, n)</code>. These fences <strong>cannot</strong> be removed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/screenshot-from-2023-11-05-22-40-25.png" /></p> <pre> <strong>Input:</strong> m = 4, n = 3, hFences = [2,3], vFences = [2] <strong>Output:</strong> 4 <strong>Explanation:</strong> Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/maxsquareareaexample1.png" style="width: 285px; height: 242px;" /></p> <pre> <strong>Input:</strong> m = 6, n = 7, hFences = [2], vFences = [4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proved that there is no way to create a square field by removing fences. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= m, n &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">1 &lt;= hF</font>ences<font face="monospace">.length, vFences.length &lt;= 600</font></code></li> <li><code><font face="monospace">1 &lt; hFences[i] &lt; m</font></code></li> <li><code><font face="monospace">1 &lt; vFences[i] &lt; n</font></code></li> <li><code><font face="monospace">hFences</font></code><font face="monospace"> and </font><code><font face="monospace">vFences</font></code><font face="monospace"> are unique.</font></li> </ul>
Array; Hash Table; Enumeration
Python
class Solution: def maximizeSquareArea( self, m: int, n: int, hFences: List[int], vFences: List[int] ) -> int: def f(nums: List[int], k: int) -> Set[int]: nums.extend([1, k]) nums.sort() return {b - a for a, b in combinations(nums, 2)} mod = 10**9 + 7 hs = f(hFences, m) vs = f(vFences, n) ans = max(hs & vs, default=0) return ans**2 % mod if ans else -1
2,975
Maximum Square Area by Removing Fences From a Field
Medium
<p>There is a large <code>(m - 1) x (n - 1)</code> rectangular field with corners at <code>(1, 1)</code> and <code>(m, n)</code> containing some horizontal and vertical fences given in arrays <code>hFences</code> and <code>vFences</code> respectively.</p> <p>Horizontal fences are from the coordinates <code>(hFences[i], 1)</code> to <code>(hFences[i], n)</code> and vertical fences are from the coordinates <code>(1, vFences[i])</code> to <code>(m, vFences[i])</code>.</p> <p>Return <em>the <strong>maximum</strong> area of a <strong>square</strong> field that can be formed by <strong>removing</strong> some fences (<strong>possibly none</strong>) or </em><code>-1</code> <em>if it is impossible to make a square field</em>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p><strong>Note: </strong>The field is surrounded by two horizontal fences from the coordinates <code>(1, 1)</code> to <code>(1, n)</code> and <code>(m, 1)</code> to <code>(m, n)</code> and two vertical fences from the coordinates <code>(1, 1)</code> to <code>(m, 1)</code> and <code>(1, n)</code> to <code>(m, n)</code>. These fences <strong>cannot</strong> be removed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/screenshot-from-2023-11-05-22-40-25.png" /></p> <pre> <strong>Input:</strong> m = 4, n = 3, hFences = [2,3], vFences = [2] <strong>Output:</strong> 4 <strong>Explanation:</strong> Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4. </pre> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2975.Maximum%20Square%20Area%20by%20Removing%20Fences%20From%20a%20Field/images/maxsquareareaexample1.png" style="width: 285px; height: 242px;" /></p> <pre> <strong>Input:</strong> m = 6, n = 7, hFences = [2], vFences = [4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proved that there is no way to create a square field by removing fences. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= m, n &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">1 &lt;= hF</font>ences<font face="monospace">.length, vFences.length &lt;= 600</font></code></li> <li><code><font face="monospace">1 &lt; hFences[i] &lt; m</font></code></li> <li><code><font face="monospace">1 &lt; vFences[i] &lt; n</font></code></li> <li><code><font face="monospace">hFences</font></code><font face="monospace"> and </font><code><font face="monospace">vFences</font></code><font face="monospace"> are unique.</font></li> </ul>
Array; Hash Table; Enumeration
TypeScript
function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: number[]): number { const f = (nums: number[], k: number): Set<number> => { nums.push(1, k); nums.sort((a, b) => a - b); const s: Set<number> = new Set(); for (let i = 0; i < nums.length; ++i) { for (let j = 0; j < i; ++j) { s.add(nums[i] - nums[j]); } } return s; }; const hs = f(hFences, m); const vs = f(vFences, n); let ans = 0; for (const h of hs) { if (vs.has(h)) { ans = Math.max(ans, h); } } return ans ? Number(BigInt(ans) ** 2n % 1000000007n) : -1; }
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
C++
class Solution { public: long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) { const int inf = 1 << 29; int g[26][26]; for (int i = 0; i < 26; ++i) { fill(begin(g[i]), end(g[i]), inf); g[i][i] = 0; } for (int i = 0; i < original.size(); ++i) { int x = original[i] - 'a'; int y = changed[i] - 'a'; int z = cost[i]; g[x][y] = min(g[x][y], z); } for (int k = 0; k < 26; ++k) { for (int i = 0; i < 26; ++i) { for (int j = 0; j < 26; ++j) { g[i][j] = min(g[i][j], g[i][k] + g[k][j]); } } } long long ans = 0; int n = source.length(); for (int i = 0; i < n; ++i) { int x = source[i] - 'a'; int y = target[i] - 'a'; if (x != y) { if (g[x][y] >= inf) { return -1; } ans += g[x][y]; } } return ans; } };
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
Go
func minimumCost(source string, target string, original []byte, changed []byte, cost []int) (ans int64) { const inf = 1 << 29 g := make([][]int, 26) for i := range g { g[i] = make([]int, 26) for j := range g[i] { if i == j { g[i][j] = 0 } else { g[i][j] = inf } } } for i := 0; i < len(original); i++ { x := int(original[i] - 'a') y := int(changed[i] - 'a') z := cost[i] g[x][y] = min(g[x][y], z) } for k := 0; k < 26; k++ { for i := 0; i < 26; i++ { for j := 0; j < 26; j++ { g[i][j] = min(g[i][j], g[i][k]+g[k][j]) } } } n := len(source) for i := 0; i < n; i++ { x := int(source[i] - 'a') y := int(target[i] - 'a') if x != y { if g[x][y] >= inf { return -1 } ans += int64(g[x][y]) } } return }
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
Java
class Solution { public long minimumCost( String source, String target, char[] original, char[] changed, int[] cost) { final int inf = 1 << 29; int[][] g = new int[26][26]; for (int i = 0; i < 26; ++i) { Arrays.fill(g[i], inf); g[i][i] = 0; } for (int i = 0; i < original.length; ++i) { int x = original[i] - 'a'; int y = changed[i] - 'a'; int z = cost[i]; g[x][y] = Math.min(g[x][y], z); } for (int k = 0; k < 26; ++k) { for (int i = 0; i < 26; ++i) { for (int j = 0; j < 26; ++j) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } long ans = 0; int n = source.length(); for (int i = 0; i < n; ++i) { int x = source.charAt(i) - 'a'; int y = target.charAt(i) - 'a'; if (x != y) { if (g[x][y] >= inf) { return -1; } ans += g[x][y]; } } return ans; } }
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
JavaScript
/** * @param {string} source * @param {string} target * @param {character[]} original * @param {character[]} changed * @param {number[]} cost * @return {number} */ var minimumCost = function (source, target, original, changed, cost) { const [n, m, MAX] = [source.length, original.length, Number.POSITIVE_INFINITY]; const g = Array.from({ length: 26 }, () => Array(26).fill(MAX)); const getIndex = ch => ch.charCodeAt(0) - 'a'.charCodeAt(0); for (let i = 0; i < 26; ++i) g[i][i] = 0; for (let i = 0; i < m; ++i) { const x = getIndex(original[i]); const y = getIndex(changed[i]); const z = cost[i]; g[x][y] = Math.min(g[x][y], z); } for (let k = 0; k < 26; ++k) { for (let i = 0; i < 26; ++i) { for (let j = 0; g[i][k] < MAX && j < 26; j++) { if (g[k][j] < MAX) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } } let ans = 0; for (let i = 0; i < n; ++i) { const x = getIndex(source[i]); const y = getIndex(target[i]); if (x === y) continue; if (g[x][y] === MAX) return -1; ans += g[x][y]; } return ans; };
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
Python
class Solution: def minimumCost( self, source: str, target: str, original: List[str], changed: List[str], cost: List[int], ) -> int: g = [[inf] * 26 for _ in range(26)] for i in range(26): g[i][i] = 0 for x, y, z in zip(original, changed, cost): x = ord(x) - ord('a') y = ord(y) - ord('a') g[x][y] = min(g[x][y], z) for k in range(26): for i in range(26): for j in range(26): g[i][j] = min(g[i][j], g[i][k] + g[k][j]) ans = 0 for a, b in zip(source, target): if a != b: x, y = ord(a) - ord('a'), ord(b) - ord('a') if g[x][y] >= inf: return -1 ans += g[x][y] return ans
2,976
Minimum Cost to Convert String I
Medium
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;: - Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5. - Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1. - Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2. - Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2] <strong>Output:</strong> 12 <strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li> <li><code>source</code>, <code>target</code> consist of lowercase English letters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li> <li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> <li><code>original[i] != changed[i]</code></li> </ul>
Graph; Array; String; Shortest Path
TypeScript
function minimumCost( source: string, target: string, original: string[], changed: string[], cost: number[], ): number { const [n, m, MAX] = [source.length, original.length, Number.POSITIVE_INFINITY]; const g: number[][] = Array.from({ length: 26 }, () => Array(26).fill(MAX)); const getIndex = (ch: string) => ch.charCodeAt(0) - 'a'.charCodeAt(0); for (let i = 0; i < 26; ++i) g[i][i] = 0; for (let i = 0; i < m; ++i) { const x = getIndex(original[i]); const y = getIndex(changed[i]); const z = cost[i]; g[x][y] = Math.min(g[x][y], z); } for (let k = 0; k < 26; ++k) { for (let i = 0; i < 26; ++i) { for (let j = 0; g[i][k] < MAX && j < 26; j++) { if (g[k][j] < MAX) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } } let ans = 0; for (let i = 0; i < n; ++i) { const x = getIndex(source[i]); const y = getIndex(target[i]); if (x === y) continue; if (g[x][y] === MAX) return -1; ans += g[x][y]; } return ans; }
2,977
Minimum Cost to Convert String II
Hard
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English characters. You are also given two <strong>0-indexed</strong> string arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of converting the string <code>original[i]</code> to the string <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a <strong>substring</strong> <code>x</code> from the string, and change it to <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>. You are allowed to do <strong>any</strong> number of operations, but any pair of operations must satisfy <strong>either</strong> of these two conditions:</p> <ul> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with either <code>b &lt; c</code> <strong>or</strong> <code>d &lt; a</code>. In other words, the indices picked in both operations are <strong>disjoint</strong>.</li> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with <code>a == c</code> <strong>and</strong> <code>b == d</code>. In other words, the indices picked in both operations are <strong>identical</strong>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations</em>. <em>If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>,<em> return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert &quot;abcd&quot; to &quot;acbe&quot;, do the following operations: - Change substring source[1..1] from &quot;b&quot; to &quot;c&quot; at a cost of 5. - Change substring source[2..2] from &quot;c&quot; to &quot;e&quot; at a cost of 1. - Change substring source[2..2] from &quot;e&quot; to &quot;b&quot; at a cost of 2. - Change substring source[3..3] from &quot;d&quot; to &quot;e&quot; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;acdeeghh&quot;, original = [&quot;bcd&quot;,&quot;fgh&quot;,&quot;thh&quot;], changed = [&quot;cde&quot;,&quot;thh&quot;,&quot;ghh&quot;], cost = [1,3,5] <strong>Output:</strong> 9 <strong>Explanation:</strong> To convert &quot;abcdefgh&quot; to &quot;acdeeghh&quot;, do the following operations: - Change substring source[1..3] from &quot;bcd&quot; to &quot;cde&quot; at a cost of 1. - Change substring source[5..7] from &quot;fgh&quot; to &quot;thh&quot; at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from &quot;thh&quot; to &quot;ghh&quot; at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;addddddd&quot;, original = [&quot;bcd&quot;,&quot;defgh&quot;], changed = [&quot;ddd&quot;,&quot;ddddd&quot;], cost = [100,1578] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert &quot;abcdefgh&quot; to &quot;addddddd&quot;. If you select substring source[1..3] as the first operation to change &quot;abcdefgh&quot; to &quot;adddefgh&quot;, you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change &quot;abcdefgh&quot; to &quot;abcddddd&quot;, you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 1000</code></li> <li><code>source</code>, <code>target</code> consist only of lowercase English characters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 100</code></li> <li><code>1 &lt;= original[i].length == changed[i].length &lt;= source.length</code></li> <li><code>original[i]</code>, <code>changed[i]</code> consist only of lowercase English characters.</li> <li><code>original[i] != changed[i]</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> </ul>
Graph; Trie; Array; String; Dynamic Programming; Shortest Path
C++
class Node { public: Node* children[26]; int v = -1; Node() { fill(children, children + 26, nullptr); } }; class Solution { private: const long long inf = 1LL << 60; Node* root = new Node(); int idx; vector<vector<long long>> g; string s; string t; vector<long long> f; public: long long minimumCost(string source, string target, vector<string>& original, vector<string>& changed, vector<int>& cost) { int m = cost.size(); g = vector<vector<long long>>(m << 1, vector<long long>(m << 1, inf)); s = source; t = target; for (int i = 0; i < g.size(); ++i) { g[i][i] = 0; } for (int i = 0; i < m; ++i) { int x = insert(original[i]); int y = insert(changed[i]); g[x][y] = min(g[x][y], static_cast<long long>(cost[i])); } for (int k = 0; k < idx; ++k) { for (int i = 0; i < idx; ++i) { if (g[i][k] >= inf) { continue; } for (int j = 0; j < idx; ++j) { g[i][j] = min(g[i][j], g[i][k] + g[k][j]); } } } f = vector<long long>(s.length(), -1); long long ans = dfs(0); return ans >= inf ? -1 : ans; } private: int insert(const string& w) { Node* node = root; for (char c : w) { int i = c - 'a'; if (node->children[i] == nullptr) { node->children[i] = new Node(); } node = node->children[i]; } if (node->v < 0) { node->v = idx++; } return node->v; } long long dfs(int i) { if (i >= s.length()) { return 0; } if (f[i] != -1) { return f[i]; } long long res = (s[i] == t[i]) ? dfs(i + 1) : inf; Node* p = root; Node* q = root; for (int j = i; j < s.length(); ++j) { p = p->children[s[j] - 'a']; q = q->children[t[j] - 'a']; if (p == nullptr || q == nullptr) { break; } if (p->v < 0 || q->v < 0) { continue; } long long temp = g[p->v][q->v]; if (temp < inf) { res = min(res, temp + dfs(j + 1)); } } return f[i] = res; } };
2,977
Minimum Cost to Convert String II
Hard
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English characters. You are also given two <strong>0-indexed</strong> string arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of converting the string <code>original[i]</code> to the string <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a <strong>substring</strong> <code>x</code> from the string, and change it to <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>. You are allowed to do <strong>any</strong> number of operations, but any pair of operations must satisfy <strong>either</strong> of these two conditions:</p> <ul> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with either <code>b &lt; c</code> <strong>or</strong> <code>d &lt; a</code>. In other words, the indices picked in both operations are <strong>disjoint</strong>.</li> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with <code>a == c</code> <strong>and</strong> <code>b == d</code>. In other words, the indices picked in both operations are <strong>identical</strong>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations</em>. <em>If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>,<em> return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert &quot;abcd&quot; to &quot;acbe&quot;, do the following operations: - Change substring source[1..1] from &quot;b&quot; to &quot;c&quot; at a cost of 5. - Change substring source[2..2] from &quot;c&quot; to &quot;e&quot; at a cost of 1. - Change substring source[2..2] from &quot;e&quot; to &quot;b&quot; at a cost of 2. - Change substring source[3..3] from &quot;d&quot; to &quot;e&quot; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;acdeeghh&quot;, original = [&quot;bcd&quot;,&quot;fgh&quot;,&quot;thh&quot;], changed = [&quot;cde&quot;,&quot;thh&quot;,&quot;ghh&quot;], cost = [1,3,5] <strong>Output:</strong> 9 <strong>Explanation:</strong> To convert &quot;abcdefgh&quot; to &quot;acdeeghh&quot;, do the following operations: - Change substring source[1..3] from &quot;bcd&quot; to &quot;cde&quot; at a cost of 1. - Change substring source[5..7] from &quot;fgh&quot; to &quot;thh&quot; at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from &quot;thh&quot; to &quot;ghh&quot; at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;addddddd&quot;, original = [&quot;bcd&quot;,&quot;defgh&quot;], changed = [&quot;ddd&quot;,&quot;ddddd&quot;], cost = [100,1578] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert &quot;abcdefgh&quot; to &quot;addddddd&quot;. If you select substring source[1..3] as the first operation to change &quot;abcdefgh&quot; to &quot;adddefgh&quot;, you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change &quot;abcdefgh&quot; to &quot;abcddddd&quot;, you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 1000</code></li> <li><code>source</code>, <code>target</code> consist only of lowercase English characters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 100</code></li> <li><code>1 &lt;= original[i].length == changed[i].length &lt;= source.length</code></li> <li><code>original[i]</code>, <code>changed[i]</code> consist only of lowercase English characters.</li> <li><code>original[i] != changed[i]</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> </ul>
Graph; Trie; Array; String; Dynamic Programming; Shortest Path
Go
type Node struct { children [26]*Node v int } func newNode() *Node { return &Node{v: -1} } func minimumCost(source string, target string, original []string, changed []string, cost []int) int64 { inf := 1 << 60 root := newNode() idx := 0 m := len(cost) g := make([][]int, m<<1) for i := range g { g[i] = make([]int, m<<1) for j := range g[i] { g[i][j] = inf } g[i][i] = 0 } insert := func(w string) int { node := root for _, c := range w { i := c - 'a' if node.children[i] == nil { node.children[i] = newNode() } node = node.children[i] } if node.v < 0 { node.v = idx idx++ } return node.v } for i := range original { x := insert(original[i]) y := insert(changed[i]) g[x][y] = min(g[x][y], cost[i]) } for k := 0; k < idx; k++ { for i := 0; i < idx; i++ { if g[i][k] >= inf { continue } for j := 0; j < idx; j++ { g[i][j] = min(g[i][j], g[i][k]+g[k][j]) } } } n := len(source) f := make([]int, n) for i := range f { f[i] = -1 } var dfs func(int) int dfs = func(i int) int { if i >= n { return 0 } if f[i] >= 0 { return f[i] } f[i] = inf if source[i] == target[i] { f[i] = dfs(i + 1) } p, q := root, root for j := i; j < n; j++ { p = p.children[source[j]-'a'] q = q.children[target[j]-'a'] if p == nil || q == nil { break } if p.v < 0 || q.v < 0 { continue } f[i] = min(f[i], dfs(j+1)+g[p.v][q.v]) } return f[i] } ans := dfs(0) if ans >= inf { ans = -1 } return int64(ans) }
2,977
Minimum Cost to Convert String II
Hard
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English characters. You are also given two <strong>0-indexed</strong> string arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of converting the string <code>original[i]</code> to the string <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a <strong>substring</strong> <code>x</code> from the string, and change it to <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>. You are allowed to do <strong>any</strong> number of operations, but any pair of operations must satisfy <strong>either</strong> of these two conditions:</p> <ul> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with either <code>b &lt; c</code> <strong>or</strong> <code>d &lt; a</code>. In other words, the indices picked in both operations are <strong>disjoint</strong>.</li> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with <code>a == c</code> <strong>and</strong> <code>b == d</code>. In other words, the indices picked in both operations are <strong>identical</strong>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations</em>. <em>If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>,<em> return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert &quot;abcd&quot; to &quot;acbe&quot;, do the following operations: - Change substring source[1..1] from &quot;b&quot; to &quot;c&quot; at a cost of 5. - Change substring source[2..2] from &quot;c&quot; to &quot;e&quot; at a cost of 1. - Change substring source[2..2] from &quot;e&quot; to &quot;b&quot; at a cost of 2. - Change substring source[3..3] from &quot;d&quot; to &quot;e&quot; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;acdeeghh&quot;, original = [&quot;bcd&quot;,&quot;fgh&quot;,&quot;thh&quot;], changed = [&quot;cde&quot;,&quot;thh&quot;,&quot;ghh&quot;], cost = [1,3,5] <strong>Output:</strong> 9 <strong>Explanation:</strong> To convert &quot;abcdefgh&quot; to &quot;acdeeghh&quot;, do the following operations: - Change substring source[1..3] from &quot;bcd&quot; to &quot;cde&quot; at a cost of 1. - Change substring source[5..7] from &quot;fgh&quot; to &quot;thh&quot; at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from &quot;thh&quot; to &quot;ghh&quot; at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;addddddd&quot;, original = [&quot;bcd&quot;,&quot;defgh&quot;], changed = [&quot;ddd&quot;,&quot;ddddd&quot;], cost = [100,1578] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert &quot;abcdefgh&quot; to &quot;addddddd&quot;. If you select substring source[1..3] as the first operation to change &quot;abcdefgh&quot; to &quot;adddefgh&quot;, you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change &quot;abcdefgh&quot; to &quot;abcddddd&quot;, you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 1000</code></li> <li><code>source</code>, <code>target</code> consist only of lowercase English characters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 100</code></li> <li><code>1 &lt;= original[i].length == changed[i].length &lt;= source.length</code></li> <li><code>original[i]</code>, <code>changed[i]</code> consist only of lowercase English characters.</li> <li><code>original[i] != changed[i]</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> </ul>
Graph; Trie; Array; String; Dynamic Programming; Shortest Path
Java
class Node { Node[] children = new Node[26]; int v = -1; } class Solution { private final long inf = 1L << 60; private Node root = new Node(); private int idx; private long[][] g; private char[] s; private char[] t; private Long[] f; public long minimumCost( String source, String target, String[] original, String[] changed, int[] cost) { int m = cost.length; g = new long[m << 1][m << 1]; s = source.toCharArray(); t = target.toCharArray(); for (int i = 0; i < g.length; ++i) { Arrays.fill(g[i], inf); g[i][i] = 0; } for (int i = 0; i < m; ++i) { int x = insert(original[i]); int y = insert(changed[i]); g[x][y] = Math.min(g[x][y], cost[i]); } for (int k = 0; k < idx; ++k) { for (int i = 0; i < idx; ++i) { if (g[i][k] >= inf) { continue; } for (int j = 0; j < idx; ++j) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } f = new Long[s.length]; long ans = dfs(0); return ans >= inf ? -1 : ans; } private int insert(String w) { Node node = root; for (char c : w.toCharArray()) { int i = c - 'a'; if (node.children[i] == null) { node.children[i] = new Node(); } node = node.children[i]; } if (node.v < 0) { node.v = idx++; } return node.v; } private long dfs(int i) { if (i >= s.length) { return 0; } if (f[i] != null) { return f[i]; } long res = s[i] == t[i] ? dfs(i + 1) : inf; Node p = root, q = root; for (int j = i; j < s.length; ++j) { p = p.children[s[j] - 'a']; q = q.children[t[j] - 'a']; if (p == null || q == null) { break; } if (p.v < 0 || q.v < 0) { continue; } long t = g[p.v][q.v]; if (t < inf) { res = Math.min(res, t + dfs(j + 1)); } } return f[i] = res; } }
2,977
Minimum Cost to Convert String II
Hard
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English characters. You are also given two <strong>0-indexed</strong> string arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of converting the string <code>original[i]</code> to the string <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a <strong>substring</strong> <code>x</code> from the string, and change it to <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>. You are allowed to do <strong>any</strong> number of operations, but any pair of operations must satisfy <strong>either</strong> of these two conditions:</p> <ul> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with either <code>b &lt; c</code> <strong>or</strong> <code>d &lt; a</code>. In other words, the indices picked in both operations are <strong>disjoint</strong>.</li> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with <code>a == c</code> <strong>and</strong> <code>b == d</code>. In other words, the indices picked in both operations are <strong>identical</strong>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations</em>. <em>If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>,<em> return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert &quot;abcd&quot; to &quot;acbe&quot;, do the following operations: - Change substring source[1..1] from &quot;b&quot; to &quot;c&quot; at a cost of 5. - Change substring source[2..2] from &quot;c&quot; to &quot;e&quot; at a cost of 1. - Change substring source[2..2] from &quot;e&quot; to &quot;b&quot; at a cost of 2. - Change substring source[3..3] from &quot;d&quot; to &quot;e&quot; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;acdeeghh&quot;, original = [&quot;bcd&quot;,&quot;fgh&quot;,&quot;thh&quot;], changed = [&quot;cde&quot;,&quot;thh&quot;,&quot;ghh&quot;], cost = [1,3,5] <strong>Output:</strong> 9 <strong>Explanation:</strong> To convert &quot;abcdefgh&quot; to &quot;acdeeghh&quot;, do the following operations: - Change substring source[1..3] from &quot;bcd&quot; to &quot;cde&quot; at a cost of 1. - Change substring source[5..7] from &quot;fgh&quot; to &quot;thh&quot; at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from &quot;thh&quot; to &quot;ghh&quot; at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;addddddd&quot;, original = [&quot;bcd&quot;,&quot;defgh&quot;], changed = [&quot;ddd&quot;,&quot;ddddd&quot;], cost = [100,1578] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert &quot;abcdefgh&quot; to &quot;addddddd&quot;. If you select substring source[1..3] as the first operation to change &quot;abcdefgh&quot; to &quot;adddefgh&quot;, you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change &quot;abcdefgh&quot; to &quot;abcddddd&quot;, you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 1000</code></li> <li><code>source</code>, <code>target</code> consist only of lowercase English characters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 100</code></li> <li><code>1 &lt;= original[i].length == changed[i].length &lt;= source.length</code></li> <li><code>original[i]</code>, <code>changed[i]</code> consist only of lowercase English characters.</li> <li><code>original[i] != changed[i]</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> </ul>
Graph; Trie; Array; String; Dynamic Programming; Shortest Path
Python
class Node: __slots__ = ["children", "v"] def __init__(self): self.children: List[Node | None] = [None] * 26 self.v = -1 class Solution: def minimumCost( self, source: str, target: str, original: List[str], changed: List[str], cost: List[int], ) -> int: m = len(cost) g = [[inf] * (m << 1) for _ in range(m << 1)] for i in range(m << 1): g[i][i] = 0 root = Node() idx = 0 def insert(w: str) -> int: node = root for c in w: i = ord(c) - ord("a") if node.children[i] is None: node.children[i] = Node() node = node.children[i] if node.v < 0: nonlocal idx node.v = idx idx += 1 return node.v @cache def dfs(i: int) -> int: if i >= len(source): return 0 res = dfs(i + 1) if source[i] == target[i] else inf p = q = root for j in range(i, len(source)): p = p.children[ord(source[j]) - ord("a")] q = q.children[ord(target[j]) - ord("a")] if p is None or q is None: break if p.v < 0 or q.v < 0: continue res = min(res, dfs(j + 1) + g[p.v][q.v]) return res for x, y, z in zip(original, changed, cost): x = insert(x) y = insert(y) g[x][y] = min(g[x][y], z) for k in range(idx): for i in range(idx): if g[i][k] >= inf: continue for j in range(idx): # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) if g[i][k] + g[k][j] < g[i][j]: g[i][j] = g[i][k] + g[k][j] ans = dfs(0) return -1 if ans >= inf else ans
2,977
Minimum Cost to Convert String II
Hard
<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English characters. You are also given two <strong>0-indexed</strong> string arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of converting the string <code>original[i]</code> to the string <code>changed[i]</code>.</p> <p>You start with the string <code>source</code>. In one operation, you can pick a <strong>substring</strong> <code>x</code> from the string, and change it to <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>. You are allowed to do <strong>any</strong> number of operations, but any pair of operations must satisfy <strong>either</strong> of these two conditions:</p> <ul> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with either <code>b &lt; c</code> <strong>or</strong> <code>d &lt; a</code>. In other words, the indices picked in both operations are <strong>disjoint</strong>.</li> <li>The substrings picked in the operations are <code>source[a..b]</code> and <code>source[c..d]</code> with <code>a == c</code> <strong>and</strong> <code>b == d</code>. In other words, the indices picked in both operations are <strong>identical</strong>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations</em>. <em>If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>,<em> return</em> <code>-1</code>.</p> <p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20] <strong>Output:</strong> 28 <strong>Explanation:</strong> To convert &quot;abcd&quot; to &quot;acbe&quot;, do the following operations: - Change substring source[1..1] from &quot;b&quot; to &quot;c&quot; at a cost of 5. - Change substring source[2..2] from &quot;c&quot; to &quot;e&quot; at a cost of 1. - Change substring source[2..2] from &quot;e&quot; to &quot;b&quot; at a cost of 2. - Change substring source[3..3] from &quot;d&quot; to &quot;e&quot; at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;acdeeghh&quot;, original = [&quot;bcd&quot;,&quot;fgh&quot;,&quot;thh&quot;], changed = [&quot;cde&quot;,&quot;thh&quot;,&quot;ghh&quot;], cost = [1,3,5] <strong>Output:</strong> 9 <strong>Explanation:</strong> To convert &quot;abcdefgh&quot; to &quot;acdeeghh&quot;, do the following operations: - Change substring source[1..3] from &quot;bcd&quot; to &quot;cde&quot; at a cost of 1. - Change substring source[5..7] from &quot;fgh&quot; to &quot;thh&quot; at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from &quot;thh&quot; to &quot;ghh&quot; at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> source = &quot;abcdefgh&quot;, target = &quot;addddddd&quot;, original = [&quot;bcd&quot;,&quot;defgh&quot;], changed = [&quot;ddd&quot;,&quot;ddddd&quot;], cost = [100,1578] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to convert &quot;abcdefgh&quot; to &quot;addddddd&quot;. If you select substring source[1..3] as the first operation to change &quot;abcdefgh&quot; to &quot;adddefgh&quot;, you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change &quot;abcdefgh&quot; to &quot;abcddddd&quot;, you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= source.length == target.length &lt;= 1000</code></li> <li><code>source</code>, <code>target</code> consist only of lowercase English characters.</li> <li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 100</code></li> <li><code>1 &lt;= original[i].length == changed[i].length &lt;= source.length</code></li> <li><code>original[i]</code>, <code>changed[i]</code> consist only of lowercase English characters.</li> <li><code>original[i] != changed[i]</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li> </ul>
Graph; Trie; Array; String; Dynamic Programming; Shortest Path
TypeScript
class Node { children: (Node | null)[] = Array(26).fill(null); v: number = -1; } function minimumCost( source: string, target: string, original: string[], changed: string[], cost: number[], ): number { const m = cost.length; const n = source.length; const g: number[][] = Array.from({ length: m << 1 }, () => Array(m << 1).fill(Infinity)); const root: Node = new Node(); let idx: number = 0; const f: number[] = Array(n).fill(-1); const insert = (w: string): number => { let node: Node = root; for (const c of w) { const i: number = c.charCodeAt(0) - 'a'.charCodeAt(0); if (node.children[i] === null) { node.children[i] = new Node(); } node = node.children[i] as Node; } if (node.v < 0) { node.v = idx++; } return node.v; }; const dfs = (i: number): number => { if (i >= n) { return 0; } if (f[i] !== -1) { return f[i]; } let res: number = source[i] === target[i] ? dfs(i + 1) : Infinity; let p: Node = root; let q: Node = root; for (let j = i; j < source.length; ++j) { p = p.children[source[j].charCodeAt(0) - 'a'.charCodeAt(0)] as Node; q = q.children[target[j].charCodeAt(0) - 'a'.charCodeAt(0)] as Node; if (p === null || q === null) { break; } if (p.v < 0 || q.v < 0) { continue; } const t: number = g[p.v][q.v]; res = Math.min(res, t + dfs(j + 1)); } return (f[i] = res); }; for (let i = 0; i < m; ++i) { const x: number = insert(original[i]); const y: number = insert(changed[i]); g[x][y] = Math.min(g[x][y], cost[i]); } for (let k = 0; k < idx; ++k) { for (let i = 0; i < idx; ++i) { if (g[i][k] >= Infinity) { continue; } for (let j = 0; j < idx; ++j) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } const ans: number = dfs(0); return ans >= Infinity ? -1 : ans; }
2,978
Symmetric Coordinates
Medium
<p>Table: <font face="monospace"><code>Coordinates</code></font></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | X | int | | Y | int | +-------------+------+ Each row includes X and Y, where both are integers. Table may contain duplicate values. </pre> <p>Two coordindates <code>(X1, Y1)</code> and <code>(X2, Y2)</code> are said to be <strong>symmetric</strong> coordintes if <code>X1 == Y2</code> and <code>X2 == Y1</code>.</p> <p>Write a solution that outputs, among all these <strong>symmetric</strong> <strong>coordintes</strong>, only those <strong>unique</strong> coordinates that satisfy the condition <code>X1 &lt;= Y1</code>.</p> <p>Return <em>the result table ordered by </em><code>X</code> <em>and </em> <code>Y</code> <em>(respectively)</em> <em>in <strong>ascending order</strong></em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Coordinates table: +----+----+ | X | Y | +----+----+ | 20 | 20 | | 20 | 20 | | 20 | 21 | | 23 | 22 | | 22 | 23 | | 21 | 20 | +----+----+ <strong>Output:</strong> +----+----+ | x | y | +----+----+ | 20 | 20 | | 20 | 21 | | 22 | 23 | +----+----+ <strong>Explanation:</strong> - (20, 20) and (20, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. This results in displaying (20, 20) as a distinctive coordinates. - (20, 21) and (21, 20) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (20, 21) will be displayed because X1 &lt;= Y1. - (23, 22) and (22, 23) are symmetric coordinates because, X1 == Y2 and X2 == Y1. However, only (22, 23) will be displayed because X1 &lt;= Y1. The output table is sorted by X and Y in ascending order. </pre>
Database
SQL
# Write your MySQL query statement below WITH P AS ( SELECT ROW_NUMBER() OVER () AS id, x, y FROM Coordinates ) SELECT DISTINCT p1.x, p1.y FROM P AS p1 JOIN P AS p2 ON p1.x = p2.y AND p1.y = p2.x AND p1.x <= p1.y AND p1.id != p2.id ORDER BY 1, 2;
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
C++
class Solution { public: int mostExpensiveItem(int primeOne, int primeTwo) { return primeOne * primeTwo - primeOne - primeTwo; } };
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
Go
func mostExpensiveItem(primeOne int, primeTwo int) int { return primeOne*primeTwo - primeOne - primeTwo }
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
Java
class Solution { public int mostExpensiveItem(int primeOne, int primeTwo) { return primeOne * primeTwo - primeOne - primeTwo; } }
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
Python
class Solution: def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: return primeOne * primeTwo - primeOne - primeTwo
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
Rust
impl Solution { pub fn most_expensive_item(prime_one: i32, prime_two: i32) -> i32 { prime_one * prime_two - prime_one - prime_two } }
2,979
Most Expensive Item That Can Not Be Bought
Medium
<p>You are given two <strong>distinct</strong> <strong>prime</strong> numbers <code>primeOne</code> and <code>primeTwo</code>.</p> <p>Alice and Bob are visiting a market. The market has an <strong>infinite</strong> number of items, for <strong>any</strong> positive integer <code>x</code> there exists an item whose price is <code>x</code>. Alice wants to buy some items from the market to gift to Bob. She has an <strong>infinite</strong> number of coins in the denomination <code>primeOne</code> and <code>primeTwo</code>. She wants to know the <strong>most expensive</strong> item she can <strong>not</strong> buy to gift to Bob.</p> <p>Return <em>the price of the <strong>most expensive</strong> item which Alice can not gift to Bob</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> primeOne = 2, primeTwo = 5 <strong>Output:</strong> 3 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,3]. It can be shown that all items with a price greater than 3 can be bought using a combination of coins of denominations 2 and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> primeOne = 5, primeTwo = 7 <strong>Output:</strong> 23 <strong>Explanation:</strong> The prices of items which cannot be bought are [1,2,3,4,6,8,9,11,13,16,18,23]. It can be shown that all items with a price greater than 23 can be bought. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt; primeOne, primeTwo &lt; 10<sup>4</sup></code></li> <li><code>primeOne</code>, <code>primeTwo</code> are prime numbers.</li> <li><code>primeOne * primeTwo &lt; 10<sup>5</sup></code></li> </ul>
Math; Dynamic Programming; Number Theory
TypeScript
function mostExpensiveItem(primeOne: number, primeTwo: number): number { return primeOne * primeTwo - primeOne - primeTwo; }
2,980
Check if Bitwise OR Has Trailing Zeros
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You have to check if it is possible to select <strong>two or more</strong> elements in the array such that the bitwise <code>OR</code> of the selected elements has <strong>at least </strong>one trailing zero in its binary representation.</p> <p>For example, the binary representation of <code>5</code>, which is <code>&quot;101&quot;</code>, does not have any trailing zeros, whereas the binary representation of <code>4</code>, which is <code>&quot;100&quot;</code>, has two trailing zeros.</p> <p>Return <code>true</code> <em>if it is possible to select two or more elements whose bitwise</em> <code>OR</code> <em>has trailing zeros, return</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,8,16] <strong>Output:</strong> true <strong>Explanation: </strong>If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,7,9] <strong>Output:</strong> false <strong>Explanation:</strong> There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: bool hasTrailingZeros(vector<int>& nums) { int cnt = 0; for (int x : nums) { cnt += (x & 1 ^ 1); } return cnt >= 2; } };
2,980
Check if Bitwise OR Has Trailing Zeros
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You have to check if it is possible to select <strong>two or more</strong> elements in the array such that the bitwise <code>OR</code> of the selected elements has <strong>at least </strong>one trailing zero in its binary representation.</p> <p>For example, the binary representation of <code>5</code>, which is <code>&quot;101&quot;</code>, does not have any trailing zeros, whereas the binary representation of <code>4</code>, which is <code>&quot;100&quot;</code>, has two trailing zeros.</p> <p>Return <code>true</code> <em>if it is possible to select two or more elements whose bitwise</em> <code>OR</code> <em>has trailing zeros, return</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,8,16] <strong>Output:</strong> true <strong>Explanation: </strong>If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,7,9] <strong>Output:</strong> false <strong>Explanation:</strong> There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Go
func hasTrailingZeros(nums []int) bool { cnt := 0 for _, x := range nums { cnt += (x&1 ^ 1) } return cnt >= 2 }
2,980
Check if Bitwise OR Has Trailing Zeros
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You have to check if it is possible to select <strong>two or more</strong> elements in the array such that the bitwise <code>OR</code> of the selected elements has <strong>at least </strong>one trailing zero in its binary representation.</p> <p>For example, the binary representation of <code>5</code>, which is <code>&quot;101&quot;</code>, does not have any trailing zeros, whereas the binary representation of <code>4</code>, which is <code>&quot;100&quot;</code>, has two trailing zeros.</p> <p>Return <code>true</code> <em>if it is possible to select two or more elements whose bitwise</em> <code>OR</code> <em>has trailing zeros, return</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,8,16] <strong>Output:</strong> true <strong>Explanation: </strong>If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,7,9] <strong>Output:</strong> false <strong>Explanation:</strong> There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Java
class Solution { public boolean hasTrailingZeros(int[] nums) { int cnt = 0; for (int x : nums) { cnt += (x & 1 ^ 1); } return cnt >= 2; } }
2,980
Check if Bitwise OR Has Trailing Zeros
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You have to check if it is possible to select <strong>two or more</strong> elements in the array such that the bitwise <code>OR</code> of the selected elements has <strong>at least </strong>one trailing zero in its binary representation.</p> <p>For example, the binary representation of <code>5</code>, which is <code>&quot;101&quot;</code>, does not have any trailing zeros, whereas the binary representation of <code>4</code>, which is <code>&quot;100&quot;</code>, has two trailing zeros.</p> <p>Return <code>true</code> <em>if it is possible to select two or more elements whose bitwise</em> <code>OR</code> <em>has trailing zeros, return</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,8,16] <strong>Output:</strong> true <strong>Explanation: </strong>If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,7,9] <strong>Output:</strong> false <strong>Explanation:</strong> There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
Python
class Solution: def hasTrailingZeros(self, nums: List[int]) -> bool: return sum(x & 1 ^ 1 for x in nums) >= 2
2,980
Check if Bitwise OR Has Trailing Zeros
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>You have to check if it is possible to select <strong>two or more</strong> elements in the array such that the bitwise <code>OR</code> of the selected elements has <strong>at least </strong>one trailing zero in its binary representation.</p> <p>For example, the binary representation of <code>5</code>, which is <code>&quot;101&quot;</code>, does not have any trailing zeros, whereas the binary representation of <code>4</code>, which is <code>&quot;100&quot;</code>, has two trailing zeros.</p> <p>Return <code>true</code> <em>if it is possible to select two or more elements whose bitwise</em> <code>OR</code> <em>has trailing zeros, return</em> <code>false</code> <em>otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> true <strong>Explanation:</strong> If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,8,16] <strong>Output:</strong> true <strong>Explanation: </strong>If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation &quot;110&quot; with one trailing zero. Other possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16). </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,7,9] <strong>Output:</strong> false <strong>Explanation:</strong> There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Bit Manipulation; Array
TypeScript
function hasTrailingZeros(nums: number[]): boolean { let cnt = 0; for (const x of nums) { cnt += (x & 1) ^ 1; } return cnt >= 2; }
2,981
Find Longest Special Substring That Occurs Thrice I
Medium
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p> <p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>&quot;abc&quot;</code> is not special, whereas the strings <code>&quot;ddd&quot;</code>, <code>&quot;zz&quot;</code>, and <code>&quot;f&quot;</code> are special.</p> <p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;aa&quot;: substrings &quot;<u><strong>aa</strong></u>aa&quot;, &quot;a<u><strong>aa</strong></u>a&quot;, and &quot;aa<u><strong>aa</strong></u>&quot;. It can be shown that the maximum length achievable is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcdef&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaba&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;a&quot;: substrings &quot;<u><strong>a</strong></u>bcaba&quot;, &quot;abc<u><strong>a</strong></u>ba&quot;, and &quot;abcab<u><strong>a</strong></u>&quot;. It can be shown that the maximum length achievable is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 50</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Counting; Sliding Window
C++
class Solution { public: int maximumLength(string s) { int n = s.size(); int l = 0, r = n; auto check = [&](int x) { int cnt[26]{}; for (int i = 0; i < n;) { int j = i + 1; while (j < n && s[j] == s[i]) { ++j; } int k = s[i] - 'a'; cnt[k] += max(0, j - i - x + 1); if (cnt[k] >= 3) { return true; } i = j; } return false; }; while (l < r) { int mid = (l + r + 1) >> 1; if (check(mid)) { l = mid; } else { r = mid - 1; } } return l == 0 ? -1 : l; } };
2,981
Find Longest Special Substring That Occurs Thrice I
Medium
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p> <p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>&quot;abc&quot;</code> is not special, whereas the strings <code>&quot;ddd&quot;</code>, <code>&quot;zz&quot;</code>, and <code>&quot;f&quot;</code> are special.</p> <p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;aa&quot;: substrings &quot;<u><strong>aa</strong></u>aa&quot;, &quot;a<u><strong>aa</strong></u>a&quot;, and &quot;aa<u><strong>aa</strong></u>&quot;. It can be shown that the maximum length achievable is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcdef&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaba&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;a&quot;: substrings &quot;<u><strong>a</strong></u>bcaba&quot;, &quot;abc<u><strong>a</strong></u>ba&quot;, and &quot;abcab<u><strong>a</strong></u>&quot;. It can be shown that the maximum length achievable is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 50</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Counting; Sliding Window
Go
func maximumLength(s string) int { n := len(s) l, r := 0, n check := func(x int) bool { cnt := [26]int{} for i := 0; i < n; { j := i + 1 for j < n && s[j] == s[i] { j++ } k := s[i] - 'a' cnt[k] += max(0, j-i-x+1) if cnt[k] >= 3 { return true } i = j } return false } for l < r { mid := (l + r + 1) >> 1 if check(mid) { l = mid } else { r = mid - 1 } } if l == 0 { return -1 } return l }
2,981
Find Longest Special Substring That Occurs Thrice I
Medium
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p> <p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>&quot;abc&quot;</code> is not special, whereas the strings <code>&quot;ddd&quot;</code>, <code>&quot;zz&quot;</code>, and <code>&quot;f&quot;</code> are special.</p> <p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;aa&quot;: substrings &quot;<u><strong>aa</strong></u>aa&quot;, &quot;a<u><strong>aa</strong></u>a&quot;, and &quot;aa<u><strong>aa</strong></u>&quot;. It can be shown that the maximum length achievable is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcdef&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaba&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;a&quot;: substrings &quot;<u><strong>a</strong></u>bcaba&quot;, &quot;abc<u><strong>a</strong></u>ba&quot;, and &quot;abcab<u><strong>a</strong></u>&quot;. It can be shown that the maximum length achievable is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 50</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Counting; Sliding Window
Java
class Solution { private String s; private int n; public int maximumLength(String s) { this.s = s; n = s.length(); int l = 0, r = n; while (l < r) { int mid = (l + r + 1) >> 1; if (check(mid)) { l = mid; } else { r = mid - 1; } } return l == 0 ? -1 : l; } private boolean check(int x) { int[] cnt = new int[26]; for (int i = 0; i < n;) { int j = i + 1; while (j < n && s.charAt(j) == s.charAt(i)) { j++; } int k = s.charAt(i) - 'a'; cnt[k] += Math.max(0, j - i - x + 1); if (cnt[k] >= 3) { return true; } i = j; } return false; } }
2,981
Find Longest Special Substring That Occurs Thrice I
Medium
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p> <p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>&quot;abc&quot;</code> is not special, whereas the strings <code>&quot;ddd&quot;</code>, <code>&quot;zz&quot;</code>, and <code>&quot;f&quot;</code> are special.</p> <p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;aa&quot;: substrings &quot;<u><strong>aa</strong></u>aa&quot;, &quot;a<u><strong>aa</strong></u>a&quot;, and &quot;aa<u><strong>aa</strong></u>&quot;. It can be shown that the maximum length achievable is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcdef&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaba&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;a&quot;: substrings &quot;<u><strong>a</strong></u>bcaba&quot;, &quot;abc<u><strong>a</strong></u>ba&quot;, and &quot;abcab<u><strong>a</strong></u>&quot;. It can be shown that the maximum length achievable is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 50</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Counting; Sliding Window
Python
class Solution: def maximumLength(self, s: str) -> int: def check(x: int) -> bool: cnt = defaultdict(int) i = 0 while i < n: j = i + 1 while j < n and s[j] == s[i]: j += 1 cnt[s[i]] += max(0, j - i - x + 1) i = j return max(cnt.values()) >= 3 n = len(s) l, r = 0, n while l < r: mid = (l + r + 1) >> 1 if check(mid): l = mid else: r = mid - 1 return -1 if l == 0 else l
2,981
Find Longest Special Substring That Occurs Thrice I
Medium
<p>You are given a string <code>s</code> that consists of lowercase English letters.</p> <p>A string is called <strong>special</strong> if it is made up of only a single character. For example, the string <code>&quot;abc&quot;</code> is not special, whereas the strings <code>&quot;ddd&quot;</code>, <code>&quot;zz&quot;</code>, and <code>&quot;f&quot;</code> are special.</p> <p>Return <em>the length of the <strong>longest special substring</strong> of </em><code>s</code> <em>which occurs <strong>at least thrice</strong></em>, <em>or </em><code>-1</code><em> if no special substring occurs at least thrice</em>.</p> <p>A <strong>substring</strong> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;aa&quot;: substrings &quot;<u><strong>aa</strong></u>aa&quot;, &quot;a<u><strong>aa</strong></u>a&quot;, and &quot;aa<u><strong>aa</strong></u>&quot;. It can be shown that the maximum length achievable is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcdef&quot; <strong>Output:</strong> -1 <strong>Explanation:</strong> There exists no special substring which occurs at least thrice. Hence return -1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaba&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> The longest special substring which occurs thrice is &quot;a&quot;: substrings &quot;<u><strong>a</strong></u>bcaba&quot;, &quot;abc<u><strong>a</strong></u>ba&quot;, and &quot;abcab<u><strong>a</strong></u>&quot;. It can be shown that the maximum length achievable is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= s.length &lt;= 50</code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Counting; Sliding Window
TypeScript
function maximumLength(s: string): number { const n = s.length; let [l, r] = [0, n]; const check = (x: number): boolean => { const cnt: number[] = Array(26).fill(0); for (let i = 0; i < n; ) { let j = i + 1; while (j < n && s[j] === s[i]) { j++; } const k = s[i].charCodeAt(0) - 'a'.charCodeAt(0); cnt[k] += Math.max(0, j - i - x + 1); if (cnt[k] >= 3) { return true; } i = j; } return false; }; while (l < r) { const mid = (l + r + 1) >> 1; if (check(mid)) { l = mid; } else { r = mid - 1; } } return l === 0 ? -1 : l; }