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,829
Determine the Minimum Sum of a k-avoiding Array
Medium
<p>You are given two integers,&nbsp;<code>n</code> and <code>k</code>.</p> <p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p> <p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18. It can be proven that there is no k-avoiding array with a sum less than 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 6 <strong>Output:</strong> 3 <strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3. It can be proven that there is no k-avoiding array with a sum less than 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 50</code></li> </ul>
Greedy; Math
TypeScript
function minimumSum(n: number, k: number): number { let s = 0; let i = 1; const vis: boolean[] = Array(n + k + 1).fill(false); while (n--) { while (vis[i]) { ++i; } if (k >= i) { vis[k - i] = true; } s += i++; } return s; }
2,830
Maximize the Profit as the Salesman
Medium
<p>You are given an integer <code>n</code> representing the number of houses on a number line, numbered from <code>0</code> to <code>n - 1</code>.</p> <p>Additionally, you are given a 2D integer array <code>offers</code> where <code>offers[i] = [start<sub>i</sub>, end<sub>i</sub>, gold<sub>i</sub>]</code>, indicating that <code>i<sup>th</sup></code> buyer wants to buy all the houses from <code>start<sub>i</sub></code> to <code>end<sub>i</sub></code> for <code>gold<sub>i</sub></code> amount of gold.</p> <p>As a salesman, your goal is to <strong>maximize</strong> your earnings by strategically selecting and selling houses to buyers.</p> <p>Return <em>the maximum amount of gold you can earn</em>.</p> <p><strong>Note</strong> that different buyers can&#39;t buy the same house, and some houses may remain unsold.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,0] to 1<sup>st</sup> buyer for 1 gold and houses in the range [1,3] to 3<sup>rd</sup> buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]] <strong>Output:</strong> 10 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,2] to 2<sup>nd</sup> buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. </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;= offers.length &lt;= 10<sup>5</sup></code></li> <li><code>offers[i].length == 3</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>1 &lt;= gold<sub>i</sub> &lt;= 10<sup>3</sup></code></li> </ul>
Array; Hash Table; Binary Search; Dynamic Programming; Sorting
C++
class Solution { public: int maximizeTheProfit(int n, vector<vector<int>>& offers) { sort(offers.begin(), offers.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); n = offers.size(); vector<int> f(n + 1); vector<int> g; for (auto& o : offers) { g.push_back(o[1]); } for (int i = 1; i <= n; ++i) { auto o = offers[i - 1]; int j = lower_bound(g.begin(), g.end(), o[0]) - g.begin(); f[i] = max(f[i - 1], f[j] + o[2]); } return f[n]; } };
2,830
Maximize the Profit as the Salesman
Medium
<p>You are given an integer <code>n</code> representing the number of houses on a number line, numbered from <code>0</code> to <code>n - 1</code>.</p> <p>Additionally, you are given a 2D integer array <code>offers</code> where <code>offers[i] = [start<sub>i</sub>, end<sub>i</sub>, gold<sub>i</sub>]</code>, indicating that <code>i<sup>th</sup></code> buyer wants to buy all the houses from <code>start<sub>i</sub></code> to <code>end<sub>i</sub></code> for <code>gold<sub>i</sub></code> amount of gold.</p> <p>As a salesman, your goal is to <strong>maximize</strong> your earnings by strategically selecting and selling houses to buyers.</p> <p>Return <em>the maximum amount of gold you can earn</em>.</p> <p><strong>Note</strong> that different buyers can&#39;t buy the same house, and some houses may remain unsold.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,0] to 1<sup>st</sup> buyer for 1 gold and houses in the range [1,3] to 3<sup>rd</sup> buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]] <strong>Output:</strong> 10 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,2] to 2<sup>nd</sup> buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. </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;= offers.length &lt;= 10<sup>5</sup></code></li> <li><code>offers[i].length == 3</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>1 &lt;= gold<sub>i</sub> &lt;= 10<sup>3</sup></code></li> </ul>
Array; Hash Table; Binary Search; Dynamic Programming; Sorting
Go
func maximizeTheProfit(n int, offers [][]int) int { sort.Slice(offers, func(i, j int) bool { return offers[i][1] < offers[j][1] }) n = len(offers) f := make([]int, n+1) g := []int{} for _, o := range offers { g = append(g, o[1]) } for i := 1; i <= n; i++ { j := sort.SearchInts(g, offers[i-1][0]) f[i] = max(f[i-1], f[j]+offers[i-1][2]) } return f[n] }
2,830
Maximize the Profit as the Salesman
Medium
<p>You are given an integer <code>n</code> representing the number of houses on a number line, numbered from <code>0</code> to <code>n - 1</code>.</p> <p>Additionally, you are given a 2D integer array <code>offers</code> where <code>offers[i] = [start<sub>i</sub>, end<sub>i</sub>, gold<sub>i</sub>]</code>, indicating that <code>i<sup>th</sup></code> buyer wants to buy all the houses from <code>start<sub>i</sub></code> to <code>end<sub>i</sub></code> for <code>gold<sub>i</sub></code> amount of gold.</p> <p>As a salesman, your goal is to <strong>maximize</strong> your earnings by strategically selecting and selling houses to buyers.</p> <p>Return <em>the maximum amount of gold you can earn</em>.</p> <p><strong>Note</strong> that different buyers can&#39;t buy the same house, and some houses may remain unsold.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,0] to 1<sup>st</sup> buyer for 1 gold and houses in the range [1,3] to 3<sup>rd</sup> buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]] <strong>Output:</strong> 10 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,2] to 2<sup>nd</sup> buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. </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;= offers.length &lt;= 10<sup>5</sup></code></li> <li><code>offers[i].length == 3</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>1 &lt;= gold<sub>i</sub> &lt;= 10<sup>3</sup></code></li> </ul>
Array; Hash Table; Binary Search; Dynamic Programming; Sorting
Java
class Solution { public int maximizeTheProfit(int n, List<List<Integer>> offers) { offers.sort((a, b) -> a.get(1) - b.get(1)); n = offers.size(); int[] f = new int[n + 1]; int[] g = new int[n]; for (int i = 0; i < n; ++i) { g[i] = offers.get(i).get(1); } for (int i = 1; i <= n; ++i) { var o = offers.get(i - 1); int j = search(g, o.get(0)); f[i] = Math.max(f[i - 1], f[j] + o.get(2)); } return f[n]; } private int search(int[] nums, int x) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; } }
2,830
Maximize the Profit as the Salesman
Medium
<p>You are given an integer <code>n</code> representing the number of houses on a number line, numbered from <code>0</code> to <code>n - 1</code>.</p> <p>Additionally, you are given a 2D integer array <code>offers</code> where <code>offers[i] = [start<sub>i</sub>, end<sub>i</sub>, gold<sub>i</sub>]</code>, indicating that <code>i<sup>th</sup></code> buyer wants to buy all the houses from <code>start<sub>i</sub></code> to <code>end<sub>i</sub></code> for <code>gold<sub>i</sub></code> amount of gold.</p> <p>As a salesman, your goal is to <strong>maximize</strong> your earnings by strategically selecting and selling houses to buyers.</p> <p>Return <em>the maximum amount of gold you can earn</em>.</p> <p><strong>Note</strong> that different buyers can&#39;t buy the same house, and some houses may remain unsold.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,0] to 1<sup>st</sup> buyer for 1 gold and houses in the range [1,3] to 3<sup>rd</sup> buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]] <strong>Output:</strong> 10 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,2] to 2<sup>nd</sup> buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. </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;= offers.length &lt;= 10<sup>5</sup></code></li> <li><code>offers[i].length == 3</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>1 &lt;= gold<sub>i</sub> &lt;= 10<sup>3</sup></code></li> </ul>
Array; Hash Table; Binary Search; Dynamic Programming; Sorting
Python
class Solution: def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: offers.sort(key=lambda x: x[1]) f = [0] * (len(offers) + 1) g = [x[1] for x in offers] for i, (s, _, v) in enumerate(offers, 1): j = bisect_left(g, s) f[i] = max(f[i - 1], f[j] + v) return f[-1]
2,830
Maximize the Profit as the Salesman
Medium
<p>You are given an integer <code>n</code> representing the number of houses on a number line, numbered from <code>0</code> to <code>n - 1</code>.</p> <p>Additionally, you are given a 2D integer array <code>offers</code> where <code>offers[i] = [start<sub>i</sub>, end<sub>i</sub>, gold<sub>i</sub>]</code>, indicating that <code>i<sup>th</sup></code> buyer wants to buy all the houses from <code>start<sub>i</sub></code> to <code>end<sub>i</sub></code> for <code>gold<sub>i</sub></code> amount of gold.</p> <p>As a salesman, your goal is to <strong>maximize</strong> your earnings by strategically selecting and selling houses to buyers.</p> <p>Return <em>the maximum amount of gold you can earn</em>.</p> <p><strong>Note</strong> that different buyers can&#39;t buy the same house, and some houses may remain unsold.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,0] to 1<sup>st</sup> buyer for 1 gold and houses in the range [1,3] to 3<sup>rd</sup> buyer for 2 golds. It can be proven that 3 is the maximum amount of gold we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]] <strong>Output:</strong> 10 <strong>Explanation:</strong> There are 5 houses numbered from 0 to 4 and there are 3 purchase offers. We sell houses in the range [0,2] to 2<sup>nd</sup> buyer for 10 golds. It can be proven that 10 is the maximum amount of gold we can achieve. </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;= offers.length &lt;= 10<sup>5</sup></code></li> <li><code>offers[i].length == 3</code></li> <li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= n - 1</code></li> <li><code>1 &lt;= gold<sub>i</sub> &lt;= 10<sup>3</sup></code></li> </ul>
Array; Hash Table; Binary Search; Dynamic Programming; Sorting
TypeScript
function maximizeTheProfit(n: number, offers: number[][]): number { offers.sort((a, b) => a[1] - b[1]); n = offers.length; const f: number[] = Array(n + 1).fill(0); const g = offers.map(x => x[1]); const search = (x: number) => { let l = 0; let r = n; while (l < r) { const mid = (l + r) >> 1; if (g[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; for (let i = 1; i <= n; ++i) { const j = search(offers[i - 1][0]); f[i] = Math.max(f[i - 1], f[j] + offers[i - 1][2]); } return f[n]; }
2,831
Find the Longest Equal Subarray
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>A subarray is called <strong>equal</strong> if all of its elements are equal. Note that the empty subarray is an <strong>equal</strong> subarray.</p> <p>Return <em>the length of the <strong>longest</strong> possible equal subarray after deleting <strong>at most</strong> </em><code>k</code><em> elements from </em><code>nums</code>.</p> <p>A <b>subarray</b> is a contiguous, possibly 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,3,2,3,1,3], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 4. After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. It can be proven that no longer equal subarrays can be created. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,1,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 3. After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. It can be proven that no longer equal subarrays can be created. </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;= nums.length</code></li> <li><code>0 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Binary Search; Sliding Window
C++
class Solution { public: int longestEqualSubarray(vector<int>& nums, int k) { unordered_map<int, int> cnt; int mx = 0, l = 0; for (int r = 0; r < nums.size(); ++r) { mx = max(mx, ++cnt[nums[r]]); if (r - l + 1 - mx > k) { --cnt[nums[l++]]; } } return mx; } };
2,831
Find the Longest Equal Subarray
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>A subarray is called <strong>equal</strong> if all of its elements are equal. Note that the empty subarray is an <strong>equal</strong> subarray.</p> <p>Return <em>the length of the <strong>longest</strong> possible equal subarray after deleting <strong>at most</strong> </em><code>k</code><em> elements from </em><code>nums</code>.</p> <p>A <b>subarray</b> is a contiguous, possibly 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,3,2,3,1,3], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 4. After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. It can be proven that no longer equal subarrays can be created. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,1,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 3. After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. It can be proven that no longer equal subarrays can be created. </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;= nums.length</code></li> <li><code>0 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Binary Search; Sliding Window
Go
func longestEqualSubarray(nums []int, k int) int { cnt := map[int]int{} mx, l := 0, 0 for r, x := range nums { cnt[x]++ mx = max(mx, cnt[x]) if r-l+1-mx > k { cnt[nums[l]]-- l++ } } return mx }
2,831
Find the Longest Equal Subarray
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>A subarray is called <strong>equal</strong> if all of its elements are equal. Note that the empty subarray is an <strong>equal</strong> subarray.</p> <p>Return <em>the length of the <strong>longest</strong> possible equal subarray after deleting <strong>at most</strong> </em><code>k</code><em> elements from </em><code>nums</code>.</p> <p>A <b>subarray</b> is a contiguous, possibly 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,3,2,3,1,3], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 4. After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. It can be proven that no longer equal subarrays can be created. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,1,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 3. After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. It can be proven that no longer equal subarrays can be created. </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;= nums.length</code></li> <li><code>0 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Binary Search; Sliding Window
Java
class Solution { public int longestEqualSubarray(List<Integer> nums, int k) { Map<Integer, Integer> cnt = new HashMap<>(); int mx = 0, l = 0; for (int r = 0; r < nums.size(); ++r) { cnt.merge(nums.get(r), 1, Integer::sum); mx = Math.max(mx, cnt.get(nums.get(r))); if (r - l + 1 - mx > k) { cnt.merge(nums.get(l++), -1, Integer::sum); } } return mx; } }
2,831
Find the Longest Equal Subarray
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>A subarray is called <strong>equal</strong> if all of its elements are equal. Note that the empty subarray is an <strong>equal</strong> subarray.</p> <p>Return <em>the length of the <strong>longest</strong> possible equal subarray after deleting <strong>at most</strong> </em><code>k</code><em> elements from </em><code>nums</code>.</p> <p>A <b>subarray</b> is a contiguous, possibly 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,3,2,3,1,3], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 4. After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. It can be proven that no longer equal subarrays can be created. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,1,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 3. After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. It can be proven that no longer equal subarrays can be created. </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;= nums.length</code></li> <li><code>0 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Binary Search; Sliding Window
Python
class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: cnt = Counter() l = 0 mx = 0 for r, x in enumerate(nums): cnt[x] += 1 mx = max(mx, cnt[x]) if r - l + 1 - mx > k: cnt[nums[l]] -= 1 l += 1 return mx
2,831
Find the Longest Equal Subarray
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>A subarray is called <strong>equal</strong> if all of its elements are equal. Note that the empty subarray is an <strong>equal</strong> subarray.</p> <p>Return <em>the length of the <strong>longest</strong> possible equal subarray after deleting <strong>at most</strong> </em><code>k</code><em> elements from </em><code>nums</code>.</p> <p>A <b>subarray</b> is a contiguous, possibly 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,3,2,3,1,3], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 4. After deleting them, nums becomes equal to [1, 3, 3, 3]. The longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3. It can be proven that no longer equal subarrays can be created. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,1,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> It&#39;s optimal to delete the elements at index 2 and index 3. After deleting them, nums becomes equal to [1, 1, 1, 1]. The array itself is an equal subarray, so the answer is 4. It can be proven that no longer equal subarrays can be created. </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;= nums.length</code></li> <li><code>0 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Binary Search; Sliding Window
TypeScript
function longestEqualSubarray(nums: number[], k: number): number { const cnt: Map<number, number> = new Map(); let mx = 0; let l = 0; for (let r = 0; r < nums.length; ++r) { cnt.set(nums[r], (cnt.get(nums[r]) ?? 0) + 1); mx = Math.max(mx, cnt.get(nums[r])!); if (r - l + 1 - mx > k) { cnt.set(nums[l], cnt.get(nums[l])! - 1); ++l; } } return mx; }
2,832
Maximal Range That Each Element Is Maximum in It
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <b>distinct </b>integers.</p> <p>Let us define a <strong>0-indexed </strong>array <code>ans</code> of the same length as <code>nums</code> in the following way:</p> <ul> <li><code>ans[i]</code> is the <strong>maximum</strong> length of a subarray <code>nums[l..r]</code>, such that the maximum element in that subarray is equal to <code>nums[i]</code>.</li> </ul> <p>Return<em> the array </em><code>ans</code>.</p> <p><strong>Note</strong> that a <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,4,3,6] <strong>Output:</strong> [1,4,2,1,5] <strong>Explanation:</strong> For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1. For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4. For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2. For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1. For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> For nums[i] the longest subarray in which it&#39;s the maximum is nums[0..i] so ans[i] = i + 1. </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>5</sup></code></li> <li>All elements in <code>nums</code> are distinct.</li> </ul>
Stack; Array; Monotonic Stack
C++
class Solution { public: vector<int> maximumLengthOfRanges(vector<int>& nums) { int n = nums.size(); vector<int> left(n, -1); vector<int> right(n, n); stack<int> stk; for (int i = 0; i < n; ++i) { while (!stk.empty() && nums[stk.top()] <= nums[i]) { stk.pop(); } if (!stk.empty()) { left[i] = stk.top(); } stk.push(i); } stk = stack<int>(); for (int i = n - 1; ~i; --i) { while (!stk.empty() && nums[stk.top()] <= nums[i]) { stk.pop(); } if (!stk.empty()) { right[i] = stk.top(); } stk.push(i); } vector<int> ans(n); for (int i = 0; i < n; ++i) { ans[i] = right[i] - left[i] - 1; } return ans; } };
2,832
Maximal Range That Each Element Is Maximum in It
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <b>distinct </b>integers.</p> <p>Let us define a <strong>0-indexed </strong>array <code>ans</code> of the same length as <code>nums</code> in the following way:</p> <ul> <li><code>ans[i]</code> is the <strong>maximum</strong> length of a subarray <code>nums[l..r]</code>, such that the maximum element in that subarray is equal to <code>nums[i]</code>.</li> </ul> <p>Return<em> the array </em><code>ans</code>.</p> <p><strong>Note</strong> that a <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,4,3,6] <strong>Output:</strong> [1,4,2,1,5] <strong>Explanation:</strong> For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1. For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4. For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2. For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1. For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> For nums[i] the longest subarray in which it&#39;s the maximum is nums[0..i] so ans[i] = i + 1. </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>5</sup></code></li> <li>All elements in <code>nums</code> are distinct.</li> </ul>
Stack; Array; Monotonic Stack
Go
func maximumLengthOfRanges(nums []int) []int { n := len(nums) left := make([]int, n) right := make([]int, n) for i := range left { left[i] = -1 right[i] = n } stk := []int{} for i, x := range nums { for len(stk) > 0 && nums[stk[len(stk)-1]] <= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { left[i] = stk[len(stk)-1] } stk = append(stk, i) } stk = []int{} for i := n - 1; i >= 0; i-- { x := nums[i] for len(stk) > 0 && nums[stk[len(stk)-1]] <= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { right[i] = stk[len(stk)-1] } stk = append(stk, i) } ans := make([]int, n) for i := range ans { ans[i] = right[i] - left[i] - 1 } return ans }
2,832
Maximal Range That Each Element Is Maximum in It
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <b>distinct </b>integers.</p> <p>Let us define a <strong>0-indexed </strong>array <code>ans</code> of the same length as <code>nums</code> in the following way:</p> <ul> <li><code>ans[i]</code> is the <strong>maximum</strong> length of a subarray <code>nums[l..r]</code>, such that the maximum element in that subarray is equal to <code>nums[i]</code>.</li> </ul> <p>Return<em> the array </em><code>ans</code>.</p> <p><strong>Note</strong> that a <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,4,3,6] <strong>Output:</strong> [1,4,2,1,5] <strong>Explanation:</strong> For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1. For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4. For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2. For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1. For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> For nums[i] the longest subarray in which it&#39;s the maximum is nums[0..i] so ans[i] = i + 1. </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>5</sup></code></li> <li>All elements in <code>nums</code> are distinct.</li> </ul>
Stack; Array; Monotonic Stack
Java
class Solution { public int[] maximumLengthOfRanges(int[] nums) { int n = nums.length; int[] left = new int[n]; int[] right = new int[n]; Arrays.fill(left, -1); Arrays.fill(right, n); Deque<Integer> stk = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { stk.pop(); } if (!stk.isEmpty()) { left[i] = stk.peek(); } stk.push(i); } stk.clear(); for (int i = n - 1; i >= 0; --i) { while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) { stk.pop(); } if (!stk.isEmpty()) { right[i] = stk.peek(); } stk.push(i); } int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = right[i] - left[i] - 1; } return ans; } }
2,832
Maximal Range That Each Element Is Maximum in It
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <b>distinct </b>integers.</p> <p>Let us define a <strong>0-indexed </strong>array <code>ans</code> of the same length as <code>nums</code> in the following way:</p> <ul> <li><code>ans[i]</code> is the <strong>maximum</strong> length of a subarray <code>nums[l..r]</code>, such that the maximum element in that subarray is equal to <code>nums[i]</code>.</li> </ul> <p>Return<em> the array </em><code>ans</code>.</p> <p><strong>Note</strong> that a <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,4,3,6] <strong>Output:</strong> [1,4,2,1,5] <strong>Explanation:</strong> For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1. For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4. For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2. For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1. For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> For nums[i] the longest subarray in which it&#39;s the maximum is nums[0..i] so ans[i] = i + 1. </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>5</sup></code></li> <li>All elements in <code>nums</code> are distinct.</li> </ul>
Stack; Array; Monotonic Stack
Python
class Solution: def maximumLengthOfRanges(self, nums: List[int]) -> List[int]: n = len(nums) left = [-1] * n right = [n] * n stk = [] for i, x in enumerate(nums): while stk and nums[stk[-1]] <= x: stk.pop() if stk: left[i] = stk[-1] stk.append(i) stk = [] for i in range(n - 1, -1, -1): while stk and nums[stk[-1]] <= nums[i]: stk.pop() if stk: right[i] = stk[-1] stk.append(i) return [r - l - 1 for l, r in zip(left, right)]
2,832
Maximal Range That Each Element Is Maximum in It
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of <b>distinct </b>integers.</p> <p>Let us define a <strong>0-indexed </strong>array <code>ans</code> of the same length as <code>nums</code> in the following way:</p> <ul> <li><code>ans[i]</code> is the <strong>maximum</strong> length of a subarray <code>nums[l..r]</code>, such that the maximum element in that subarray is equal to <code>nums[i]</code>.</li> </ul> <p>Return<em> the array </em><code>ans</code>.</p> <p><strong>Note</strong> that a <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,4,3,6] <strong>Output:</strong> [1,4,2,1,5] <strong>Explanation:</strong> For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1. For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4. For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2. For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1. For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [1,2,3,4,5] <strong>Explanation:</strong> For nums[i] the longest subarray in which it&#39;s the maximum is nums[0..i] so ans[i] = i + 1. </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>5</sup></code></li> <li>All elements in <code>nums</code> are distinct.</li> </ul>
Stack; Array; Monotonic Stack
TypeScript
function maximumLengthOfRanges(nums: number[]): number[] { const n = nums.length; const left: number[] = Array(n).fill(-1); const right: number[] = Array(n).fill(n); const stk: number[] = []; for (let i = 0; i < n; ++i) { while (stk.length && nums[stk.at(-1)] <= nums[i]) { stk.pop(); } if (stk.length) { left[i] = stk.at(-1); } stk.push(i); } stk.length = 0; for (let i = n - 1; i >= 0; --i) { while (stk.length && nums[stk.at(-1)] <= nums[i]) { stk.pop(); } if (stk.length) { right[i] = stk.at(-1); } stk.push(i); } return left.map((l, i) => right[i] - l - 1); }
2,833
Furthest Point From Origin
Easy
<p>You are given a string <code>moves</code> of length <code>n</code> consisting only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, and <code>&#39;_&#39;</code>. The string represents your movement on a number line starting from the origin <code>0</code>.</p> <p>In the <code>i<sup>th</sup></code> move, you can choose one of the following directions:</p> <ul> <li>move to the left if <code>moves[i] = &#39;L&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> <li>move to the right if <code>moves[i] = &#39;R&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> </ul> <p>Return <em>the <strong>distance from the origin</strong> of the <strong>furthest</strong> point you can get to after </em><code>n</code><em> moves</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> moves = &quot;L_RL__R&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves &quot;LLRLLLR&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_R__LL_&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves &quot;LRLLLLL&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_______&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves &quot;RRRRRRR&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= moves.length == n &lt;= 50</code></li> <li><code>moves</code> consists only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code> and <code>&#39;_&#39;</code>.</li> </ul>
String; Counting
C++
class Solution { public: int furthestDistanceFromOrigin(string moves) { auto cnt = [&](char c) { return count(moves.begin(), moves.end(), c); }; return abs(cnt('L') - cnt('R')) + cnt('_'); } };
2,833
Furthest Point From Origin
Easy
<p>You are given a string <code>moves</code> of length <code>n</code> consisting only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, and <code>&#39;_&#39;</code>. The string represents your movement on a number line starting from the origin <code>0</code>.</p> <p>In the <code>i<sup>th</sup></code> move, you can choose one of the following directions:</p> <ul> <li>move to the left if <code>moves[i] = &#39;L&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> <li>move to the right if <code>moves[i] = &#39;R&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> </ul> <p>Return <em>the <strong>distance from the origin</strong> of the <strong>furthest</strong> point you can get to after </em><code>n</code><em> moves</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> moves = &quot;L_RL__R&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves &quot;LLRLLLR&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_R__LL_&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves &quot;LRLLLLL&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_______&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves &quot;RRRRRRR&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= moves.length == n &lt;= 50</code></li> <li><code>moves</code> consists only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code> and <code>&#39;_&#39;</code>.</li> </ul>
String; Counting
Go
func furthestDistanceFromOrigin(moves string) int { count := func(c string) int { return strings.Count(moves, c) } return abs(count("L")-count("R")) + count("_") } func abs(x int) int { if x < 0 { return -x } return x }
2,833
Furthest Point From Origin
Easy
<p>You are given a string <code>moves</code> of length <code>n</code> consisting only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, and <code>&#39;_&#39;</code>. The string represents your movement on a number line starting from the origin <code>0</code>.</p> <p>In the <code>i<sup>th</sup></code> move, you can choose one of the following directions:</p> <ul> <li>move to the left if <code>moves[i] = &#39;L&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> <li>move to the right if <code>moves[i] = &#39;R&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> </ul> <p>Return <em>the <strong>distance from the origin</strong> of the <strong>furthest</strong> point you can get to after </em><code>n</code><em> moves</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> moves = &quot;L_RL__R&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves &quot;LLRLLLR&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_R__LL_&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves &quot;LRLLLLL&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_______&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves &quot;RRRRRRR&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= moves.length == n &lt;= 50</code></li> <li><code>moves</code> consists only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code> and <code>&#39;_&#39;</code>.</li> </ul>
String; Counting
Java
class Solution { public int furthestDistanceFromOrigin(String moves) { return Math.abs(count(moves, 'L') - count(moves, 'R')) + count(moves, '_'); } private int count(String s, char c) { int cnt = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == c) { ++cnt; } } return cnt; } }
2,833
Furthest Point From Origin
Easy
<p>You are given a string <code>moves</code> of length <code>n</code> consisting only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, and <code>&#39;_&#39;</code>. The string represents your movement on a number line starting from the origin <code>0</code>.</p> <p>In the <code>i<sup>th</sup></code> move, you can choose one of the following directions:</p> <ul> <li>move to the left if <code>moves[i] = &#39;L&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> <li>move to the right if <code>moves[i] = &#39;R&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> </ul> <p>Return <em>the <strong>distance from the origin</strong> of the <strong>furthest</strong> point you can get to after </em><code>n</code><em> moves</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> moves = &quot;L_RL__R&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves &quot;LLRLLLR&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_R__LL_&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves &quot;LRLLLLL&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_______&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves &quot;RRRRRRR&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= moves.length == n &lt;= 50</code></li> <li><code>moves</code> consists only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code> and <code>&#39;_&#39;</code>.</li> </ul>
String; Counting
Python
class Solution: def furthestDistanceFromOrigin(self, moves: str) -> int: return abs(moves.count("L") - moves.count("R")) + moves.count("_")
2,833
Furthest Point From Origin
Easy
<p>You are given a string <code>moves</code> of length <code>n</code> consisting only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, and <code>&#39;_&#39;</code>. The string represents your movement on a number line starting from the origin <code>0</code>.</p> <p>In the <code>i<sup>th</sup></code> move, you can choose one of the following directions:</p> <ul> <li>move to the left if <code>moves[i] = &#39;L&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> <li>move to the right if <code>moves[i] = &#39;R&#39;</code> or <code>moves[i] = &#39;_&#39;</code></li> </ul> <p>Return <em>the <strong>distance from the origin</strong> of the <strong>furthest</strong> point you can get to after </em><code>n</code><em> moves</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> moves = &quot;L_RL__R&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves &quot;LLRLLLR&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_R__LL_&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves &quot;LRLLLLL&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> moves = &quot;_______&quot; <strong>Output:</strong> 7 <strong>Explanation:</strong> The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves &quot;RRRRRRR&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= moves.length == n &lt;= 50</code></li> <li><code>moves</code> consists only of characters <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code> and <code>&#39;_&#39;</code>.</li> </ul>
String; Counting
TypeScript
function furthestDistanceFromOrigin(moves: string): number { const count = (c: string) => moves.split('').filter(x => x === c).length; return Math.abs(count('L') - count('R')) + count('_'); }
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
C++
class Solution { public: int minimumPossibleSum(int n, int target) { const int mod = 1e9 + 7; int m = target / 2; if (n <= m) { return (1LL + n) * n / 2 % mod; } long long a = (1LL + m) * m / 2 % mod; long long b = (1LL * target + target + n - m - 1) * (n - m) / 2 % mod; return (a + b) % mod; } };
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
C#
public class Solution { public int MinimumPossibleSum(int n, int target) { const int mod = (int) 1e9 + 7; int m = target / 2; if (n <= m) { return (int) ((1L + n) * n / 2 % mod); } long a = (1L + m) * m / 2 % mod; long b = ((1L * target + target + n - m - 1) * (n - m) / 2) % mod; return (int) ((a + b) % mod); } }
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
Go
func minimumPossibleSum(n int, target int) int { const mod int = 1e9 + 7 m := target / 2 if n <= m { return (n + 1) * n / 2 % mod } a := (m + 1) * m / 2 % mod b := (target + target + n - m - 1) * (n - m) / 2 % mod return (a + b) % mod }
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
Java
class Solution { public int minimumPossibleSum(int n, int target) { final int mod = (int) 1e9 + 7; int m = target / 2; if (n <= m) { return (int) ((1L + n) * n / 2 % mod); } long a = (1L + m) * m / 2 % mod; long b = ((1L * target + target + n - m - 1) * (n - m) / 2) % mod; return (int) ((a + b) % mod); } }
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
Python
class Solution: def minimumPossibleSum(self, n: int, target: int) -> int: mod = 10**9 + 7 m = target // 2 if n <= m: return ((1 + n) * n // 2) % mod return ((1 + m) * m // 2 + (target + target + n - m - 1) * (n - m) // 2) % mod
2,834
Find the Minimum Possible Sum of a Beautiful Array
Medium
<p>You are given positive integers <code>n</code> and <code>target</code>.</p> <p>An array <code>nums</code> is <strong>beautiful</strong> if it meets the following conditions:</p> <ul> <li><code>nums.length == n</code>.</li> <li><code>nums</code> consists of pairwise <strong>distinct</strong> <strong>positive</strong> integers.</li> <li>There doesn&#39;t exist two <strong>distinct</strong> indices, <code>i</code> and <code>j</code>, in the range <code>[0, n - 1]</code>, such that <code>nums[i] + nums[j] == target</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> possible sum that a beautiful array could have modulo </em><code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2, target = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can see that nums = [1,3] is beautiful. - The array nums has length n = 2. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 4 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, target = 3 <strong>Output:</strong> 8 <strong>Explanation:</strong> We can see that nums = [1,3,4] is beautiful. - The array nums has length n = 3. - The array nums consists of pairwise distinct positive integers. - There doesn&#39;t exist two distinct indices, i and j, with nums[i] + nums[j] == 3. It can be proven that 8 is the minimum possible sum that a beautiful array could have. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, target = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can see, that nums = [1] is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Math
TypeScript
function minimumPossibleSum(n: number, target: number): number { const mod = 10 ** 9 + 7; const m = target >> 1; if (n <= m) { return (((1 + n) * n) / 2) % mod; } return (((1 + m) * m) / 2 + ((target + target + n - m - 1) * (n - m)) / 2) % mod; }
2,835
Minimum Operations to Form Subsequence With Target Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>non-negative</strong> powers of <code>2</code>, and an integer <code>target</code>.</p> <p>In one operation, you must apply the following changes to the array:</p> <ul> <li>Choose any element of the array <code>nums[i]</code> such that <code>nums[i] &gt; 1</code>.</li> <li>Remove <code>nums[i]</code> from the array.</li> <li>Add <strong>two</strong> occurrences of <code>nums[i] / 2</code> to the <strong>end</strong> of <code>nums</code>.</li> </ul> <p>Return the <em><strong>minimum number of operations</strong> you need to perform so that </em><code>nums</code><em> contains a <strong>subsequence</strong> whose elements sum to</em> <code>target</code>. If it is impossible to obtain such a subsequence, return <code>-1</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,8], target = 7 <strong>Output:</strong> 1 <strong>Explanation:</strong> In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. At this stage, nums contains the subsequence [1,2,4] which sums up to 7. It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1,2], target = 12 <strong>Output:</strong> 2 <strong>Explanation:</strong> In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1], target = 35 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that no sequence of operations results in a subsequence that sums up to 35. </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;= 2<sup>30</sup></code></li> <li><code>nums</code> consists only of non-negative powers of two.</li> <li><code>1 &lt;= target &lt; 2<sup>31</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
C++
class Solution { public: int minOperations(vector<int>& nums, int target) { long long s = 0; int cnt[32]{}; for (int x : nums) { s += x; for (int i = 0; i < 32; ++i) { if (x >> i & 1) { ++cnt[i]; } } } if (s < target) { return -1; } int i = 0, j = 0; int ans = 0; while (1) { while (i < 32 && (target >> i & 1) == 0) { ++i; } if (i == 32) { return ans; } while (j < i) { cnt[j + 1] += cnt[j] / 2; cnt[j] %= 2; ++j; } while (cnt[j] == 0) { cnt[j] = 1; ++j; } ans += j - i; --cnt[j]; j = i; ++i; } } };
2,835
Minimum Operations to Form Subsequence With Target Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>non-negative</strong> powers of <code>2</code>, and an integer <code>target</code>.</p> <p>In one operation, you must apply the following changes to the array:</p> <ul> <li>Choose any element of the array <code>nums[i]</code> such that <code>nums[i] &gt; 1</code>.</li> <li>Remove <code>nums[i]</code> from the array.</li> <li>Add <strong>two</strong> occurrences of <code>nums[i] / 2</code> to the <strong>end</strong> of <code>nums</code>.</li> </ul> <p>Return the <em><strong>minimum number of operations</strong> you need to perform so that </em><code>nums</code><em> contains a <strong>subsequence</strong> whose elements sum to</em> <code>target</code>. If it is impossible to obtain such a subsequence, return <code>-1</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,8], target = 7 <strong>Output:</strong> 1 <strong>Explanation:</strong> In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. At this stage, nums contains the subsequence [1,2,4] which sums up to 7. It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1,2], target = 12 <strong>Output:</strong> 2 <strong>Explanation:</strong> In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1], target = 35 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that no sequence of operations results in a subsequence that sums up to 35. </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;= 2<sup>30</sup></code></li> <li><code>nums</code> consists only of non-negative powers of two.</li> <li><code>1 &lt;= target &lt; 2<sup>31</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Go
func minOperations(nums []int, target int) (ans int) { s := 0 cnt := [32]int{} for _, x := range nums { s += x for i := 0; i < 32; i++ { if x>>i&1 > 0 { cnt[i]++ } } } if s < target { return -1 } var i, j int for { for i < 32 && target>>i&1 == 0 { i++ } if i == 32 { return } for j < i { cnt[j+1] += cnt[j] >> 1 cnt[j] %= 2 j++ } for cnt[j] == 0 { cnt[j] = 1 j++ } ans += j - i cnt[j]-- j = i i++ } }
2,835
Minimum Operations to Form Subsequence With Target Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>non-negative</strong> powers of <code>2</code>, and an integer <code>target</code>.</p> <p>In one operation, you must apply the following changes to the array:</p> <ul> <li>Choose any element of the array <code>nums[i]</code> such that <code>nums[i] &gt; 1</code>.</li> <li>Remove <code>nums[i]</code> from the array.</li> <li>Add <strong>two</strong> occurrences of <code>nums[i] / 2</code> to the <strong>end</strong> of <code>nums</code>.</li> </ul> <p>Return the <em><strong>minimum number of operations</strong> you need to perform so that </em><code>nums</code><em> contains a <strong>subsequence</strong> whose elements sum to</em> <code>target</code>. If it is impossible to obtain such a subsequence, return <code>-1</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,8], target = 7 <strong>Output:</strong> 1 <strong>Explanation:</strong> In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. At this stage, nums contains the subsequence [1,2,4] which sums up to 7. It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1,2], target = 12 <strong>Output:</strong> 2 <strong>Explanation:</strong> In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1], target = 35 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that no sequence of operations results in a subsequence that sums up to 35. </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;= 2<sup>30</sup></code></li> <li><code>nums</code> consists only of non-negative powers of two.</li> <li><code>1 &lt;= target &lt; 2<sup>31</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Java
class Solution { public int minOperations(List<Integer> nums, int target) { long s = 0; int[] cnt = new int[32]; for (int x : nums) { s += x; for (int i = 0; i < 32; ++i) { if ((x >> i & 1) == 1) { ++cnt[i]; } } } if (s < target) { return -1; } int i = 0, j = 0; int ans = 0; while (true) { while (i < 32 && (target >> i & 1) == 0) { ++i; } if (i == 32) { return ans; } while (j < i) { cnt[j + 1] += cnt[j] / 2; cnt[j] %= 2; ++j; } while (cnt[j] == 0) { cnt[j] = 1; ++j; } ans += j - i; --cnt[j]; j = i; ++i; } } }
2,835
Minimum Operations to Form Subsequence With Target Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>non-negative</strong> powers of <code>2</code>, and an integer <code>target</code>.</p> <p>In one operation, you must apply the following changes to the array:</p> <ul> <li>Choose any element of the array <code>nums[i]</code> such that <code>nums[i] &gt; 1</code>.</li> <li>Remove <code>nums[i]</code> from the array.</li> <li>Add <strong>two</strong> occurrences of <code>nums[i] / 2</code> to the <strong>end</strong> of <code>nums</code>.</li> </ul> <p>Return the <em><strong>minimum number of operations</strong> you need to perform so that </em><code>nums</code><em> contains a <strong>subsequence</strong> whose elements sum to</em> <code>target</code>. If it is impossible to obtain such a subsequence, return <code>-1</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,8], target = 7 <strong>Output:</strong> 1 <strong>Explanation:</strong> In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. At this stage, nums contains the subsequence [1,2,4] which sums up to 7. It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1,2], target = 12 <strong>Output:</strong> 2 <strong>Explanation:</strong> In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1], target = 35 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that no sequence of operations results in a subsequence that sums up to 35. </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;= 2<sup>30</sup></code></li> <li><code>nums</code> consists only of non-negative powers of two.</li> <li><code>1 &lt;= target &lt; 2<sup>31</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Python
class Solution: def minOperations(self, nums: List[int], target: int) -> int: s = sum(nums) if s < target: return -1 cnt = [0] * 32 for x in nums: for i in range(32): if x >> i & 1: cnt[i] += 1 i = j = 0 ans = 0 while 1: while i < 32 and (target >> i & 1) == 0: i += 1 if i == 32: break while j < i: cnt[j + 1] += cnt[j] // 2 cnt[j] %= 2 j += 1 while cnt[j] == 0: cnt[j] = 1 j += 1 ans += j - i cnt[j] -= 1 j = i i += 1 return ans
2,835
Minimum Operations to Form Subsequence With Target Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>non-negative</strong> powers of <code>2</code>, and an integer <code>target</code>.</p> <p>In one operation, you must apply the following changes to the array:</p> <ul> <li>Choose any element of the array <code>nums[i]</code> such that <code>nums[i] &gt; 1</code>.</li> <li>Remove <code>nums[i]</code> from the array.</li> <li>Add <strong>two</strong> occurrences of <code>nums[i] / 2</code> to the <strong>end</strong> of <code>nums</code>.</li> </ul> <p>Return the <em><strong>minimum number of operations</strong> you need to perform so that </em><code>nums</code><em> contains a <strong>subsequence</strong> whose elements sum to</em> <code>target</code>. If it is impossible to obtain such a subsequence, return <code>-1</code>.</p> <p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,8], target = 7 <strong>Output:</strong> 1 <strong>Explanation:</strong> In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4]. At this stage, nums contains the subsequence [1,2,4] which sums up to 7. It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1,2], target = 12 <strong>Output:</strong> 2 <strong>Explanation:</strong> In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16]. In the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8] At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12. It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,32,1], target = 35 <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that no sequence of operations results in a subsequence that sums up to 35. </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;= 2<sup>30</sup></code></li> <li><code>nums</code> consists only of non-negative powers of two.</li> <li><code>1 &lt;= target &lt; 2<sup>31</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
TypeScript
function minOperations(nums: number[], target: number): number { let s = 0; const cnt: number[] = Array(32).fill(0); for (const x of nums) { s += x; for (let i = 0; i < 32; ++i) { if ((x >> i) & 1) { ++cnt[i]; } } } if (s < target) { return -1; } let [ans, i, j] = [0, 0, 0]; while (1) { while (i < 32 && ((target >> i) & 1) === 0) { ++i; } if (i === 32) { return ans; } while (j < i) { cnt[j + 1] += cnt[j] >> 1; cnt[j] %= 2; ++j; } while (cnt[j] == 0) { cnt[j] = 1; j++; } ans += j - i; cnt[j]--; j = i; i++; } }
2,836
Maximize Value of Function in a Ball Passing Game
Hard
<p>You are given an integer array <code>receiver</code> of length <code>n</code> and an integer <code>k</code>. <code>n</code> players are playing a ball-passing game.</p> <p>You choose the starting player, <code>i</code>. The game proceeds as follows: player <code>i</code> passes the ball to player <code>receiver[i]</code>, who then passes it to <code>receiver[receiver[i]]</code>, and so on, for <code>k</code> passes in total. The game&#39;s score is the sum of the indices of the players who touched the ball, including repetitions, i.e. <code>i + receiver[i] + receiver[receiver[i]] + ... + receiver<sup>(k)</sup>[i]</code>.</p> <p>Return&nbsp;the <strong>maximum</strong>&nbsp;possible score.</p> <p><strong>Notes:</strong></p> <ul> <li><code>receiver</code> may contain duplicates.</li> <li><code>receiver[i]</code> may be equal to <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [2,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 2</code> the initial score is 2:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>1</td> <td>0</td> <td>3</td> </tr> <tr> <td>3</td> <td>0</td> <td>2</td> <td>5</td> </tr> <tr> <td>4</td> <td>2</td> <td>1</td> <td>6</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [1,1,1,2,3], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 4</code> the initial score is 4:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>4</td> <td>3</td> <td>7</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>9</td> </tr> <tr> <td>3</td> <td>2</td> <td>1</td> <td>10</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= receiver.length == n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= receiver[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>10</sup></code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
C++
class Solution { public: long long getMaxFunctionValue(vector<int>& receiver, long long k) { int n = receiver.size(), m = 64 - __builtin_clzll(k); int f[n][m]; long long g[n][m]; for (int i = 0; i < n; ++i) { f[i][0] = receiver[i]; g[i][0] = i; } for (int j = 1; j < m; ++j) { for (int i = 0; i < n; ++i) { f[i][j] = f[f[i][j - 1]][j - 1]; g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; } } long long ans = 0; for (int i = 0; i < n; ++i) { int p = i; long long t = 0; for (int j = 0; j < m; ++j) { if (k >> j & 1) { t += g[p][j]; p = f[p][j]; } } ans = max(ans, p + t); } return ans; } };
2,836
Maximize Value of Function in a Ball Passing Game
Hard
<p>You are given an integer array <code>receiver</code> of length <code>n</code> and an integer <code>k</code>. <code>n</code> players are playing a ball-passing game.</p> <p>You choose the starting player, <code>i</code>. The game proceeds as follows: player <code>i</code> passes the ball to player <code>receiver[i]</code>, who then passes it to <code>receiver[receiver[i]]</code>, and so on, for <code>k</code> passes in total. The game&#39;s score is the sum of the indices of the players who touched the ball, including repetitions, i.e. <code>i + receiver[i] + receiver[receiver[i]] + ... + receiver<sup>(k)</sup>[i]</code>.</p> <p>Return&nbsp;the <strong>maximum</strong>&nbsp;possible score.</p> <p><strong>Notes:</strong></p> <ul> <li><code>receiver</code> may contain duplicates.</li> <li><code>receiver[i]</code> may be equal to <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [2,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 2</code> the initial score is 2:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>1</td> <td>0</td> <td>3</td> </tr> <tr> <td>3</td> <td>0</td> <td>2</td> <td>5</td> </tr> <tr> <td>4</td> <td>2</td> <td>1</td> <td>6</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [1,1,1,2,3], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 4</code> the initial score is 4:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>4</td> <td>3</td> <td>7</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>9</td> </tr> <tr> <td>3</td> <td>2</td> <td>1</td> <td>10</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= receiver.length == n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= receiver[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>10</sup></code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Go
func getMaxFunctionValue(receiver []int, k int64) (ans int64) { n, m := len(receiver), bits.Len(uint(k)) f := make([][]int, n) g := make([][]int64, n) for i := range f { f[i] = make([]int, m) g[i] = make([]int64, m) f[i][0] = receiver[i] g[i][0] = int64(i) } for j := 1; j < m; j++ { for i := 0; i < n; i++ { f[i][j] = f[f[i][j-1]][j-1] g[i][j] = g[i][j-1] + g[f[i][j-1]][j-1] } } for i := 0; i < n; i++ { p := i t := int64(0) for j := 0; j < m; j++ { if k>>j&1 == 1 { t += g[p][j] p = f[p][j] } } ans = max(ans, t+int64(p)) } return }
2,836
Maximize Value of Function in a Ball Passing Game
Hard
<p>You are given an integer array <code>receiver</code> of length <code>n</code> and an integer <code>k</code>. <code>n</code> players are playing a ball-passing game.</p> <p>You choose the starting player, <code>i</code>. The game proceeds as follows: player <code>i</code> passes the ball to player <code>receiver[i]</code>, who then passes it to <code>receiver[receiver[i]]</code>, and so on, for <code>k</code> passes in total. The game&#39;s score is the sum of the indices of the players who touched the ball, including repetitions, i.e. <code>i + receiver[i] + receiver[receiver[i]] + ... + receiver<sup>(k)</sup>[i]</code>.</p> <p>Return&nbsp;the <strong>maximum</strong>&nbsp;possible score.</p> <p><strong>Notes:</strong></p> <ul> <li><code>receiver</code> may contain duplicates.</li> <li><code>receiver[i]</code> may be equal to <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [2,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 2</code> the initial score is 2:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>1</td> <td>0</td> <td>3</td> </tr> <tr> <td>3</td> <td>0</td> <td>2</td> <td>5</td> </tr> <tr> <td>4</td> <td>2</td> <td>1</td> <td>6</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [1,1,1,2,3], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 4</code> the initial score is 4:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>4</td> <td>3</td> <td>7</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>9</td> </tr> <tr> <td>3</td> <td>2</td> <td>1</td> <td>10</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= receiver.length == n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= receiver[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>10</sup></code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Java
class Solution { public long getMaxFunctionValue(List<Integer> receiver, long k) { int n = receiver.size(), m = 64 - Long.numberOfLeadingZeros(k); int[][] f = new int[n][m]; long[][] g = new long[n][m]; for (int i = 0; i < n; ++i) { f[i][0] = receiver.get(i); g[i][0] = i; } for (int j = 1; j < m; ++j) { for (int i = 0; i < n; ++i) { f[i][j] = f[f[i][j - 1]][j - 1]; g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1]; } } long ans = 0; for (int i = 0; i < n; ++i) { int p = i; long t = 0; for (int j = 0; j < m; ++j) { if ((k >> j & 1) == 1) { t += g[p][j]; p = f[p][j]; } } ans = Math.max(ans, p + t); } return ans; } }
2,836
Maximize Value of Function in a Ball Passing Game
Hard
<p>You are given an integer array <code>receiver</code> of length <code>n</code> and an integer <code>k</code>. <code>n</code> players are playing a ball-passing game.</p> <p>You choose the starting player, <code>i</code>. The game proceeds as follows: player <code>i</code> passes the ball to player <code>receiver[i]</code>, who then passes it to <code>receiver[receiver[i]]</code>, and so on, for <code>k</code> passes in total. The game&#39;s score is the sum of the indices of the players who touched the ball, including repetitions, i.e. <code>i + receiver[i] + receiver[receiver[i]] + ... + receiver<sup>(k)</sup>[i]</code>.</p> <p>Return&nbsp;the <strong>maximum</strong>&nbsp;possible score.</p> <p><strong>Notes:</strong></p> <ul> <li><code>receiver</code> may contain duplicates.</li> <li><code>receiver[i]</code> may be equal to <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [2,0,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 2</code> the initial score is 2:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td>2</td> <td>1</td> <td>0</td> <td>3</td> </tr> <tr> <td>3</td> <td>0</td> <td>2</td> <td>5</td> </tr> <tr> <td>4</td> <td>2</td> <td>1</td> <td>6</td> </tr> </tbody> </table> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">receiver = [1,1,1,2,3], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Starting with player <code>i = 4</code> the initial score is 4:</p> <table> <tbody> <tr> <th>Pass</th> <th>Sender Index</th> <th>Receiver Index</th> <th>Score</th> </tr> <tr> <td>1</td> <td>4</td> <td>3</td> <td>7</td> </tr> <tr> <td>2</td> <td>3</td> <td>2</td> <td>9</td> </tr> <tr> <td>3</td> <td>2</td> <td>1</td> <td>10</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= receiver.length == n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= receiver[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>10</sup></code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Python
class Solution: def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: n, m = len(receiver), k.bit_length() f = [[0] * m for _ in range(n)] g = [[0] * m for _ in range(n)] for i, x in enumerate(receiver): f[i][0] = x g[i][0] = i for j in range(1, m): for i in range(n): f[i][j] = f[f[i][j - 1]][j - 1] g[i][j] = g[i][j - 1] + g[f[i][j - 1]][j - 1] ans = 0 for i in range(n): p, t = i, 0 for j in range(m): if k >> j & 1: t += g[p][j] p = f[p][j] ans = max(ans, t + p) return ans
2,837
Total Traveled Distance
Easy
<p>Table: <code><font face="monospace">Users</font></code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | name | varchar | +-------------+---------+ <code>user_id</code> is the column with unique values for this table. Each row of this table contains user id and name. </pre> <p>Table: <code>Rides</code></p> <pre> +--------------+------+ | Column Name | Type | +--------------+------+ | ride_id | int | | user_id | int | | distance | int | +--------------+------+ ride_id is the column of unique values for this table. Each row of this table contains ride id, user id, and traveled distance. </pre> <p>Write a solution to calculate the <code>distance</code> traveled by <strong>each user</strong>. If there is a user&nbsp;who hasn&#39;t completed any rides, then their <code>distance</code> should be considered&nbsp;as <code>0</code>. Output the <code>user_id</code>, <code>name</code> and total traveled <code>distance</code>.</p> <p>Return<em> the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order.</em></p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Users table: +---------+---------+ | user_id | name | +---------+---------+ | 17 | Addison | | 14 | Ethan | | 4 | Michael | | 2 | Avery | | 10 | Eleanor | +---------+---------+ Rides table: +---------+---------+----------+ | ride_id | user_id | distance | +---------+---------+----------+ | 72 | 17 | 160 | | 42 | 14 | 161 | | 45 | 4 | 59 | | 32 | 2 | 197 | | 15 | 4 | 357 | | 56 | 2 | 196 | | 10 | 14 | 25 | +---------+---------+----------+ <strong>Output:</strong> +---------+---------+-------------------+ | user_id | name | traveled distance | +---------+---------+-------------------+ | 2 | Avery | 393 | | 4 | Michael | 416 | | 10 | Eleanor | 0 | | 14 | Ethan | 186 | | 17 | Addison | 160 | +---------+---------+-------------------+ <strong>Explanation:</strong> - User id 2 completed two journeys of 197 and 196, resulting in a combined travel distance of 393. - User id 4 completed two journeys of 59 and 357, resulting in a combined travel distance of 416. - User id 14 completed two journeys of 161 and 25, resulting in a combined travel distance of 186. - User id 16 completed only one journey of 160. - User id 10 did not complete any journeys, thus the total travel distance remains at 0. Returning the table orderd by user_id in ascending order.</pre>
Database
SQL
# Write your MySQL query statement below SELECT user_id, name, IFNULL(SUM(distance), 0) AS 'traveled distance' FROM Users LEFT JOIN Rides USING (user_id) GROUP BY 1 ORDER BY 1;
2,838
Maximum Coins Heroes Can Collect
Medium
<p>There is a battle and <code>n</code> heroes are trying to defeat <code>m</code> monsters. You are given two <strong>1-indexed</strong> arrays of <strong>positive</strong> integers <code><font face="monospace">heroes</font></code> and <code><font face="monospace">monsters</font></code> of length <code>n</code> and <code>m</code>, respectively. <code><font face="monospace">heroes</font>[i]</code> is the power of <code>i<sup>th</sup></code> hero, and <code><font face="monospace">monsters</font>[i]</code> is the power of <code>i<sup>th</sup></code> monster.</p> <p>The <code>i<sup>th</sup></code> hero can defeat the <code>j<sup>th</sup></code> monster if <code>monsters[j] &lt;= heroes[i]</code>.</p> <p>You are also given a <strong>1-indexed</strong> array <code>coins</code> of length <code>m</code> consisting of <strong>positive</strong> integers. <code>coins[i]</code> is the number of coins that each hero earns after defeating the <code>i<sup>th</sup></code> monster.</p> <p>Return<em> an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the <strong>maximum</strong> number of coins that the </em><code>i<sup>th</sup></code><em> hero can collect from this battle</em>.</p> <p><strong>Notes</strong></p> <ul> <li>The health of a hero doesn&#39;t get reduced after defeating a monster.</li> <li>Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6] <strong>Output:</strong> [5,16,10] <strong>Explanation: </strong>For each hero, we list the index of all the monsters he can defeat: 1<sup>st</sup> hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] &lt;= 1. So this hero collects coins[1] + coins[2] = 5 coins. 2<sup>nd</sup> hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] &lt;= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins. 3<sup>rd</sup> hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] &lt;= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins. So the answer would be [5,16,10].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2] <strong>Output:</strong> [23] <strong>Explanation:</strong> This hero can defeat all the monsters since monsters[i] &lt;= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> heroes = [4,4], monsters = [5,7,8], coins = [1,1,1] <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, no hero can defeat a monster. So the answer would be [0,0], </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heroes.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m == monsters.length &lt;= 10<sup>5</sup></code></li> <li><code>coins.length == m</code></li> <li><code>1 &lt;= heroes[i], monsters[i], coins[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Prefix Sum; Sorting
C++
class Solution { public: vector<long long> maximumCoins(vector<int>& heroes, vector<int>& monsters, vector<int>& coins) { int m = monsters.size(); vector<int> idx(m); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int i, int j) { return monsters[i] < monsters[j]; }); long long s[m + 1]; s[0] = 0; for (int i = 1; i <= m; ++i) { s[i] = s[i - 1] + coins[idx[i - 1]]; } vector<long long> ans; auto search = [&](int x) { int l = 0, r = m; while (l < r) { int mid = (l + r) >> 1; if (monsters[idx[mid]] > x) { r = mid; } else { l = mid + 1; } } return l; }; for (int h : heroes) { ans.push_back(s[search(h)]); } return ans; } };
2,838
Maximum Coins Heroes Can Collect
Medium
<p>There is a battle and <code>n</code> heroes are trying to defeat <code>m</code> monsters. You are given two <strong>1-indexed</strong> arrays of <strong>positive</strong> integers <code><font face="monospace">heroes</font></code> and <code><font face="monospace">monsters</font></code> of length <code>n</code> and <code>m</code>, respectively. <code><font face="monospace">heroes</font>[i]</code> is the power of <code>i<sup>th</sup></code> hero, and <code><font face="monospace">monsters</font>[i]</code> is the power of <code>i<sup>th</sup></code> monster.</p> <p>The <code>i<sup>th</sup></code> hero can defeat the <code>j<sup>th</sup></code> monster if <code>monsters[j] &lt;= heroes[i]</code>.</p> <p>You are also given a <strong>1-indexed</strong> array <code>coins</code> of length <code>m</code> consisting of <strong>positive</strong> integers. <code>coins[i]</code> is the number of coins that each hero earns after defeating the <code>i<sup>th</sup></code> monster.</p> <p>Return<em> an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the <strong>maximum</strong> number of coins that the </em><code>i<sup>th</sup></code><em> hero can collect from this battle</em>.</p> <p><strong>Notes</strong></p> <ul> <li>The health of a hero doesn&#39;t get reduced after defeating a monster.</li> <li>Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6] <strong>Output:</strong> [5,16,10] <strong>Explanation: </strong>For each hero, we list the index of all the monsters he can defeat: 1<sup>st</sup> hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] &lt;= 1. So this hero collects coins[1] + coins[2] = 5 coins. 2<sup>nd</sup> hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] &lt;= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins. 3<sup>rd</sup> hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] &lt;= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins. So the answer would be [5,16,10].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2] <strong>Output:</strong> [23] <strong>Explanation:</strong> This hero can defeat all the monsters since monsters[i] &lt;= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> heroes = [4,4], monsters = [5,7,8], coins = [1,1,1] <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, no hero can defeat a monster. So the answer would be [0,0], </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heroes.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m == monsters.length &lt;= 10<sup>5</sup></code></li> <li><code>coins.length == m</code></li> <li><code>1 &lt;= heroes[i], monsters[i], coins[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Prefix Sum; Sorting
Go
func maximumCoins(heroes []int, monsters []int, coins []int) (ans []int64) { m := len(monsters) idx := make([]int, m) for i := range idx { idx[i] = i } sort.Slice(idx, func(i, j int) bool { return monsters[idx[i]] < monsters[idx[j]] }) s := make([]int64, m+1) for i, j := range idx { s[i+1] = s[i] + int64(coins[j]) } for _, h := range heroes { i := sort.Search(m, func(i int) bool { return monsters[idx[i]] > h }) ans = append(ans, s[i]) } return }
2,838
Maximum Coins Heroes Can Collect
Medium
<p>There is a battle and <code>n</code> heroes are trying to defeat <code>m</code> monsters. You are given two <strong>1-indexed</strong> arrays of <strong>positive</strong> integers <code><font face="monospace">heroes</font></code> and <code><font face="monospace">monsters</font></code> of length <code>n</code> and <code>m</code>, respectively. <code><font face="monospace">heroes</font>[i]</code> is the power of <code>i<sup>th</sup></code> hero, and <code><font face="monospace">monsters</font>[i]</code> is the power of <code>i<sup>th</sup></code> monster.</p> <p>The <code>i<sup>th</sup></code> hero can defeat the <code>j<sup>th</sup></code> monster if <code>monsters[j] &lt;= heroes[i]</code>.</p> <p>You are also given a <strong>1-indexed</strong> array <code>coins</code> of length <code>m</code> consisting of <strong>positive</strong> integers. <code>coins[i]</code> is the number of coins that each hero earns after defeating the <code>i<sup>th</sup></code> monster.</p> <p>Return<em> an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the <strong>maximum</strong> number of coins that the </em><code>i<sup>th</sup></code><em> hero can collect from this battle</em>.</p> <p><strong>Notes</strong></p> <ul> <li>The health of a hero doesn&#39;t get reduced after defeating a monster.</li> <li>Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6] <strong>Output:</strong> [5,16,10] <strong>Explanation: </strong>For each hero, we list the index of all the monsters he can defeat: 1<sup>st</sup> hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] &lt;= 1. So this hero collects coins[1] + coins[2] = 5 coins. 2<sup>nd</sup> hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] &lt;= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins. 3<sup>rd</sup> hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] &lt;= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins. So the answer would be [5,16,10].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2] <strong>Output:</strong> [23] <strong>Explanation:</strong> This hero can defeat all the monsters since monsters[i] &lt;= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> heroes = [4,4], monsters = [5,7,8], coins = [1,1,1] <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, no hero can defeat a monster. So the answer would be [0,0], </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heroes.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m == monsters.length &lt;= 10<sup>5</sup></code></li> <li><code>coins.length == m</code></li> <li><code>1 &lt;= heroes[i], monsters[i], coins[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Prefix Sum; Sorting
Java
class Solution { public long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) { int m = monsters.length; Integer[] idx = new Integer[m]; for (int i = 0; i < m; ++i) { idx[i] = i; } Arrays.sort(idx, Comparator.comparingInt(j -> monsters[j])); long[] s = new long[m + 1]; for (int i = 0; i < m; ++i) { s[i + 1] = s[i] + coins[idx[i]]; } int n = heroes.length; long[] ans = new long[n]; for (int k = 0; k < n; ++k) { int i = search(monsters, idx, heroes[k]); ans[k] = s[i]; } return ans; } private int search(int[] nums, Integer[] idx, int x) { int l = 0, r = idx.length; while (l < r) { int mid = (l + r) >> 1; if (nums[idx[mid]] > x) { r = mid; } else { l = mid + 1; } } return l; } }
2,838
Maximum Coins Heroes Can Collect
Medium
<p>There is a battle and <code>n</code> heroes are trying to defeat <code>m</code> monsters. You are given two <strong>1-indexed</strong> arrays of <strong>positive</strong> integers <code><font face="monospace">heroes</font></code> and <code><font face="monospace">monsters</font></code> of length <code>n</code> and <code>m</code>, respectively. <code><font face="monospace">heroes</font>[i]</code> is the power of <code>i<sup>th</sup></code> hero, and <code><font face="monospace">monsters</font>[i]</code> is the power of <code>i<sup>th</sup></code> monster.</p> <p>The <code>i<sup>th</sup></code> hero can defeat the <code>j<sup>th</sup></code> monster if <code>monsters[j] &lt;= heroes[i]</code>.</p> <p>You are also given a <strong>1-indexed</strong> array <code>coins</code> of length <code>m</code> consisting of <strong>positive</strong> integers. <code>coins[i]</code> is the number of coins that each hero earns after defeating the <code>i<sup>th</sup></code> monster.</p> <p>Return<em> an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the <strong>maximum</strong> number of coins that the </em><code>i<sup>th</sup></code><em> hero can collect from this battle</em>.</p> <p><strong>Notes</strong></p> <ul> <li>The health of a hero doesn&#39;t get reduced after defeating a monster.</li> <li>Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6] <strong>Output:</strong> [5,16,10] <strong>Explanation: </strong>For each hero, we list the index of all the monsters he can defeat: 1<sup>st</sup> hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] &lt;= 1. So this hero collects coins[1] + coins[2] = 5 coins. 2<sup>nd</sup> hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] &lt;= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins. 3<sup>rd</sup> hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] &lt;= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins. So the answer would be [5,16,10].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2] <strong>Output:</strong> [23] <strong>Explanation:</strong> This hero can defeat all the monsters since monsters[i] &lt;= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> heroes = [4,4], monsters = [5,7,8], coins = [1,1,1] <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, no hero can defeat a monster. So the answer would be [0,0], </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heroes.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m == monsters.length &lt;= 10<sup>5</sup></code></li> <li><code>coins.length == m</code></li> <li><code>1 &lt;= heroes[i], monsters[i], coins[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Prefix Sum; Sorting
Python
class Solution: def maximumCoins( self, heroes: List[int], monsters: List[int], coins: List[int] ) -> List[int]: m = len(monsters) idx = sorted(range(m), key=lambda i: monsters[i]) s = list(accumulate((coins[i] for i in idx), initial=0)) ans = [] for h in heroes: i = bisect_right(idx, h, key=lambda i: monsters[i]) ans.append(s[i]) return ans
2,838
Maximum Coins Heroes Can Collect
Medium
<p>There is a battle and <code>n</code> heroes are trying to defeat <code>m</code> monsters. You are given two <strong>1-indexed</strong> arrays of <strong>positive</strong> integers <code><font face="monospace">heroes</font></code> and <code><font face="monospace">monsters</font></code> of length <code>n</code> and <code>m</code>, respectively. <code><font face="monospace">heroes</font>[i]</code> is the power of <code>i<sup>th</sup></code> hero, and <code><font face="monospace">monsters</font>[i]</code> is the power of <code>i<sup>th</sup></code> monster.</p> <p>The <code>i<sup>th</sup></code> hero can defeat the <code>j<sup>th</sup></code> monster if <code>monsters[j] &lt;= heroes[i]</code>.</p> <p>You are also given a <strong>1-indexed</strong> array <code>coins</code> of length <code>m</code> consisting of <strong>positive</strong> integers. <code>coins[i]</code> is the number of coins that each hero earns after defeating the <code>i<sup>th</sup></code> monster.</p> <p>Return<em> an array </em><code>ans</code><em> of length </em><code>n</code><em> where </em><code>ans[i]</code><em> is the <strong>maximum</strong> number of coins that the </em><code>i<sup>th</sup></code><em> hero can collect from this battle</em>.</p> <p><strong>Notes</strong></p> <ul> <li>The health of a hero doesn&#39;t get reduced after defeating a monster.</li> <li>Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6] <strong>Output:</strong> [5,16,10] <strong>Explanation: </strong>For each hero, we list the index of all the monsters he can defeat: 1<sup>st</sup> hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] &lt;= 1. So this hero collects coins[1] + coins[2] = 5 coins. 2<sup>nd</sup> hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] &lt;= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins. 3<sup>rd</sup> hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] &lt;= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins. So the answer would be [5,16,10].</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2] <strong>Output:</strong> [23] <strong>Explanation:</strong> This hero can defeat all the monsters since monsters[i] &lt;= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> heroes = [4,4], monsters = [5,7,8], coins = [1,1,1] <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, no hero can defeat a monster. So the answer would be [0,0], </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heroes.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m == monsters.length &lt;= 10<sup>5</sup></code></li> <li><code>coins.length == m</code></li> <li><code>1 &lt;= heroes[i], monsters[i], coins[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Prefix Sum; Sorting
TypeScript
function maximumCoins(heroes: number[], monsters: number[], coins: number[]): number[] { const m = monsters.length; const idx: number[] = Array.from({ length: m }, (_, i) => i); idx.sort((i, j) => monsters[i] - monsters[j]); const s: number[] = Array(m + 1).fill(0); for (let i = 0; i < m; ++i) { s[i + 1] = s[i] + coins[idx[i]]; } const search = (x: number): number => { let l = 0; let r = m; while (l < r) { const mid = (l + r) >> 1; if (monsters[idx[mid]] > x) { r = mid; } else { l = mid + 1; } } return l; }; return heroes.map(h => s[search(h)]); }
2,839
Check if Strings Can be Made Equal With Operations I
Easy
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>4</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on any of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>j - i = 2</code>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;cdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbad&quot;. - Choose the indices i = 1, j = 3. The resulting string is s1 = &quot;cdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;dacb&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length == 4</code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
String
C++
class Solution { public: bool canBeEqual(string s1, string s2) { vector<vector<int>> cnt(2, vector<int>(26, 0)); for (int i = 0; i < s1.size(); ++i) { ++cnt[i & 1][s1[i] - 'a']; --cnt[i & 1][s2[i] - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[0][i] || cnt[1][i]) { return false; } } return true; } };
2,839
Check if Strings Can be Made Equal With Operations I
Easy
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>4</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on any of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>j - i = 2</code>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;cdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbad&quot;. - Choose the indices i = 1, j = 3. The resulting string is s1 = &quot;cdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;dacb&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length == 4</code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
String
Go
func canBeEqual(s1 string, s2 string) bool { cnt := [2][26]int{} for i := 0; i < len(s1); i++ { cnt[i&1][s1[i]-'a']++ cnt[i&1][s2[i]-'a']-- } for i := 0; i < 26; i++ { if cnt[0][i] != 0 || cnt[1][i] != 0 { return false } } return true }
2,839
Check if Strings Can be Made Equal With Operations I
Easy
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>4</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on any of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>j - i = 2</code>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;cdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbad&quot;. - Choose the indices i = 1, j = 3. The resulting string is s1 = &quot;cdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;dacb&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length == 4</code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
String
Java
class Solution { public boolean canBeEqual(String s1, String s2) { int[][] cnt = new int[2][26]; for (int i = 0; i < s1.length(); ++i) { ++cnt[i & 1][s1.charAt(i) - 'a']; --cnt[i & 1][s2.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[0][i] != 0 || cnt[1][i] != 0) { return false; } } return true; } }
2,839
Check if Strings Can be Made Equal With Operations I
Easy
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>4</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on any of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>j - i = 2</code>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;cdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbad&quot;. - Choose the indices i = 1, j = 3. The resulting string is s1 = &quot;cdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;dacb&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length == 4</code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
String
Python
class Solution: def canBeEqual(self, s1: str, s2: str) -> bool: return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( s2[1::2] )
2,839
Check if Strings Can be Made Equal With Operations I
Easy
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>4</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on any of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>j - i = 2</code>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;cdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbad&quot;. - Choose the indices i = 1, j = 3. The resulting string is s1 = &quot;cdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcd&quot;, s2 = &quot;dacb&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length == 4</code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
String
TypeScript
function canBeEqual(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); for (let i = 0; i < s1.length; ++i) { ++cnt[i & 1][s1.charCodeAt(i) - 97]; --cnt[i & 1][s2.charCodeAt(i) - 97]; } for (let i = 0; i < 26; ++i) { if (cnt[0][i] || cnt[1][i]) { return false; } } return true; }
2,840
Check if Strings Can be Made Equal With Operations II
Medium
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on <strong>any</strong> of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>i &lt; j</code> and the difference <code>j - i</code> is <strong>even</strong>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and&nbsp;</em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcdba&quot;, s2 = &quot;cabdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbadba&quot;. - Choose the indices i = 2, j = 4. The resulting string is s1 = &quot;cbbdaa&quot;. - Choose the indices i = 1, j = 5. The resulting string is s1 = &quot;cabdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abe&quot;, s2 = &quot;bea&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s1.length == s2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sorting
C++
class Solution { public: bool checkStrings(string s1, string s2) { vector<vector<int>> cnt(2, vector<int>(26, 0)); for (int i = 0; i < s1.size(); ++i) { ++cnt[i & 1][s1[i] - 'a']; --cnt[i & 1][s2[i] - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[0][i] || cnt[1][i]) { return false; } } return true; } };
2,840
Check if Strings Can be Made Equal With Operations II
Medium
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on <strong>any</strong> of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>i &lt; j</code> and the difference <code>j - i</code> is <strong>even</strong>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and&nbsp;</em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcdba&quot;, s2 = &quot;cabdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbadba&quot;. - Choose the indices i = 2, j = 4. The resulting string is s1 = &quot;cbbdaa&quot;. - Choose the indices i = 1, j = 5. The resulting string is s1 = &quot;cabdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abe&quot;, s2 = &quot;bea&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s1.length == s2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sorting
Go
func checkStrings(s1 string, s2 string) bool { cnt := [2][26]int{} for i := 0; i < len(s1); i++ { cnt[i&1][s1[i]-'a']++ cnt[i&1][s2[i]-'a']-- } for i := 0; i < 26; i++ { if cnt[0][i] != 0 || cnt[1][i] != 0 { return false } } return true }
2,840
Check if Strings Can be Made Equal With Operations II
Medium
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on <strong>any</strong> of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>i &lt; j</code> and the difference <code>j - i</code> is <strong>even</strong>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and&nbsp;</em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcdba&quot;, s2 = &quot;cabdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbadba&quot;. - Choose the indices i = 2, j = 4. The resulting string is s1 = &quot;cbbdaa&quot;. - Choose the indices i = 1, j = 5. The resulting string is s1 = &quot;cabdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abe&quot;, s2 = &quot;bea&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s1.length == s2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sorting
Java
class Solution { public boolean checkStrings(String s1, String s2) { int[][] cnt = new int[2][26]; for (int i = 0; i < s1.length(); ++i) { ++cnt[i & 1][s1.charAt(i) - 'a']; --cnt[i & 1][s2.charAt(i) - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[0][i] != 0 || cnt[1][i] != 0) { return false; } } return true; } }
2,840
Check if Strings Can be Made Equal With Operations II
Medium
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on <strong>any</strong> of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>i &lt; j</code> and the difference <code>j - i</code> is <strong>even</strong>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and&nbsp;</em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcdba&quot;, s2 = &quot;cabdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbadba&quot;. - Choose the indices i = 2, j = 4. The resulting string is s1 = &quot;cbbdaa&quot;. - Choose the indices i = 1, j = 5. The resulting string is s1 = &quot;cabdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abe&quot;, s2 = &quot;bea&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s1.length == s2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sorting
Python
class Solution: def checkStrings(self, s1: str, s2: str) -> bool: return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted( s2[1::2] )
2,840
Check if Strings Can be Made Equal With Operations II
Medium
<p>You are given two strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, consisting of <strong>lowercase</strong> English letters.</p> <p>You can apply the following operation on <strong>any</strong> of the two strings <strong>any</strong> number of times:</p> <ul> <li>Choose any two indices <code>i</code> and <code>j</code> such that <code>i &lt; j</code> and the difference <code>j - i</code> is <strong>even</strong>, then <strong>swap</strong> the two characters at those indices in the string.</li> </ul> <p>Return <code>true</code><em> if you can make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, and&nbsp;</em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abcdba&quot;, s2 = &quot;cabdab&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = &quot;cbadba&quot;. - Choose the indices i = 2, j = 4. The resulting string is s1 = &quot;cbbdaa&quot;. - Choose the indices i = 1, j = 5. The resulting string is s1 = &quot;cabdab&quot; = s2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;abe&quot;, s2 = &quot;bea&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make the two strings equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s1.length == s2.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s1</code> and <code>s2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sorting
TypeScript
function checkStrings(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); for (let i = 0; i < s1.length; ++i) { ++cnt[i & 1][s1.charCodeAt(i) - 97]; --cnt[i & 1][s2.charCodeAt(i) - 97]; } for (let i = 0; i < 26; ++i) { if (cnt[0][i] || cnt[1][i]) { return false; } } return true; }
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
C++
class Solution { public: long long maxSum(vector<int>& nums, int m, int k) { unordered_map<int, int> cnt; long long s = 0; int n = nums.size(); for (int i = 0; i < k; ++i) { cnt[nums[i]]++; s += nums[i]; } long long ans = cnt.size() >= m ? s : 0; for (int i = k; i < n; ++i) { cnt[nums[i]]++; if (--cnt[nums[i - k]] == 0) { cnt.erase(nums[i - k]); } s += nums[i] - nums[i - k]; if (cnt.size() >= m) { ans = max(ans, s); } } return ans; } };
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
C#
public class Solution { public long MaxSum(IList<int> nums, int m, int k) { Dictionary<int, int> cnt = new Dictionary<int, int>(); int n = nums.Count; long s = 0; for (int i = 0; i < k; ++i) { if (!cnt.ContainsKey(nums[i])) { cnt[nums[i]] = 1; } else { cnt[nums[i]]++; } s += nums[i]; } long ans = cnt.Count >= m ? s : 0; for (int i = k; i < n; ++i) { if (!cnt.ContainsKey(nums[i])) { cnt[nums[i]] = 1; } else { cnt[nums[i]]++; } if (cnt.ContainsKey(nums[i - k])) { cnt[nums[i - k]]--; if (cnt[nums[i - k]] == 0) { cnt.Remove(nums[i - k]); } } s += nums[i] - nums[i - k]; if (cnt.Count >= m) { ans = Math.Max(ans, s); } } return ans; } }
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Go
func maxSum(nums []int, m int, k int) int64 { cnt := map[int]int{} var s int64 for _, x := range nums[:k] { cnt[x]++ s += int64(x) } var ans int64 if len(cnt) >= m { ans = s } for i := k; i < len(nums); i++ { cnt[nums[i]]++ cnt[nums[i-k]]-- if cnt[nums[i-k]] == 0 { delete(cnt, nums[i-k]) } s += int64(nums[i]) - int64(nums[i-k]) if len(cnt) >= m { ans = max(ans, s) } } return ans }
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Java
class Solution { public long maxSum(List<Integer> nums, int m, int k) { Map<Integer, Integer> cnt = new HashMap<>(); int n = nums.size(); long s = 0; for (int i = 0; i < k; ++i) { cnt.merge(nums.get(i), 1, Integer::sum); s += nums.get(i); } long ans = cnt.size() >= m ? s : 0; for (int i = k; i < n; ++i) { cnt.merge(nums.get(i), 1, Integer::sum); if (cnt.merge(nums.get(i - k), -1, Integer::sum) == 0) { cnt.remove(nums.get(i - k)); } s += nums.get(i) - nums.get(i - k); if (cnt.size() >= m) { ans = Math.max(ans, s); } } return ans; } }
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Python
class Solution: def maxSum(self, nums: List[int], m: int, k: int) -> int: cnt = Counter(nums[:k]) s = sum(nums[:k]) ans = s if len(cnt) >= m else 0 for i in range(k, len(nums)): cnt[nums[i]] += 1 cnt[nums[i - k]] -= 1 s += nums[i] - nums[i - k] if cnt[nums[i - k]] == 0: cnt.pop(nums[i - k]) if len(cnt) >= m: ans = max(ans, s) return ans
2,841
Maximum Sum of Almost Unique Subarray
Medium
<p>You are given an integer array <code>nums</code> and two positive integers <code>m</code> and <code>k</code>.</p> <p>Return <em>the <strong>maximum sum</strong> out of all <strong>almost unique</strong> subarrays of length </em><code>k</code><em> of</em> <code>nums</code>. If no such subarray exists, return <code>0</code>.</p> <p>A subarray of <code>nums</code> is <strong>almost unique</strong> if it contains at least <code>m</code> distinct elements.</p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,7,3,1,7], m = 3, k = 4 <strong>Output:</strong> 18 <strong>Explanation:</strong> There are 3 almost unique subarrays of size <code>k = 4</code>. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,9,9,2,4,5,4], m = 1, k = 3 <strong>Output:</strong> 23 <strong>Explanation:</strong> There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1], m = 3, k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no subarrays of size <code>k = 3</code> that contain at least <code>m = 3</code> distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>1 &lt;= m &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sliding Window
TypeScript
function maxSum(nums: number[], m: number, k: number): number { const n = nums.length; const cnt: Map<number, number> = new Map(); let s = 0; for (let i = 0; i < k; ++i) { cnt.set(nums[i], (cnt.get(nums[i]) || 0) + 1); s += nums[i]; } let ans = cnt.size >= m ? s : 0; for (let i = k; i < n; ++i) { cnt.set(nums[i], (cnt.get(nums[i]) || 0) + 1); cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); if (cnt.get(nums[i - k]) === 0) { cnt.delete(nums[i - k]); } s += nums[i] - nums[i - k]; if (cnt.size >= m) { ans = Math.max(ans, s); } } return ans; }
2,842
Count K-Subsequences of a String With Maximum Beauty
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>A <strong>k-subsequence</strong> is a <strong>subsequence</strong> of <code>s</code>, having length <code>k</code>, and all its characters are <strong>unique</strong>, <strong>i.e</strong>., every character occurs once.</p> <p>Let <code>f(c)</code> denote the number of times the character <code>c</code> occurs in <code>s</code>.</p> <p>The <strong>beauty</strong> of a <strong>k-subsequence</strong> is the <strong>sum</strong> of <code>f(c)</code> for every character <code>c</code> in the k-subsequence.</p> <p>For example, consider <code>s = &quot;abbbdd&quot;</code> and <code>k = 2</code>:</p> <ul> <li><code>f(&#39;a&#39;) = 1</code>, <code>f(&#39;b&#39;) = 3</code>, <code>f(&#39;d&#39;) = 2</code></li> <li>Some k-subsequences of <code>s</code> are: <ul> <li><code>&quot;<u><strong>ab</strong></u>bbdd&quot;</code> -&gt; <code>&quot;ab&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;b&#39;) = 4</code></li> <li><code>&quot;<u><strong>a</strong></u>bbb<strong><u>d</u></strong>d&quot;</code> -&gt; <code>&quot;ad&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;d&#39;) = 3</code></li> <li><code>&quot;a<strong><u>b</u></strong>bb<u><strong>d</strong></u>d&quot;</code> -&gt; <code>&quot;bd&quot;</code> having a beauty of <code>f(&#39;b&#39;) + f(&#39;d&#39;) = 5</code></li> </ul> </li> </ul> <p>Return <em>an integer denoting the number of k-subsequences </em><em>whose <strong>beauty</strong> is the <strong>maximum</strong> among all <strong>k-subsequences</strong></em>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p> <p><strong>Notes</strong></p> <ul> <li><code>f(c)</code> is the number of times a character <code>c</code> occurs in <code>s</code>, not a k-subsequence.</li> <li>Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcca&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> <span style="white-space: normal">From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 1, and f(&#39;c&#39;) = 2.</span> The k-subsequences of s are: <strong><u>bc</u></strong>ca having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>c<u><strong>c</strong></u>a having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>cc<strong><u>a</u></strong> having a beauty of f(&#39;b&#39;) + f(&#39;a&#39;) = 2 b<strong><u>c</u></strong>c<u><strong>a</strong></u><strong> </strong>having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 bc<strong><u>ca</u></strong> having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abbcd&quot;, k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 2, f(&#39;c&#39;) = 1, and f(&#39;d&#39;) = 1. The k-subsequences of s are: <u><strong>ab</strong></u>b<strong><u>cd</u></strong> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 <u style="white-space: normal;"><strong>a</strong></u>b<u><strong>bcd</strong></u> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; Math; String; Combinatorics
C++
class Solution { public: int countKSubsequencesWithMaxBeauty(string s, int k) { int f[26]{}; int cnt = 0; for (char& c : s) { if (++f[c - 'a'] == 1) { ++cnt; } } if (cnt < k) { return 0; } vector<int> vs(cnt); for (int i = 0, j = 0; i < 26; ++i) { if (f[i]) { vs[j++] = f[i]; } } sort(vs.rbegin(), vs.rend()); const int mod = 1e9 + 7; long long ans = 1; int val = vs[k - 1]; int x = 0; for (int v : vs) { x += v == val; } for (int v : vs) { if (v == val) { break; } --k; ans = ans * v % mod; } int c[x + 1][x + 1]; memset(c, 0, sizeof(c)); for (int i = 0; i <= x; ++i) { c[i][0] = 1; for (int j = 1; j <= i; ++j) { c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; } } auto qpow = [&](long long a, int n) { long long ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return ans; }; ans = (ans * c[x][k] % mod) * qpow(val, k) % mod; return ans; } };
2,842
Count K-Subsequences of a String With Maximum Beauty
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>A <strong>k-subsequence</strong> is a <strong>subsequence</strong> of <code>s</code>, having length <code>k</code>, and all its characters are <strong>unique</strong>, <strong>i.e</strong>., every character occurs once.</p> <p>Let <code>f(c)</code> denote the number of times the character <code>c</code> occurs in <code>s</code>.</p> <p>The <strong>beauty</strong> of a <strong>k-subsequence</strong> is the <strong>sum</strong> of <code>f(c)</code> for every character <code>c</code> in the k-subsequence.</p> <p>For example, consider <code>s = &quot;abbbdd&quot;</code> and <code>k = 2</code>:</p> <ul> <li><code>f(&#39;a&#39;) = 1</code>, <code>f(&#39;b&#39;) = 3</code>, <code>f(&#39;d&#39;) = 2</code></li> <li>Some k-subsequences of <code>s</code> are: <ul> <li><code>&quot;<u><strong>ab</strong></u>bbdd&quot;</code> -&gt; <code>&quot;ab&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;b&#39;) = 4</code></li> <li><code>&quot;<u><strong>a</strong></u>bbb<strong><u>d</u></strong>d&quot;</code> -&gt; <code>&quot;ad&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;d&#39;) = 3</code></li> <li><code>&quot;a<strong><u>b</u></strong>bb<u><strong>d</strong></u>d&quot;</code> -&gt; <code>&quot;bd&quot;</code> having a beauty of <code>f(&#39;b&#39;) + f(&#39;d&#39;) = 5</code></li> </ul> </li> </ul> <p>Return <em>an integer denoting the number of k-subsequences </em><em>whose <strong>beauty</strong> is the <strong>maximum</strong> among all <strong>k-subsequences</strong></em>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p> <p><strong>Notes</strong></p> <ul> <li><code>f(c)</code> is the number of times a character <code>c</code> occurs in <code>s</code>, not a k-subsequence.</li> <li>Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcca&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> <span style="white-space: normal">From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 1, and f(&#39;c&#39;) = 2.</span> The k-subsequences of s are: <strong><u>bc</u></strong>ca having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>c<u><strong>c</strong></u>a having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>cc<strong><u>a</u></strong> having a beauty of f(&#39;b&#39;) + f(&#39;a&#39;) = 2 b<strong><u>c</u></strong>c<u><strong>a</strong></u><strong> </strong>having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 bc<strong><u>ca</u></strong> having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abbcd&quot;, k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 2, f(&#39;c&#39;) = 1, and f(&#39;d&#39;) = 1. The k-subsequences of s are: <u><strong>ab</strong></u>b<strong><u>cd</u></strong> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 <u style="white-space: normal;"><strong>a</strong></u>b<u><strong>bcd</strong></u> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; Math; String; Combinatorics
Go
func countKSubsequencesWithMaxBeauty(s string, k int) int { f := [26]int{} cnt := 0 for _, c := range s { f[c-'a']++ if f[c-'a'] == 1 { cnt++ } } if cnt < k { return 0 } vs := []int{} for _, x := range f { if x > 0 { vs = append(vs, x) } } sort.Slice(vs, func(i, j int) bool { return vs[i] > vs[j] }) const mod int = 1e9 + 7 ans := 1 val := vs[k-1] x := 0 for _, v := range vs { if v == val { x++ } } for _, v := range vs { if v == val { break } k-- ans = ans * v % mod } c := make([][]int, x+1) for i := range c { c[i] = make([]int, x+1) c[i][0] = 1 for j := 1; j <= i; j++ { c[i][j] = (c[i-1][j-1] + c[i-1][j]) % mod } } qpow := func(a, n int) int { ans := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { ans = ans * a % mod } a = a * a % mod } return ans } ans = (ans * c[x][k] % mod) * qpow(val, k) % mod return ans }
2,842
Count K-Subsequences of a String With Maximum Beauty
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>A <strong>k-subsequence</strong> is a <strong>subsequence</strong> of <code>s</code>, having length <code>k</code>, and all its characters are <strong>unique</strong>, <strong>i.e</strong>., every character occurs once.</p> <p>Let <code>f(c)</code> denote the number of times the character <code>c</code> occurs in <code>s</code>.</p> <p>The <strong>beauty</strong> of a <strong>k-subsequence</strong> is the <strong>sum</strong> of <code>f(c)</code> for every character <code>c</code> in the k-subsequence.</p> <p>For example, consider <code>s = &quot;abbbdd&quot;</code> and <code>k = 2</code>:</p> <ul> <li><code>f(&#39;a&#39;) = 1</code>, <code>f(&#39;b&#39;) = 3</code>, <code>f(&#39;d&#39;) = 2</code></li> <li>Some k-subsequences of <code>s</code> are: <ul> <li><code>&quot;<u><strong>ab</strong></u>bbdd&quot;</code> -&gt; <code>&quot;ab&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;b&#39;) = 4</code></li> <li><code>&quot;<u><strong>a</strong></u>bbb<strong><u>d</u></strong>d&quot;</code> -&gt; <code>&quot;ad&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;d&#39;) = 3</code></li> <li><code>&quot;a<strong><u>b</u></strong>bb<u><strong>d</strong></u>d&quot;</code> -&gt; <code>&quot;bd&quot;</code> having a beauty of <code>f(&#39;b&#39;) + f(&#39;d&#39;) = 5</code></li> </ul> </li> </ul> <p>Return <em>an integer denoting the number of k-subsequences </em><em>whose <strong>beauty</strong> is the <strong>maximum</strong> among all <strong>k-subsequences</strong></em>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p> <p><strong>Notes</strong></p> <ul> <li><code>f(c)</code> is the number of times a character <code>c</code> occurs in <code>s</code>, not a k-subsequence.</li> <li>Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcca&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> <span style="white-space: normal">From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 1, and f(&#39;c&#39;) = 2.</span> The k-subsequences of s are: <strong><u>bc</u></strong>ca having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>c<u><strong>c</strong></u>a having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>cc<strong><u>a</u></strong> having a beauty of f(&#39;b&#39;) + f(&#39;a&#39;) = 2 b<strong><u>c</u></strong>c<u><strong>a</strong></u><strong> </strong>having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 bc<strong><u>ca</u></strong> having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abbcd&quot;, k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 2, f(&#39;c&#39;) = 1, and f(&#39;d&#39;) = 1. The k-subsequences of s are: <u><strong>ab</strong></u>b<strong><u>cd</u></strong> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 <u style="white-space: normal;"><strong>a</strong></u>b<u><strong>bcd</strong></u> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; Math; String; Combinatorics
Java
class Solution { private final int mod = (int) 1e9 + 7; public int countKSubsequencesWithMaxBeauty(String s, int k) { int[] f = new int[26]; int n = s.length(); int cnt = 0; for (int i = 0; i < n; ++i) { if (++f[s.charAt(i) - 'a'] == 1) { ++cnt; } } if (cnt < k) { return 0; } Integer[] vs = new Integer[cnt]; for (int i = 0, j = 0; i < 26; ++i) { if (f[i] > 0) { vs[j++] = f[i]; } } Arrays.sort(vs, (a, b) -> b - a); long ans = 1; int val = vs[k - 1]; int x = 0; for (int v : vs) { if (v == val) { ++x; } } for (int v : vs) { if (v == val) { break; } --k; ans = ans * v % mod; } int[][] c = new int[x + 1][x + 1]; for (int i = 0; i <= x; ++i) { c[i][0] = 1; for (int j = 1; j <= i; ++j) { c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod; } } ans = ((ans * c[x][k]) % mod) * qpow(val, k) % mod; return (int) ans; } private long qpow(long a, int n) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return ans; } }
2,842
Count K-Subsequences of a String With Maximum Beauty
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>A <strong>k-subsequence</strong> is a <strong>subsequence</strong> of <code>s</code>, having length <code>k</code>, and all its characters are <strong>unique</strong>, <strong>i.e</strong>., every character occurs once.</p> <p>Let <code>f(c)</code> denote the number of times the character <code>c</code> occurs in <code>s</code>.</p> <p>The <strong>beauty</strong> of a <strong>k-subsequence</strong> is the <strong>sum</strong> of <code>f(c)</code> for every character <code>c</code> in the k-subsequence.</p> <p>For example, consider <code>s = &quot;abbbdd&quot;</code> and <code>k = 2</code>:</p> <ul> <li><code>f(&#39;a&#39;) = 1</code>, <code>f(&#39;b&#39;) = 3</code>, <code>f(&#39;d&#39;) = 2</code></li> <li>Some k-subsequences of <code>s</code> are: <ul> <li><code>&quot;<u><strong>ab</strong></u>bbdd&quot;</code> -&gt; <code>&quot;ab&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;b&#39;) = 4</code></li> <li><code>&quot;<u><strong>a</strong></u>bbb<strong><u>d</u></strong>d&quot;</code> -&gt; <code>&quot;ad&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;d&#39;) = 3</code></li> <li><code>&quot;a<strong><u>b</u></strong>bb<u><strong>d</strong></u>d&quot;</code> -&gt; <code>&quot;bd&quot;</code> having a beauty of <code>f(&#39;b&#39;) + f(&#39;d&#39;) = 5</code></li> </ul> </li> </ul> <p>Return <em>an integer denoting the number of k-subsequences </em><em>whose <strong>beauty</strong> is the <strong>maximum</strong> among all <strong>k-subsequences</strong></em>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p> <p><strong>Notes</strong></p> <ul> <li><code>f(c)</code> is the number of times a character <code>c</code> occurs in <code>s</code>, not a k-subsequence.</li> <li>Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcca&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> <span style="white-space: normal">From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 1, and f(&#39;c&#39;) = 2.</span> The k-subsequences of s are: <strong><u>bc</u></strong>ca having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>c<u><strong>c</strong></u>a having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>cc<strong><u>a</u></strong> having a beauty of f(&#39;b&#39;) + f(&#39;a&#39;) = 2 b<strong><u>c</u></strong>c<u><strong>a</strong></u><strong> </strong>having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 bc<strong><u>ca</u></strong> having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abbcd&quot;, k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 2, f(&#39;c&#39;) = 1, and f(&#39;d&#39;) = 1. The k-subsequences of s are: <u><strong>ab</strong></u>b<strong><u>cd</u></strong> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 <u style="white-space: normal;"><strong>a</strong></u>b<u><strong>bcd</strong></u> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; Math; String; Combinatorics
Python
class Solution: def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: f = Counter(s) if len(f) < k: return 0 mod = 10**9 + 7 vs = sorted(f.values(), reverse=True) val = vs[k - 1] x = vs.count(val) ans = 1 for v in vs: if v == val: break k -= 1 ans = ans * v % mod ans = ans * comb(x, k) * pow(val, k, mod) % mod return ans
2,842
Count K-Subsequences of a String With Maximum Beauty
Hard
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>A <strong>k-subsequence</strong> is a <strong>subsequence</strong> of <code>s</code>, having length <code>k</code>, and all its characters are <strong>unique</strong>, <strong>i.e</strong>., every character occurs once.</p> <p>Let <code>f(c)</code> denote the number of times the character <code>c</code> occurs in <code>s</code>.</p> <p>The <strong>beauty</strong> of a <strong>k-subsequence</strong> is the <strong>sum</strong> of <code>f(c)</code> for every character <code>c</code> in the k-subsequence.</p> <p>For example, consider <code>s = &quot;abbbdd&quot;</code> and <code>k = 2</code>:</p> <ul> <li><code>f(&#39;a&#39;) = 1</code>, <code>f(&#39;b&#39;) = 3</code>, <code>f(&#39;d&#39;) = 2</code></li> <li>Some k-subsequences of <code>s</code> are: <ul> <li><code>&quot;<u><strong>ab</strong></u>bbdd&quot;</code> -&gt; <code>&quot;ab&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;b&#39;) = 4</code></li> <li><code>&quot;<u><strong>a</strong></u>bbb<strong><u>d</u></strong>d&quot;</code> -&gt; <code>&quot;ad&quot;</code> having a beauty of <code>f(&#39;a&#39;) + f(&#39;d&#39;) = 3</code></li> <li><code>&quot;a<strong><u>b</u></strong>bb<u><strong>d</strong></u>d&quot;</code> -&gt; <code>&quot;bd&quot;</code> having a beauty of <code>f(&#39;b&#39;) + f(&#39;d&#39;) = 5</code></li> </ul> </li> </ul> <p>Return <em>an integer denoting the number of k-subsequences </em><em>whose <strong>beauty</strong> is the <strong>maximum</strong> among all <strong>k-subsequences</strong></em>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p> <p>A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p> <p><strong>Notes</strong></p> <ul> <li><code>f(c)</code> is the number of times a character <code>c</code> occurs in <code>s</code>, not a k-subsequence.</li> <li>Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcca&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> <span style="white-space: normal">From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 1, and f(&#39;c&#39;) = 2.</span> The k-subsequences of s are: <strong><u>bc</u></strong>ca having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>c<u><strong>c</strong></u>a having a beauty of f(&#39;b&#39;) + f(&#39;c&#39;) = 3 <strong><u>b</u></strong>cc<strong><u>a</u></strong> having a beauty of f(&#39;b&#39;) + f(&#39;a&#39;) = 2 b<strong><u>c</u></strong>c<u><strong>a</strong></u><strong> </strong>having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 bc<strong><u>ca</u></strong> having a beauty of f(&#39;c&#39;) + f(&#39;a&#39;) = 3 There are 4 k-subsequences that have the maximum beauty, 3. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abbcd&quot;, k = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> From s we have f(&#39;a&#39;) = 1, f(&#39;b&#39;) = 2, f(&#39;c&#39;) = 1, and f(&#39;d&#39;) = 1. The k-subsequences of s are: <u><strong>ab</strong></u>b<strong><u>cd</u></strong> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 <u style="white-space: normal;"><strong>a</strong></u>b<u><strong>bcd</strong></u> having a beauty of f(&#39;a&#39;) + f(&#39;b&#39;) + f(&#39;c&#39;) + f(&#39;d&#39;) = 5 There are 2 k-subsequences that have the maximum beauty, 5. Hence, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= s.length</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; Math; String; Combinatorics
TypeScript
function countKSubsequencesWithMaxBeauty(s: string, k: number): number { const f: number[] = new Array(26).fill(0); let cnt = 0; for (const c of s) { const i = c.charCodeAt(0) - 97; if (++f[i] === 1) { ++cnt; } } if (cnt < k) { return 0; } const mod = BigInt(10 ** 9 + 7); const vs: number[] = f.filter(v => v > 0).sort((a, b) => b - a); const val = vs[k - 1]; const x = vs.filter(v => v === val).length; let ans = 1n; for (const v of vs) { if (v === val) { break; } --k; ans = (ans * BigInt(v)) % mod; } const c: number[][] = new Array(x + 1).fill(0).map(() => new Array(k + 1).fill(0)); for (let i = 0; i <= x; ++i) { c[i][0] = 1; for (let j = 1; j <= Math.min(i, k); ++j) { c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % Number(mod); } } const qpow = (a: bigint, n: number): bigint => { let ans = 1n; for (; n; n >>>= 1) { if (n & 1) { ans = (ans * a) % BigInt(mod); } a = (a * a) % BigInt(mod); } return ans; }; ans = (((ans * BigInt(c[x][k])) % mod) * qpow(BigInt(val), k)) % mod; return Number(ans); }
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
C++
class Solution { public: int countSymmetricIntegers(int low, int high) { int ans = 0; auto f = [](int x) { string s = to_string(x); int n = s.size(); if (n & 1) { return 0; } int a = 0, b = 0; for (int i = 0; i < n / 2; ++i) { a += s[i] - '0'; b += s[n / 2 + i] - '0'; } return a == b ? 1 : 0; }; for (int x = low; x <= high; ++x) { ans += f(x); } return ans; } };
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
C#
public class Solution { public int CountSymmetricIntegers(int low, int high) { int ans = 0; for (int x = low; x <= high; ++x) { ans += f(x); } return ans; } private int f(int x) { string s = x.ToString(); int n = s.Length; if (n % 2 == 1) { return 0; } int a = 0, b = 0; for (int i = 0; i < n / 2; ++i) { a += s[i] - '0'; } for (int i = n / 2; i < n; ++i) { b += s[i] - '0'; } return a == b ? 1 : 0; } }
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
Go
func countSymmetricIntegers(low int, high int) (ans int) { f := func(x int) int { s := strconv.Itoa(x) n := len(s) if n&1 == 1 { return 0 } a, b := 0, 0 for i := 0; i < n/2; i++ { a += int(s[i] - '0') b += int(s[n/2+i] - '0') } if a == b { return 1 } return 0 } for x := low; x <= high; x++ { ans += f(x) } return }
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
Java
class Solution { public int countSymmetricIntegers(int low, int high) { int ans = 0; for (int x = low; x <= high; ++x) { ans += f(x); } return ans; } private int f(int x) { String s = "" + x; int n = s.length(); if (n % 2 == 1) { return 0; } int a = 0, b = 0; for (int i = 0; i < n / 2; ++i) { a += s.charAt(i) - '0'; } for (int i = n / 2; i < n; ++i) { b += s.charAt(i) - '0'; } return a == b ? 1 : 0; } }
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
Python
class Solution: def countSymmetricIntegers(self, low: int, high: int) -> int: def f(x: int) -> bool: s = str(x) if len(s) & 1: return False n = len(s) // 2 return sum(map(int, s[:n])) == sum(map(int, s[n:])) return sum(f(x) for x in range(low, high + 1))
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
Rust
impl Solution { pub fn count_symmetric_integers(low: i32, high: i32) -> i32 { let mut ans = 0; for x in low..=high { ans += Self::f(x); } ans } fn f(x: i32) -> i32 { let s = x.to_string(); let n = s.len(); if n % 2 == 1 { return 0; } let bytes = s.as_bytes(); let mut a = 0; let mut b = 0; for i in 0..n / 2 { a += (bytes[i] - b'0') as i32; } for i in n / 2..n { b += (bytes[i] - b'0') as i32; } if a == b { 1 } else { 0 } } }
2,843
Count Symmetric Integers
Easy
<p>You are given two positive integers <code>low</code> and <code>high</code>.</p> <p>An integer <code>x</code> consisting of <code>2 * n</code> digits is <strong>symmetric</strong> if the sum of the first <code>n</code> digits of <code>x</code> is equal to the sum of the last <code>n</code> digits of <code>x</code>. Numbers with an odd number of digits are never symmetric.</p> <p>Return <em>the <strong>number of symmetric</strong> integers in the range</em> <code>[low, high]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> low = 1, high = 100 <strong>Output:</strong> 9 <strong>Explanation:</strong> There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> low = 1200, high = 1230 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li> </ul>
Math; Enumeration
TypeScript
function countSymmetricIntegers(low: number, high: number): number { let ans = 0; const f = (x: number): number => { const s = x.toString(); const n = s.length; if (n & 1) { return 0; } let a = 0; let b = 0; for (let i = 0; i < n >> 1; ++i) { a += Number(s[i]); b += Number(s[(n >> 1) + i]); } return a === b ? 1 : 0; }; for (let x = low; x <= high; ++x) { ans += f(x); } return ans; }
2,844
Minimum Operations to Make a Special Number
Medium
<p>You are given a <strong>0-indexed</strong> string <code>num</code> representing a non-negative integer.</p> <p>In one operation, you can pick any digit of <code>num</code> and delete it. Note that if you delete all the digits of <code>num</code>, <code>num</code> becomes <code>0</code>.</p> <p>Return <em>the <strong>minimum number of operations</strong> required to make</em> <code>num</code> <i>special</i>.</p> <p>An integer <code>x</code> is considered <strong>special</strong> if it is divisible by <code>25</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;2245047&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Delete digits num[5] and num[6]. The resulting number is &quot;22450&quot; which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;2908305&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Delete digits num[3], num[4], and num[6]. The resulting number is &quot;2900&quot; which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> Delete digit num[0]. The resulting number is &quot;0&quot; which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 100</code></li> <li><code>num</code> only consists of digits <code>&#39;0&#39;</code> through <code>&#39;9&#39;</code>.</li> <li><code>num</code> does not contain any leading zeros.</li> </ul>
Greedy; Math; String; Enumeration
C++
class Solution { public: int minimumOperations(string num) { int n = num.size(); int f[n][25]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i, int k) -> int { if (i == n) { return k == 0 ? 0 : n; } if (f[i][k] != -1) { return f[i][k]; } f[i][k] = dfs(i + 1, k) + 1; f[i][k] = min(f[i][k], dfs(i + 1, (k * 10 + num[i] - '0') % 25)); return f[i][k]; }; return dfs(0, 0); } };
2,844
Minimum Operations to Make a Special Number
Medium
<p>You are given a <strong>0-indexed</strong> string <code>num</code> representing a non-negative integer.</p> <p>In one operation, you can pick any digit of <code>num</code> and delete it. Note that if you delete all the digits of <code>num</code>, <code>num</code> becomes <code>0</code>.</p> <p>Return <em>the <strong>minimum number of operations</strong> required to make</em> <code>num</code> <i>special</i>.</p> <p>An integer <code>x</code> is considered <strong>special</strong> if it is divisible by <code>25</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;2245047&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Delete digits num[5] and num[6]. The resulting number is &quot;22450&quot; which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;2908305&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Delete digits num[3], num[4], and num[6]. The resulting number is &quot;2900&quot; which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> Delete digit num[0]. The resulting number is &quot;0&quot; which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 100</code></li> <li><code>num</code> only consists of digits <code>&#39;0&#39;</code> through <code>&#39;9&#39;</code>.</li> <li><code>num</code> does not contain any leading zeros.</li> </ul>
Greedy; Math; String; Enumeration
Go
func minimumOperations(num string) int { n := len(num) f := make([][25]int, n) for i := range f { for j := range f[i] { f[i][j] = -1 } } var dfs func(i, k int) int dfs = func(i, k int) int { if i == n { if k == 0 { return 0 } return n } if f[i][k] != -1 { return f[i][k] } f[i][k] = dfs(i+1, k) + 1 f[i][k] = min(f[i][k], dfs(i+1, (k*10+int(num[i]-'0'))%25)) return f[i][k] } return dfs(0, 0) }
2,844
Minimum Operations to Make a Special Number
Medium
<p>You are given a <strong>0-indexed</strong> string <code>num</code> representing a non-negative integer.</p> <p>In one operation, you can pick any digit of <code>num</code> and delete it. Note that if you delete all the digits of <code>num</code>, <code>num</code> becomes <code>0</code>.</p> <p>Return <em>the <strong>minimum number of operations</strong> required to make</em> <code>num</code> <i>special</i>.</p> <p>An integer <code>x</code> is considered <strong>special</strong> if it is divisible by <code>25</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;2245047&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Delete digits num[5] and num[6]. The resulting number is &quot;22450&quot; which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;2908305&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Delete digits num[3], num[4], and num[6]. The resulting number is &quot;2900&quot; which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> Delete digit num[0]. The resulting number is &quot;0&quot; which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 100</code></li> <li><code>num</code> only consists of digits <code>&#39;0&#39;</code> through <code>&#39;9&#39;</code>.</li> <li><code>num</code> does not contain any leading zeros.</li> </ul>
Greedy; Math; String; Enumeration
Java
class Solution { private Integer[][] f; private String num; private int n; public int minimumOperations(String num) { n = num.length(); this.num = num; f = new Integer[n][25]; return dfs(0, 0); } private int dfs(int i, int k) { if (i == n) { return k == 0 ? 0 : n; } if (f[i][k] != null) { return f[i][k]; } f[i][k] = dfs(i + 1, k) + 1; f[i][k] = Math.min(f[i][k], dfs(i + 1, (k * 10 + num.charAt(i) - '0') % 25)); return f[i][k]; } }
2,844
Minimum Operations to Make a Special Number
Medium
<p>You are given a <strong>0-indexed</strong> string <code>num</code> representing a non-negative integer.</p> <p>In one operation, you can pick any digit of <code>num</code> and delete it. Note that if you delete all the digits of <code>num</code>, <code>num</code> becomes <code>0</code>.</p> <p>Return <em>the <strong>minimum number of operations</strong> required to make</em> <code>num</code> <i>special</i>.</p> <p>An integer <code>x</code> is considered <strong>special</strong> if it is divisible by <code>25</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;2245047&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Delete digits num[5] and num[6]. The resulting number is &quot;22450&quot; which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;2908305&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Delete digits num[3], num[4], and num[6]. The resulting number is &quot;2900&quot; which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> Delete digit num[0]. The resulting number is &quot;0&quot; which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 100</code></li> <li><code>num</code> only consists of digits <code>&#39;0&#39;</code> through <code>&#39;9&#39;</code>.</li> <li><code>num</code> does not contain any leading zeros.</li> </ul>
Greedy; Math; String; Enumeration
Python
class Solution: def minimumOperations(self, num: str) -> int: @cache def dfs(i: int, k: int) -> int: if i == n: return 0 if k == 0 else n ans = dfs(i + 1, k) + 1 ans = min(ans, dfs(i + 1, (k * 10 + int(num[i])) % 25)) return ans n = len(num) return dfs(0, 0)
2,844
Minimum Operations to Make a Special Number
Medium
<p>You are given a <strong>0-indexed</strong> string <code>num</code> representing a non-negative integer.</p> <p>In one operation, you can pick any digit of <code>num</code> and delete it. Note that if you delete all the digits of <code>num</code>, <code>num</code> becomes <code>0</code>.</p> <p>Return <em>the <strong>minimum number of operations</strong> required to make</em> <code>num</code> <i>special</i>.</p> <p>An integer <code>x</code> is considered <strong>special</strong> if it is divisible by <code>25</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;2245047&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> Delete digits num[5] and num[6]. The resulting number is &quot;22450&quot; which is special since it is divisible by 25. It can be shown that 2 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;2908305&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> Delete digits num[3], num[4], and num[6]. The resulting number is &quot;2900&quot; which is special since it is divisible by 25. It can be shown that 3 is the minimum number of operations required to get a special number.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;10&quot; <strong>Output:</strong> 1 <strong>Explanation:</strong> Delete digit num[0]. The resulting number is &quot;0&quot; which is special since it is divisible by 25. It can be shown that 1 is the minimum number of operations required to get a special number. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 100</code></li> <li><code>num</code> only consists of digits <code>&#39;0&#39;</code> through <code>&#39;9&#39;</code>.</li> <li><code>num</code> does not contain any leading zeros.</li> </ul>
Greedy; Math; String; Enumeration
TypeScript
function minimumOperations(num: string): number { const n = num.length; const f: number[][] = Array.from({ length: n }, () => Array.from({ length: 25 }, () => -1)); const dfs = (i: number, k: number): number => { if (i === n) { return k === 0 ? 0 : n; } if (f[i][k] !== -1) { return f[i][k]; } f[i][k] = dfs(i + 1, k) + 1; f[i][k] = Math.min(f[i][k], dfs(i + 1, (k * 10 + Number(num[i])) % 25)); return f[i][k]; }; return dfs(0, 0); }
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: long long countInterestingSubarrays(vector<int>& nums, int modulo, int k) { int n = nums.size(); vector<int> arr(n); for (int i = 0; i < n; ++i) { arr[i] = int(nums[i] % modulo == k); } unordered_map<int, int> cnt; cnt[0] = 1; long long ans = 0; int s = 0; for (int x : arr) { s += x; ans += cnt[(s - k + modulo) % modulo]; cnt[s % modulo]++; } return ans; } };
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
Go
func countInterestingSubarrays(nums []int, modulo int, k int) (ans int64) { arr := make([]int, len(nums)) for i, x := range nums { if x%modulo == k { arr[i] = 1 } } cnt := map[int]int{} cnt[0] = 1 s := 0 for _, x := range arr { s += x ans += int64(cnt[(s-k+modulo)%modulo]) cnt[s%modulo]++ } return }
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public long countInterestingSubarrays(List<Integer> nums, int modulo, int k) { int n = nums.size(); int[] arr = new int[n]; for (int i = 0; i < n; ++i) { arr[i] = nums.get(i) % modulo == k ? 1 : 0; } Map<Integer, Integer> cnt = new HashMap<>(); cnt.put(0, 1); long ans = 0; int s = 0; for (int x : arr) { s += x; ans += cnt.getOrDefault((s - k + modulo) % modulo, 0); cnt.merge(s % modulo, 1, Integer::sum); } return ans; } }
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int: arr = [int(x % modulo == k) for x in nums] cnt = Counter() cnt[0] = 1 ans = s = 0 for x in arr: s += x ans += cnt[(s - k) % modulo] cnt[s % modulo] += 1 return ans
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
Rust
use std::collections::HashMap; impl Solution { pub fn count_interesting_subarrays(nums: Vec<i32>, modulo: i32, k: i32) -> i64 { let mut arr: Vec<i32> = nums .iter() .map(|&x| if x % modulo == k { 1 } else { 0 }) .collect(); let mut cnt: HashMap<i32, i64> = HashMap::new(); cnt.insert(0, 1); let mut ans: i64 = 0; let mut s: i32 = 0; for x in arr { s += x; let key = (s - k).rem_euclid(modulo); ans += *cnt.get(&key).unwrap_or(&0); *cnt.entry(s % modulo).or_insert(0) += 1; } ans } }
2,845
Count of Interesting Subarrays
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>, an integer <code>modulo</code>, and an integer <code>k</code>.</p> <p>Your task is to find the count of subarrays that are <strong>interesting</strong>.</p> <p>A <strong>subarray</strong> <code>nums[l..r]</code> is <strong>interesting</strong> if the following condition holds:</p> <ul> <li>Let <code>cnt</code> be the number of indices <code>i</code> in the range <code>[l, r]</code> such that <code>nums[i] % modulo == k</code>. Then, <code>cnt % modulo == k</code>.</li> </ul> <p>Return <em>an integer denoting the count of interesting subarrays. </em></p> <p><span><strong>Note:</strong> A subarray is <em>a contiguous non-empty sequence of elements within an array</em>.</span></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,4], modulo = 2, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example the interesting subarrays are: The subarray nums[0..0] which is [3]. - There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..1] which is [3,2]. - There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. The subarray nums[0..2] which is [3,2,4]. - There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. - Hence, cnt = 1 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,9,6], modulo = 3, k = 0 <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6]. - There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. - Hence, cnt = 3 and cnt % modulo == k. The subarray nums[1..1] which is [1]. - There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. - Hence, cnt = 0 and cnt % modulo == k. It can be shown that there are no other interesting subarrays. So, the answer is 2.</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>1 &lt;= modulo &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt; modulo</code></li> </ul>
Array; Hash Table; Prefix Sum
TypeScript
function countInterestingSubarrays(nums: number[], modulo: number, k: number): number { const arr: number[] = []; for (const x of nums) { arr.push(x % modulo === k ? 1 : 0); } const cnt: Map<number, number> = new Map(); cnt.set(0, 1); let ans = 0; let s = 0; for (const x of arr) { s += x; ans += cnt.get((s - k + modulo) % modulo) || 0; cnt.set(s % modulo, (cnt.get(s % modulo) || 0) + 1); } return ans; }
2,846
Minimum Edge Weight Equilibrium Queries in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>You are also given a 2D integer array <code>queries</code> of length <code>m</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. For each query, find the <strong>minimum number of operations</strong> required to make the weight of every edge on the path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> equal. In one operation, you can choose any edge of the tree and change its weight to any value.</p> <p><strong>Note</strong> that:</p> <ul> <li>Queries are <strong>independent</strong> of each other, meaning that the tree returns to its <strong>initial state</strong> on each new query.</li> <li>The path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a<sub>i</sub></code> and ending with node <code>b<sub>i</sub></code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of length </em><code>m</code><em> where</em> <code>answer[i]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</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/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-6-1.png" style="width: 339px; height: 344px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]] <strong>Output:</strong> [0,0,1,3] <strong>Explanation:</strong> In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-9-1.png" style="width: 472px; height: 370px;" /> <pre> <strong>Input:</strong> n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]] <strong>Output:</strong> [1,2,2,3] <strong>Explanation:</strong> In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 26</code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> <li><code>1 &lt;= queries.length == m &lt;= 2 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> </ul>
Tree; Graph; Array; Strongly Connected Component
C++
class Solution { public: vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) { int m = 32 - __builtin_clz(n); vector<pair<int, int>> g[n]; int f[n][m]; int p[n]; int cnt[n][26]; int depth[n]; memset(f, 0, sizeof(f)); memset(cnt, 0, sizeof(cnt)); memset(depth, 0, sizeof(depth)); memset(p, 0, sizeof(p)); for (auto& e : edges) { int u = e[0], v = e[1], w = e[2] - 1; g[u].emplace_back(v, w); g[v].emplace_back(u, w); } queue<int> q; q.push(0); while (!q.empty()) { int i = q.front(); q.pop(); f[i][0] = p[i]; for (int j = 1; j < m; ++j) { f[i][j] = f[f[i][j - 1]][j - 1]; } for (auto& [j, w] : g[i]) { if (j != p[i]) { p[j] = i; memcpy(cnt[j], cnt[i], sizeof(cnt[i])); cnt[j][w]++; depth[j] = depth[i] + 1; q.push(j); } } } vector<int> ans; for (auto& qq : queries) { int u = qq[0], v = qq[1]; int x = u, y = v; if (depth[x] < depth[y]) { swap(x, y); } for (int j = m - 1; ~j; --j) { if (depth[x] - depth[y] >= (1 << j)) { x = f[x][j]; } } for (int j = m - 1; ~j; --j) { if (f[x][j] != f[y][j]) { x = f[x][j]; y = f[y][j]; } } if (x != y) { x = p[x]; } int mx = 0; for (int j = 0; j < 26; ++j) { mx = max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); } ans.push_back(depth[u] + depth[v] - 2 * depth[x] - mx); } return ans; } };
2,846
Minimum Edge Weight Equilibrium Queries in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>You are also given a 2D integer array <code>queries</code> of length <code>m</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. For each query, find the <strong>minimum number of operations</strong> required to make the weight of every edge on the path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> equal. In one operation, you can choose any edge of the tree and change its weight to any value.</p> <p><strong>Note</strong> that:</p> <ul> <li>Queries are <strong>independent</strong> of each other, meaning that the tree returns to its <strong>initial state</strong> on each new query.</li> <li>The path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a<sub>i</sub></code> and ending with node <code>b<sub>i</sub></code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of length </em><code>m</code><em> where</em> <code>answer[i]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</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/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-6-1.png" style="width: 339px; height: 344px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]] <strong>Output:</strong> [0,0,1,3] <strong>Explanation:</strong> In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-9-1.png" style="width: 472px; height: 370px;" /> <pre> <strong>Input:</strong> n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]] <strong>Output:</strong> [1,2,2,3] <strong>Explanation:</strong> In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 26</code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> <li><code>1 &lt;= queries.length == m &lt;= 2 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> </ul>
Tree; Graph; Array; Strongly Connected Component
Go
func minOperationsQueries(n int, edges [][]int, queries [][]int) []int { m := bits.Len(uint(n)) g := make([][][2]int, n) f := make([][]int, n) for i := range f { f[i] = make([]int, m) } p := make([]int, n) cnt := make([][26]int, n) cnt[0] = [26]int{} depth := make([]int, n) for _, e := range edges { u, v, w := e[0], e[1], e[2]-1 g[u] = append(g[u], [2]int{v, w}) g[v] = append(g[v], [2]int{u, w}) } q := []int{0} for len(q) > 0 { i := q[0] q = q[1:] f[i][0] = p[i] for j := 1; j < m; j++ { f[i][j] = f[f[i][j-1]][j-1] } for _, nxt := range g[i] { j, w := nxt[0], nxt[1] if j != p[i] { p[j] = i cnt[j] = [26]int{} for k := 0; k < 26; k++ { cnt[j][k] = cnt[i][k] } cnt[j][w]++ depth[j] = depth[i] + 1 q = append(q, j) } } } ans := make([]int, len(queries)) for i, qq := range queries { u, v := qq[0], qq[1] x, y := u, v if depth[x] < depth[y] { x, y = y, x } for j := m - 1; j >= 0; j-- { if depth[x]-depth[y] >= (1 << j) { x = f[x][j] } } for j := m - 1; j >= 0; j-- { if f[x][j] != f[y][j] { x, y = f[x][j], f[y][j] } } if x != y { x = p[x] } mx := 0 for j := 0; j < 26; j++ { mx = max(mx, cnt[u][j]+cnt[v][j]-2*cnt[x][j]) } ans[i] = depth[u] + depth[v] - 2*depth[x] - mx } return ans }
2,846
Minimum Edge Weight Equilibrium Queries in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>You are also given a 2D integer array <code>queries</code> of length <code>m</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. For each query, find the <strong>minimum number of operations</strong> required to make the weight of every edge on the path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> equal. In one operation, you can choose any edge of the tree and change its weight to any value.</p> <p><strong>Note</strong> that:</p> <ul> <li>Queries are <strong>independent</strong> of each other, meaning that the tree returns to its <strong>initial state</strong> on each new query.</li> <li>The path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a<sub>i</sub></code> and ending with node <code>b<sub>i</sub></code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of length </em><code>m</code><em> where</em> <code>answer[i]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</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/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-6-1.png" style="width: 339px; height: 344px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]] <strong>Output:</strong> [0,0,1,3] <strong>Explanation:</strong> In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-9-1.png" style="width: 472px; height: 370px;" /> <pre> <strong>Input:</strong> n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]] <strong>Output:</strong> [1,2,2,3] <strong>Explanation:</strong> In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 26</code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> <li><code>1 &lt;= queries.length == m &lt;= 2 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> </ul>
Tree; Graph; Array; Strongly Connected Component
Java
class Solution { public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { int m = 32 - Integer.numberOfLeadingZeros(n); List<int[]>[] g = new List[n]; Arrays.setAll(g, i -> new ArrayList<>()); int[][] f = new int[n][m]; int[] p = new int[n]; int[][] cnt = new int[n][0]; int[] depth = new int[n]; for (var e : edges) { int u = e[0], v = e[1], w = e[2] - 1; g[u].add(new int[] {v, w}); g[v].add(new int[] {u, w}); } cnt[0] = new int[26]; Deque<Integer> q = new ArrayDeque<>(); q.offer(0); while (!q.isEmpty()) { int i = q.poll(); f[i][0] = p[i]; for (int j = 1; j < m; ++j) { f[i][j] = f[f[i][j - 1]][j - 1]; } for (var nxt : g[i]) { int j = nxt[0], w = nxt[1]; if (j != p[i]) { p[j] = i; cnt[j] = cnt[i].clone(); cnt[j][w]++; depth[j] = depth[i] + 1; q.offer(j); } } } int k = queries.length; int[] ans = new int[k]; for (int i = 0; i < k; ++i) { int u = queries[i][0], v = queries[i][1]; int x = u, y = v; if (depth[x] < depth[y]) { int t = x; x = y; y = t; } for (int j = m - 1; j >= 0; --j) { if (depth[x] - depth[y] >= (1 << j)) { x = f[x][j]; } } for (int j = m - 1; j >= 0; --j) { if (f[x][j] != f[y][j]) { x = f[x][j]; y = f[y][j]; } } if (x != y) { x = p[x]; } int mx = 0; for (int j = 0; j < 26; ++j) { mx = Math.max(mx, cnt[u][j] + cnt[v][j] - 2 * cnt[x][j]); } ans[i] = depth[u] + depth[v] - 2 * depth[x] - mx; } return ans; } }
2,846
Minimum Edge Weight Equilibrium Queries in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code> in the tree.</p> <p>You are also given a 2D integer array <code>queries</code> of length <code>m</code>, where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. For each query, find the <strong>minimum number of operations</strong> required to make the weight of every edge on the path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> equal. In one operation, you can choose any edge of the tree and change its weight to any value.</p> <p><strong>Note</strong> that:</p> <ul> <li>Queries are <strong>independent</strong> of each other, meaning that the tree returns to its <strong>initial state</strong> on each new query.</li> <li>The path from <code>a<sub>i</sub></code> to <code>b<sub>i</sub></code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a<sub>i</sub></code> and ending with node <code>b<sub>i</sub></code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of length </em><code>m</code><em> where</em> <code>answer[i]</code> <em>is the answer to the</em> <code>i<sup>th</sup></code> <em>query.</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/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-6-1.png" style="width: 339px; height: 344px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]] <strong>Output:</strong> [0,0,1,3] <strong>Explanation:</strong> In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0. In the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0. In the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1. In the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2846.Minimum%20Edge%20Weight%20Equilibrium%20Queries%20in%20a%20Tree/images/graph-9-1.png" style="width: 472px; height: 370px;" /> <pre> <strong>Input:</strong> n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]] <strong>Output:</strong> [1,2,2,3] <strong>Explanation:</strong> In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1. In the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2. In the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2. In the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3. For each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from a<sub>i</sub> to b<sub>i</sub>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 26</code></li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> <li><code>1 &lt;= queries.length == m &lt;= 2 * 10<sup>4</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> </ul>
Tree; Graph; Array; Strongly Connected Component
Python
class Solution: def minOperationsQueries( self, n: int, edges: List[List[int]], queries: List[List[int]] ) -> List[int]: m = n.bit_length() g = [[] for _ in range(n)] f = [[0] * m for _ in range(n)] p = [0] * n cnt = [None] * n depth = [0] * n for u, v, w in edges: g[u].append((v, w - 1)) g[v].append((u, w - 1)) cnt[0] = [0] * 26 q = deque([0]) while q: i = q.popleft() f[i][0] = p[i] for j in range(1, m): f[i][j] = f[f[i][j - 1]][j - 1] for j, w in g[i]: if j != p[i]: p[j] = i cnt[j] = cnt[i][:] cnt[j][w] += 1 depth[j] = depth[i] + 1 q.append(j) ans = [] for u, v in queries: x, y = u, v if depth[x] < depth[y]: x, y = y, x for j in reversed(range(m)): if depth[x] - depth[y] >= (1 << j): x = f[x][j] for j in reversed(range(m)): if f[x][j] != f[y][j]: x, y = f[x][j], f[y][j] if x != y: x = p[x] mx = max(cnt[u][j] + cnt[v][j] - 2 * cnt[x][j] for j in range(26)) ans.append(depth[u] + depth[v] - 2 * depth[x] - mx) return ans
2,847
Smallest Number With Given Digit Product
Medium
<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>a string representing the <strong>smallest positive</strong> integer such that the product of its digits is equal to</em> <code>n</code><em>, or </em><code>&quot;-1&quot;</code><em> if no such number exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 105 <strong>Output:</strong> &quot;357&quot; <strong>Explanation:</strong> 3 * 5 * 7 = 105. It can be shown that 357 is the smallest number with a product of digits equal to 105. So the answer would be &quot;357&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> &quot;7&quot; <strong>Explanation:</strong> Since 7 has only one digit, its product of digits would be 7. We will show that 7 is the smallest number with a product of digits equal to 7. Since the product of numbers 1 to 6 is 1 to 6 respectively, so &quot;7&quot; would be the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 44 <strong>Output:</strong> &quot;-1&quot; <strong>Explanation:</strong> It can be shown that there is no number such that its product of digits is equal to 44. So the answer would be &quot;-1&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>18</sup></code></li> </ul>
Greedy; Math
C++
class Solution { public: string smallestNumber(long long n) { int cnt[10]{}; for (int i = 9; i > 1; --i) { while (n % i == 0) { n /= i; ++cnt[i]; } } if (n > 1) { return "-1"; } string ans; for (int i = 2; i < 10; ++i) { ans += string(cnt[i], '0' + i); } return ans == "" ? "1" : ans; } };
2,847
Smallest Number With Given Digit Product
Medium
<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>a string representing the <strong>smallest positive</strong> integer such that the product of its digits is equal to</em> <code>n</code><em>, or </em><code>&quot;-1&quot;</code><em> if no such number exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 105 <strong>Output:</strong> &quot;357&quot; <strong>Explanation:</strong> 3 * 5 * 7 = 105. It can be shown that 357 is the smallest number with a product of digits equal to 105. So the answer would be &quot;357&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> &quot;7&quot; <strong>Explanation:</strong> Since 7 has only one digit, its product of digits would be 7. We will show that 7 is the smallest number with a product of digits equal to 7. Since the product of numbers 1 to 6 is 1 to 6 respectively, so &quot;7&quot; would be the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 44 <strong>Output:</strong> &quot;-1&quot; <strong>Explanation:</strong> It can be shown that there is no number such that its product of digits is equal to 44. So the answer would be &quot;-1&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>18</sup></code></li> </ul>
Greedy; Math
Go
func smallestNumber(n int64) string { cnt := [10]int{} for i := 9; i > 1; i-- { for n%int64(i) == 0 { cnt[i]++ n /= int64(i) } } if n != 1 { return "-1" } sb := &strings.Builder{} for i := 2; i < 10; i++ { for j := 0; j < cnt[i]; j++ { sb.WriteByte(byte(i) + '0') } } ans := sb.String() if len(ans) > 0 { return ans } return "1" }
2,847
Smallest Number With Given Digit Product
Medium
<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>a string representing the <strong>smallest positive</strong> integer such that the product of its digits is equal to</em> <code>n</code><em>, or </em><code>&quot;-1&quot;</code><em> if no such number exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 105 <strong>Output:</strong> &quot;357&quot; <strong>Explanation:</strong> 3 * 5 * 7 = 105. It can be shown that 357 is the smallest number with a product of digits equal to 105. So the answer would be &quot;357&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> &quot;7&quot; <strong>Explanation:</strong> Since 7 has only one digit, its product of digits would be 7. We will show that 7 is the smallest number with a product of digits equal to 7. Since the product of numbers 1 to 6 is 1 to 6 respectively, so &quot;7&quot; would be the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 44 <strong>Output:</strong> &quot;-1&quot; <strong>Explanation:</strong> It can be shown that there is no number such that its product of digits is equal to 44. So the answer would be &quot;-1&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>18</sup></code></li> </ul>
Greedy; Math
Java
class Solution { public String smallestNumber(long n) { int[] cnt = new int[10]; for (int i = 9; i > 1; --i) { while (n % i == 0) { ++cnt[i]; n /= i; } } if (n > 1) { return "-1"; } StringBuilder sb = new StringBuilder(); for (int i = 2; i < 10; ++i) { while (cnt[i] > 0) { sb.append(i); --cnt[i]; } } String ans = sb.toString(); return ans.isEmpty() ? "1" : ans; } }
2,847
Smallest Number With Given Digit Product
Medium
<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>a string representing the <strong>smallest positive</strong> integer such that the product of its digits is equal to</em> <code>n</code><em>, or </em><code>&quot;-1&quot;</code><em> if no such number exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 105 <strong>Output:</strong> &quot;357&quot; <strong>Explanation:</strong> 3 * 5 * 7 = 105. It can be shown that 357 is the smallest number with a product of digits equal to 105. So the answer would be &quot;357&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> &quot;7&quot; <strong>Explanation:</strong> Since 7 has only one digit, its product of digits would be 7. We will show that 7 is the smallest number with a product of digits equal to 7. Since the product of numbers 1 to 6 is 1 to 6 respectively, so &quot;7&quot; would be the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 44 <strong>Output:</strong> &quot;-1&quot; <strong>Explanation:</strong> It can be shown that there is no number such that its product of digits is equal to 44. So the answer would be &quot;-1&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>18</sup></code></li> </ul>
Greedy; Math
Python
class Solution: def smallestNumber(self, n: int) -> str: cnt = [0] * 10 for i in range(9, 1, -1): while n % i == 0: n //= i cnt[i] += 1 if n > 1: return "-1" ans = "".join(str(i) * cnt[i] for i in range(2, 10)) return ans if ans else "1"
2,848
Points That Intersect With Cars
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code> representing the coordinates of the cars parking on a number line. For any index <code>i</code>, <code>nums[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> where <code>start<sub>i</sub></code> is the starting point of the <code>i<sup>th</sup></code> car and <code>end<sub>i</sub></code> is the ending point of the <code>i<sup>th</sup></code> car.</p> <p>Return <em>the number of integer points on the line that are covered with <strong>any part</strong> of a car.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[3,6],[1,5],[4,7]] <strong>Output:</strong> 7 <strong>Explanation:</strong> All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,3],[5,8]] <strong>Output:</strong> 7 <strong>Explanation:</strong> Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i].length == 2</code></li> <li><code><font face="monospace">1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 100</font></code></li> </ul>
Array; Hash Table; Prefix Sum
C++
class Solution { public: int numberOfPoints(vector<vector<int>>& nums) { int d[102]{}; for (const auto& e : nums) { int start = e[0], end = e[1]; ++d[start]; --d[end + 1]; } int ans = 0, s = 0; for (int x : d) { s += x; ans += s > 0; } return ans; } };
2,848
Points That Intersect With Cars
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code> representing the coordinates of the cars parking on a number line. For any index <code>i</code>, <code>nums[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> where <code>start<sub>i</sub></code> is the starting point of the <code>i<sup>th</sup></code> car and <code>end<sub>i</sub></code> is the ending point of the <code>i<sup>th</sup></code> car.</p> <p>Return <em>the number of integer points on the line that are covered with <strong>any part</strong> of a car.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[3,6],[1,5],[4,7]] <strong>Output:</strong> 7 <strong>Explanation:</strong> All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,3],[5,8]] <strong>Output:</strong> 7 <strong>Explanation:</strong> Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i].length == 2</code></li> <li><code><font face="monospace">1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 100</font></code></li> </ul>
Array; Hash Table; Prefix Sum
Go
func numberOfPoints(nums [][]int) (ans int) { d := [102]int{} for _, e := range nums { start, end := e[0], e[1] d[start]++ d[end+1]-- } s := 0 for _, x := range d { s += x if s > 0 { ans++ } } return }
2,848
Points That Intersect With Cars
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code> representing the coordinates of the cars parking on a number line. For any index <code>i</code>, <code>nums[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> where <code>start<sub>i</sub></code> is the starting point of the <code>i<sup>th</sup></code> car and <code>end<sub>i</sub></code> is the ending point of the <code>i<sup>th</sup></code> car.</p> <p>Return <em>the number of integer points on the line that are covered with <strong>any part</strong> of a car.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[3,6],[1,5],[4,7]] <strong>Output:</strong> 7 <strong>Explanation:</strong> All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,3],[5,8]] <strong>Output:</strong> 7 <strong>Explanation:</strong> Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i].length == 2</code></li> <li><code><font face="monospace">1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 100</font></code></li> </ul>
Array; Hash Table; Prefix Sum
Java
class Solution { public int numberOfPoints(List<List<Integer>> nums) { int[] d = new int[102]; for (var e : nums) { int start = e.get(0), end = e.get(1); ++d[start]; --d[end + 1]; } int ans = 0, s = 0; for (int x : d) { s += x; if (s > 0) { ++ans; } } return ans; } }
2,848
Points That Intersect With Cars
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code> representing the coordinates of the cars parking on a number line. For any index <code>i</code>, <code>nums[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> where <code>start<sub>i</sub></code> is the starting point of the <code>i<sup>th</sup></code> car and <code>end<sub>i</sub></code> is the ending point of the <code>i<sup>th</sup></code> car.</p> <p>Return <em>the number of integer points on the line that are covered with <strong>any part</strong> of a car.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[3,6],[1,5],[4,7]] <strong>Output:</strong> 7 <strong>Explanation:</strong> All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,3],[5,8]] <strong>Output:</strong> 7 <strong>Explanation:</strong> Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i].length == 2</code></li> <li><code><font face="monospace">1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 100</font></code></li> </ul>
Array; Hash Table; Prefix Sum
Python
class Solution: def numberOfPoints(self, nums: List[List[int]]) -> int: m = 102 d = [0] * m for start, end in nums: d[start] += 1 d[end + 1] -= 1 return sum(s > 0 for s in accumulate(d))
2,848
Points That Intersect With Cars
Easy
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code> representing the coordinates of the cars parking on a number line. For any index <code>i</code>, <code>nums[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> where <code>start<sub>i</sub></code> is the starting point of the <code>i<sup>th</sup></code> car and <code>end<sub>i</sub></code> is the ending point of the <code>i<sup>th</sup></code> car.</p> <p>Return <em>the number of integer points on the line that are covered with <strong>any part</strong> of a car.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[3,6],[1,5],[4,7]] <strong>Output:</strong> 7 <strong>Explanation:</strong> All the points from 1 to 7 intersect at least one car, therefore the answer would be 7. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,3],[5,8]] <strong>Output:</strong> 7 <strong>Explanation:</strong> Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i].length == 2</code></li> <li><code><font face="monospace">1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 100</font></code></li> </ul>
Array; Hash Table; Prefix Sum
TypeScript
function numberOfPoints(nums: number[][]): number { const d: number[] = Array(102).fill(0); for (const [start, end] of nums) { ++d[start]; --d[end + 1]; } let ans = 0; let s = 0; for (const x of d) { s += x; ans += s > 0 ? 1 : 0; } return ans; }
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
C++
class Solution { public: bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { if (sx == fx && sy == fy) { return t != 1; } int dx = abs(fx - sx), dy = abs(fy - sy); return max(dx, dy) <= t; } };
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
C#
public class Solution { public bool IsReachableAtTime(int sx, int sy, int fx, int fy, int t) { if (sx == fx && sy == fy) { return t != 1; } return Math.Max(Math.Abs(sx - fx), Math.Abs(sy - fy)) <= t; } }
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
Go
func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool { if sx == fx && sy == fy { return t != 1 } dx := abs(sx - fx) dy := abs(sy - fy) return max(dx, dy) <= t } func abs(x int) int { if x < 0 { return -x } return x }
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
Java
class Solution { public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { if (sx == fx && sy == fy) { return t != 1; } int dx = Math.abs(sx - fx); int dy = Math.abs(sy - fy); return Math.max(dx, dy) <= t; } }
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
Python
class Solution: def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: if sx == fx and sy == fy: return t != 1 dx = abs(sx - fx) dy = abs(sy - fy) return max(dx, dy) <= t
2,849
Determine if a Cell Is Reachable at a Given Time
Medium
<p>You are given four integers <code>sx</code>, <code>sy</code>, <code>fx</code>, <code>fy</code>, and a <strong>non-negative</strong> integer <code>t</code>.</p> <p>In an infinite 2D grid, you start at the cell <code>(sx, sy)</code>. Each second, you <strong>must</strong> move to any of its adjacent cells.</p> <p>Return <code>true</code> <em>if you can reach cell </em><code>(fx, fy)</code> <em>after<strong> exactly</strong></em> <code>t</code> <strong><em>seconds</em></strong>, <em>or</em> <code>false</code> <em>otherwise</em>.</p> <p>A cell&#39;s <strong>adjacent cells</strong> are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example2.svg" style="width: 443px; height: 243px;" /> <pre> <strong>Input:</strong> sx = 2, sy = 4, fx = 7, fy = 7, t = 6 <strong>Output:</strong> true <strong>Explanation:</strong> Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2849.Determine%20if%20a%20Cell%20Is%20Reachable%20at%20a%20Given%20Time/images/example1.svg" style="width: 383px; height: 202px;" /> <pre> <strong>Input:</strong> sx = 3, sy = 1, fx = 7, fy = 3, t = 3 <strong>Output:</strong> false <strong>Explanation:</strong> Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= sx, sy, fx, fy &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= t &lt;= 10<sup>9</sup></code></li> </ul>
Math
TypeScript
function isReachableAtTime(sx: number, sy: number, fx: number, fy: number, t: number): boolean { if (sx === fx && sy === fy) { return t !== 1; } const dx = Math.abs(sx - fx); const dy = Math.abs(sy - fy); return Math.max(dx, dy) <= t; }