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,871
Split Array Into Maximum Number of Subarrays
Medium
<p>You are given an array <code>nums</code> consisting of <strong>non-negative</strong> integers.</p> <p>We define the score of subarray <code>nums[l..r]</code> such that <code>l &lt;= r</code> as <code>nums[l] AND nums[l + 1] AND ... AND nums[r]</code> where <strong>AND</strong> is the bitwise <code>AND</code> operation.</p> <p>Consider splitting the array into one or more subarrays such that the following conditions are satisfied:</p> <ul> <li><strong>E</strong><strong>ach</strong> element of the array belongs to <strong>exactly</strong> one subarray.</li> <li>The sum of scores of the subarrays is the <strong>minimum</strong> possible.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of subarrays in a split that satisfies the conditions above.</em></p> <p>A <strong>subarray</strong> is a contiguous part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,2,0,1,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can split the array into the following subarrays: - [1,0]. The score of this subarray is 1 AND 0 = 0. - [2,0]. The score of this subarray is 2 AND 0 = 0. - [1,2]. The score of this subarray is 1 AND 2 = 0. The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,7,1,3] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 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>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
TypeScript
function maxSubarrays(nums: number[]): number { let [ans, score] = [1, -1]; for (const num of nums) { score &= num; if (score === 0) { --score; ++ans; } } return ans == 1 ? 1 : ans - 1; }
2,872
Maximum Number of K-Divisible Components
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] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>values</code> of length <code>n</code>, where <code>values[i]</code> is the <strong>value</strong> associated with the <code>i<sup>th</sup></code> node, and an integer <code>k</code>.</p> <p>A <strong>valid split</strong> of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by <code>k</code>, where the <strong>value of a connected component</strong> is the sum of the values of its nodes.</p> <p>Return <em>the <strong>maximum number of components</strong> in any valid split</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/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example12-cropped2svg.jpg" style="width: 1024px; height: 453px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> We remove the edge connecting node 1 with 2. The resulting split is valid because: - The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. - The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. It can be shown that no other valid split has more than 2 connected components.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example21svg-1.jpg" style="width: 999px; height: 338px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: - The value of the component containing node 0 is values[0] = 3. - The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. - The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. It can be shown that no other valid split has more than 3 connected components. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>values.length == n</code></li> <li><code>0 &lt;= values[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> <li>Sum of <code>values</code> is divisible by <code>k</code>.</li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search
C++
class Solution { public: int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { int ans = 0; vector<int> g[n]; for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } function<long long(int, int)> dfs = [&](int i, int fa) { long long s = values[i]; for (int j : g[i]) { if (j != fa) { s += dfs(j, i); } } ans += s % k == 0; return s; }; dfs(0, -1); return ans; } };
2,872
Maximum Number of K-Divisible Components
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] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>values</code> of length <code>n</code>, where <code>values[i]</code> is the <strong>value</strong> associated with the <code>i<sup>th</sup></code> node, and an integer <code>k</code>.</p> <p>A <strong>valid split</strong> of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by <code>k</code>, where the <strong>value of a connected component</strong> is the sum of the values of its nodes.</p> <p>Return <em>the <strong>maximum number of components</strong> in any valid split</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/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example12-cropped2svg.jpg" style="width: 1024px; height: 453px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> We remove the edge connecting node 1 with 2. The resulting split is valid because: - The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. - The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. It can be shown that no other valid split has more than 2 connected components.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example21svg-1.jpg" style="width: 999px; height: 338px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: - The value of the component containing node 0 is values[0] = 3. - The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. - The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. It can be shown that no other valid split has more than 3 connected components. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>values.length == n</code></li> <li><code>0 &lt;= values[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> <li>Sum of <code>values</code> is divisible by <code>k</code>.</li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search
Go
func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) (ans int) { g := make([][]int, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } var dfs func(int, int) int dfs = func(i, fa int) int { s := values[i] for _, j := range g[i] { if j != fa { s += dfs(j, i) } } if s%k == 0 { ans++ } return s } dfs(0, -1) return }
2,872
Maximum Number of K-Divisible Components
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] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>values</code> of length <code>n</code>, where <code>values[i]</code> is the <strong>value</strong> associated with the <code>i<sup>th</sup></code> node, and an integer <code>k</code>.</p> <p>A <strong>valid split</strong> of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by <code>k</code>, where the <strong>value of a connected component</strong> is the sum of the values of its nodes.</p> <p>Return <em>the <strong>maximum number of components</strong> in any valid split</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/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example12-cropped2svg.jpg" style="width: 1024px; height: 453px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> We remove the edge connecting node 1 with 2. The resulting split is valid because: - The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. - The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. It can be shown that no other valid split has more than 2 connected components.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example21svg-1.jpg" style="width: 999px; height: 338px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: - The value of the component containing node 0 is values[0] = 3. - The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. - The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. It can be shown that no other valid split has more than 3 connected components. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>values.length == n</code></li> <li><code>0 &lt;= values[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> <li>Sum of <code>values</code> is divisible by <code>k</code>.</li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search
Java
class Solution { private int ans; private List<Integer>[] g; private int[] values; private int k; public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { g = new List[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (int[] e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } this.values = values; this.k = k; dfs(0, -1); return ans; } private long dfs(int i, int fa) { long s = values[i]; for (int j : g[i]) { if (j != fa) { s += dfs(j, i); } } ans += s % k == 0 ? 1 : 0; return s; } }
2,872
Maximum Number of K-Divisible Components
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] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>values</code> of length <code>n</code>, where <code>values[i]</code> is the <strong>value</strong> associated with the <code>i<sup>th</sup></code> node, and an integer <code>k</code>.</p> <p>A <strong>valid split</strong> of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by <code>k</code>, where the <strong>value of a connected component</strong> is the sum of the values of its nodes.</p> <p>Return <em>the <strong>maximum number of components</strong> in any valid split</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/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example12-cropped2svg.jpg" style="width: 1024px; height: 453px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> We remove the edge connecting node 1 with 2. The resulting split is valid because: - The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. - The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. It can be shown that no other valid split has more than 2 connected components.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example21svg-1.jpg" style="width: 999px; height: 338px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: - The value of the component containing node 0 is values[0] = 3. - The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. - The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. It can be shown that no other valid split has more than 3 connected components. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>values.length == n</code></li> <li><code>0 &lt;= values[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> <li>Sum of <code>values</code> is divisible by <code>k</code>.</li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search
Python
class Solution: def maxKDivisibleComponents( self, n: int, edges: List[List[int]], values: List[int], k: int ) -> int: def dfs(i: int, fa: int) -> int: s = values[i] for j in g[i]: if j != fa: s += dfs(j, i) nonlocal ans ans += s % k == 0 return s g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) ans = 0 dfs(0, -1) return ans
2,872
Maximum Number of K-Divisible Components
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] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p> <p>You are also given a <strong>0-indexed</strong> integer array <code>values</code> of length <code>n</code>, where <code>values[i]</code> is the <strong>value</strong> associated with the <code>i<sup>th</sup></code> node, and an integer <code>k</code>.</p> <p>A <strong>valid split</strong> of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by <code>k</code>, where the <strong>value of a connected component</strong> is the sum of the values of its nodes.</p> <p>Return <em>the <strong>maximum number of components</strong> in any valid split</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/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example12-cropped2svg.jpg" style="width: 1024px; height: 453px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> We remove the edge connecting node 1 with 2. The resulting split is valid because: - The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12. - The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6. It can be shown that no other valid split has more than 2 connected components.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2872.Maximum%20Number%20of%20K-Divisible%20Components/images/example21svg-1.jpg" style="width: 999px; height: 338px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because: - The value of the component containing node 0 is values[0] = 3. - The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9. - The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6. It can be shown that no other valid split has more than 3 connected components. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>values.length == n</code></li> <li><code>0 &lt;= values[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> <li>Sum of <code>values</code> is divisible by <code>k</code>.</li> <li>The input is generated such that <code>edges</code> represents a valid tree.</li> </ul>
Tree; Depth-First Search
TypeScript
function maxKDivisibleComponents( n: number, edges: number[][], values: number[], k: number, ): number { const g: number[][] = Array.from({ length: n }, () => []); for (const [a, b] of edges) { g[a].push(b); g[b].push(a); } let ans = 0; const dfs = (i: number, fa: number): number => { let s = values[i]; for (const j of g[i]) { if (j !== fa) { s += dfs(j, i); } } if (s % k === 0) { ++ans; } return s; }; dfs(0, -1); return ans; }
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
C++
class Solution { public: long long maximumTripletValue(vector<int>& nums) { long long ans = 0, mxDiff = 0; int mx = 0; for (int x : nums) { ans = max(ans, mxDiff * x); mxDiff = max(mxDiff, 1LL * mx - x); mx = max(mx, x); } return ans; } };
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Go
func maximumTripletValue(nums []int) int64 { ans, mx, mxDiff := 0, 0, 0 for _, x := range nums { ans = max(ans, mxDiff*x) mxDiff = max(mxDiff, mx-x) mx = max(mx, x) } return int64(ans) }
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Java
class Solution { public long maximumTripletValue(int[] nums) { long ans = 0, mxDiff = 0; int mx = 0; for (int x : nums) { ans = Math.max(ans, mxDiff * x); mxDiff = Math.max(mxDiff, mx - x); mx = Math.max(mx, x); } return ans; } }
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Python
class Solution: def maximumTripletValue(self, nums: List[int]) -> int: ans = mx = mx_diff = 0 for x in nums: ans = max(ans, mx_diff * x) mx_diff = max(mx_diff, mx - x) mx = max(mx, x) return ans
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Rust
impl Solution { pub fn maximum_triplet_value(nums: Vec<i32>) -> i64 { let mut ans: i64 = 0; let mut mx: i32 = 0; let mut mx_diff: i32 = 0; for &x in &nums { ans = ans.max(mx_diff as i64 * x as i64); mx_diff = mx_diff.max(mx - x); mx = mx.max(x); } ans } }
2,873
Maximum Value of an Ordered Triplet I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code>. If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
TypeScript
function maximumTripletValue(nums: number[]): number { let [ans, mx, mxDiff] = [0, 0, 0]; for (const x of nums) { ans = Math.max(ans, mxDiff * x); mxDiff = Math.max(mxDiff, mx - x); mx = Math.max(mx, x); } return ans; }
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
C++
class Solution { public: long long maximumTripletValue(vector<int>& nums) { long long ans = 0, mxDiff = 0; int mx = 0; for (int x : nums) { ans = max(ans, mxDiff * x); mxDiff = max(mxDiff, 1LL * mx - x); mx = max(mx, x); } return ans; } };
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Go
func maximumTripletValue(nums []int) int64 { ans, mx, mxDiff := 0, 0, 0 for _, x := range nums { ans = max(ans, mxDiff*x) mxDiff = max(mxDiff, mx-x) mx = max(mx, x) } return int64(ans) }
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Java
class Solution { public long maximumTripletValue(int[] nums) { long ans = 0, mxDiff = 0; int mx = 0; for (int x : nums) { ans = Math.max(ans, mxDiff * x); mxDiff = Math.max(mxDiff, mx - x); mx = Math.max(mx, x); } return ans; } }
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Python
class Solution: def maximumTripletValue(self, nums: List[int]) -> int: ans = mx = mx_diff = 0 for x in nums: ans = max(ans, mx_diff * x) mx_diff = max(mx_diff, mx - x) mx = max(mx, x) return ans
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
Rust
impl Solution { pub fn maximum_triplet_value(nums: Vec<i32>) -> i64 { let mut ans: i64 = 0; let mut mx: i32 = 0; let mut mx_diff: i32 = 0; for &x in &nums { ans = ans.max(mx_diff as i64 * x as i64); mx_diff = mx_diff.max(mx - x); mx = mx.max(x); } ans } }
2,874
Maximum Value of an Ordered Triplet II
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>Return <em><strong>the maximum value over all triplets of indices</strong></em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code><em>. </em>If all such triplets have a negative value, return <code>0</code>.</p> <p>The <strong>value of a triplet of indices</strong> <code>(i, j, k)</code> is equal to <code>(nums[i] - nums[j]) * nums[k]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,6,1,2,7] <strong>Output:</strong> 77 <strong>Explanation:</strong> The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77. It can be shown that there are no ordered triplets of indices with a value greater than 77. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,10,3,4,19] <strong>Output:</strong> 133 <strong>Explanation:</strong> The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133. It can be shown that there are no ordered triplets of indices with a value greater than 133. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array
TypeScript
function maximumTripletValue(nums: number[]): number { let [ans, mx, mxDiff] = [0, 0, 0]; for (const x of nums) { ans = Math.max(ans, mxDiff * x); mxDiff = Math.max(mxDiff, mx - x); mx = Math.max(mx, x); } return ans; }
2,875
Minimum Size Subarray in Infinite Array
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and an integer <code>target</code>.</p> <p>A <strong>0-indexed</strong> array <code>infinite_nums</code> is generated by infinitely appending the elements of <code>nums</code> to itself.</p> <p>Return <em>the length of the <strong>shortest</strong> subarray of the array </em><code>infinite_nums</code><em> with a sum equal to </em><code>target</code><em>.</em> If there is no such subarray return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,2,3], target = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8], target = 3 <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum; Sliding Window
C++
class Solution { public: int minSizeSubarray(vector<int>& nums, int target) { long long s = accumulate(nums.begin(), nums.end(), 0LL); int n = nums.size(); int a = 0; if (target > s) { a = n * (target / s); target -= target / s * s; } if (target == s) { return n; } unordered_map<int, int> pos{{0, -1}}; long long pre = 0; int b = 1 << 30; for (int i = 0; i < n; ++i) { pre += nums[i]; if (pos.count(pre - target)) { b = min(b, i - pos[pre - target]); } if (pos.count(pre - (s - target))) { b = min(b, n - (i - pos[pre - (s - target)])); } pos[pre] = i; } return b == 1 << 30 ? -1 : a + b; } };
2,875
Minimum Size Subarray in Infinite Array
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and an integer <code>target</code>.</p> <p>A <strong>0-indexed</strong> array <code>infinite_nums</code> is generated by infinitely appending the elements of <code>nums</code> to itself.</p> <p>Return <em>the length of the <strong>shortest</strong> subarray of the array </em><code>infinite_nums</code><em> with a sum equal to </em><code>target</code><em>.</em> If there is no such subarray return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,2,3], target = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8], target = 3 <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum; Sliding Window
Go
func minSizeSubarray(nums []int, target int) int { s := 0 for _, x := range nums { s += x } n := len(nums) a := 0 if target > s { a = n * (target / s) target -= target / s * s } if target == s { return n } pos := map[int]int{0: -1} pre := 0 b := 1 << 30 for i, x := range nums { pre += x if j, ok := pos[pre-target]; ok { b = min(b, i-j) } if j, ok := pos[pre-(s-target)]; ok { b = min(b, n-(i-j)) } pos[pre] = i } if b == 1<<30 { return -1 } return a + b }
2,875
Minimum Size Subarray in Infinite Array
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and an integer <code>target</code>.</p> <p>A <strong>0-indexed</strong> array <code>infinite_nums</code> is generated by infinitely appending the elements of <code>nums</code> to itself.</p> <p>Return <em>the length of the <strong>shortest</strong> subarray of the array </em><code>infinite_nums</code><em> with a sum equal to </em><code>target</code><em>.</em> If there is no such subarray return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,2,3], target = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8], target = 3 <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum; Sliding Window
Java
class Solution { public int minSizeSubarray(int[] nums, int target) { long s = Arrays.stream(nums).sum(); int n = nums.length; int a = 0; if (target > s) { a = n * (target / (int) s); target -= target / s * s; } if (target == s) { return n; } Map<Long, Integer> pos = new HashMap<>(); pos.put(0L, -1); long pre = 0; int b = 1 << 30; for (int i = 0; i < n; ++i) { pre += nums[i]; if (pos.containsKey(pre - target)) { b = Math.min(b, i - pos.get(pre - target)); } if (pos.containsKey(pre - (s - target))) { b = Math.min(b, n - (i - pos.get(pre - (s - target)))); } pos.put(pre, i); } return b == 1 << 30 ? -1 : a + b; } }
2,875
Minimum Size Subarray in Infinite Array
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and an integer <code>target</code>.</p> <p>A <strong>0-indexed</strong> array <code>infinite_nums</code> is generated by infinitely appending the elements of <code>nums</code> to itself.</p> <p>Return <em>the length of the <strong>shortest</strong> subarray of the array </em><code>infinite_nums</code><em> with a sum equal to </em><code>target</code><em>.</em> If there is no such subarray return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,2,3], target = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8], target = 3 <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum; Sliding Window
Python
class Solution: def minSizeSubarray(self, nums: List[int], target: int) -> int: s = sum(nums) n = len(nums) a = 0 if target > s: a = n * (target // s) target -= target // s * s if target == s: return n pos = {0: -1} pre = 0 b = inf for i, x in enumerate(nums): pre += x if (t := pre - target) in pos: b = min(b, i - pos[t]) if (t := pre - (s - target)) in pos: b = min(b, n - (i - pos[t])) pos[pre] = i return -1 if b == inf else a + b
2,875
Minimum Size Subarray in Infinite Array
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> and an integer <code>target</code>.</p> <p>A <strong>0-indexed</strong> array <code>infinite_nums</code> is generated by infinitely appending the elements of <code>nums</code> to itself.</p> <p>Return <em>the length of the <strong>shortest</strong> subarray of the array </em><code>infinite_nums</code><em> with a sum equal to </em><code>target</code><em>.</em> If there is no such subarray return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], target = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,2,3,1,2,3,1,2,...]. The subarray in the range [1,2], has the sum equal to target = 5 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,2,3], target = 4 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...]. The subarray in the range [4,5], has the sum equal to target = 4 and length = 2. It can be proven that 2 is the shortest length of a subarray with sum equal to target = 4. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8], target = 3 <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example infinite_nums = [2,4,6,8,2,4,6,8,...]. It can be proven that there is no subarray with sum equal to target = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Prefix Sum; Sliding Window
TypeScript
function minSizeSubarray(nums: number[], target: number): number { const s = nums.reduce((a, b) => a + b); const n = nums.length; let a = 0; if (target > s) { a = n * ((target / s) | 0); target -= ((target / s) | 0) * s; } if (target === s) { return n; } const pos: Map<number, number> = new Map(); let pre = 0; pos.set(0, -1); let b = Infinity; for (let i = 0; i < n; ++i) { pre += nums[i]; if (pos.has(pre - target)) { b = Math.min(b, i - pos.get(pre - target)!); } if (pos.has(pre - (s - target))) { b = Math.min(b, n - (i - pos.get(pre - (s - target))!)); } pos.set(pre, i); } return b === Infinity ? -1 : a + b; }
2,876
Count Visited Nodes in a Directed Graph
Hard
<p>There is a <strong>directed</strong> graph consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and <code>n</code> directed edges.</p> <p>You are given a <strong>0-indexed</strong> array <code>edges</code> where <code>edges[i]</code> indicates that there is an edge from node <code>i</code> to node <code>edges[i]</code>.</p> <p>Consider the following process on the graph:</p> <ul> <li>You start from a node <code>x</code> and keep visiting other nodes through edges until you reach a node that you have already visited before on this <strong>same</strong> process.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the number of <strong>different</strong> nodes that you will visit if you perform the process starting from node </em><code>i</code>.</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/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaphdrawio-1.png" /> <pre> <strong>Input:</strong> edges = [1,2,0,0] <strong>Output:</strong> [3,3,3,4] <strong>Explanation:</strong> We perform the process starting from each node in the following way: - Starting from node 0, we visit the nodes 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 3. - Starting from node 1, we visit the nodes 1 -&gt; 2 -&gt; 0 -&gt; 1. The number of different nodes we visit is 3. - Starting from node 2, we visit the nodes 2 -&gt; 0 -&gt; 1 -&gt; 2. The number of different nodes we visit is 3. - Starting from node 3, we visit the nodes 3 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaph2drawio.png" style="width: 191px; height: 251px;" /> <pre> <strong>Input:</strong> edges = [1,2,3,4,0] <strong>Output:</strong> [5,5,5,5,5] <strong>Explanation:</strong> Starting from any node we can visit every node in the graph in the process. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == edges.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges[i] &lt;= n - 1</code></li> <li><code>edges[i] != i</code></li> </ul>
Graph; Memoization; Dynamic Programming
C++
class Solution { public: vector<int> countVisitedNodes(vector<int>& edges) { int n = edges.size(); vector<int> ans(n), vis(n); for (int i = 0; i < n; ++i) { if (!ans[i]) { int cnt = 0, j = i; while (vis[j] == 0) { vis[j] = ++cnt; j = edges[j]; } int cycle = 0, total = cnt + ans[j]; if (ans[j] == 0) { cycle = cnt - vis[j] + 1; } j = i; while (ans[j] == 0) { ans[j] = max(total--, cycle); j = edges[j]; } } } return ans; } };
2,876
Count Visited Nodes in a Directed Graph
Hard
<p>There is a <strong>directed</strong> graph consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and <code>n</code> directed edges.</p> <p>You are given a <strong>0-indexed</strong> array <code>edges</code> where <code>edges[i]</code> indicates that there is an edge from node <code>i</code> to node <code>edges[i]</code>.</p> <p>Consider the following process on the graph:</p> <ul> <li>You start from a node <code>x</code> and keep visiting other nodes through edges until you reach a node that you have already visited before on this <strong>same</strong> process.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the number of <strong>different</strong> nodes that you will visit if you perform the process starting from node </em><code>i</code>.</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/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaphdrawio-1.png" /> <pre> <strong>Input:</strong> edges = [1,2,0,0] <strong>Output:</strong> [3,3,3,4] <strong>Explanation:</strong> We perform the process starting from each node in the following way: - Starting from node 0, we visit the nodes 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 3. - Starting from node 1, we visit the nodes 1 -&gt; 2 -&gt; 0 -&gt; 1. The number of different nodes we visit is 3. - Starting from node 2, we visit the nodes 2 -&gt; 0 -&gt; 1 -&gt; 2. The number of different nodes we visit is 3. - Starting from node 3, we visit the nodes 3 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaph2drawio.png" style="width: 191px; height: 251px;" /> <pre> <strong>Input:</strong> edges = [1,2,3,4,0] <strong>Output:</strong> [5,5,5,5,5] <strong>Explanation:</strong> Starting from any node we can visit every node in the graph in the process. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == edges.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges[i] &lt;= n - 1</code></li> <li><code>edges[i] != i</code></li> </ul>
Graph; Memoization; Dynamic Programming
Go
func countVisitedNodes(edges []int) []int { n := len(edges) ans := make([]int, n) vis := make([]int, n) for i := range ans { if ans[i] == 0 { cnt, j := 0, i for vis[j] == 0 { cnt++ vis[j] = cnt j = edges[j] } cycle, total := 0, cnt+ans[j] if ans[j] == 0 { cycle = cnt - vis[j] + 1 } j = i for ans[j] == 0 { ans[j] = max(total, cycle) total-- j = edges[j] } } } return ans }
2,876
Count Visited Nodes in a Directed Graph
Hard
<p>There is a <strong>directed</strong> graph consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and <code>n</code> directed edges.</p> <p>You are given a <strong>0-indexed</strong> array <code>edges</code> where <code>edges[i]</code> indicates that there is an edge from node <code>i</code> to node <code>edges[i]</code>.</p> <p>Consider the following process on the graph:</p> <ul> <li>You start from a node <code>x</code> and keep visiting other nodes through edges until you reach a node that you have already visited before on this <strong>same</strong> process.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the number of <strong>different</strong> nodes that you will visit if you perform the process starting from node </em><code>i</code>.</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/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaphdrawio-1.png" /> <pre> <strong>Input:</strong> edges = [1,2,0,0] <strong>Output:</strong> [3,3,3,4] <strong>Explanation:</strong> We perform the process starting from each node in the following way: - Starting from node 0, we visit the nodes 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 3. - Starting from node 1, we visit the nodes 1 -&gt; 2 -&gt; 0 -&gt; 1. The number of different nodes we visit is 3. - Starting from node 2, we visit the nodes 2 -&gt; 0 -&gt; 1 -&gt; 2. The number of different nodes we visit is 3. - Starting from node 3, we visit the nodes 3 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaph2drawio.png" style="width: 191px; height: 251px;" /> <pre> <strong>Input:</strong> edges = [1,2,3,4,0] <strong>Output:</strong> [5,5,5,5,5] <strong>Explanation:</strong> Starting from any node we can visit every node in the graph in the process. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == edges.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges[i] &lt;= n - 1</code></li> <li><code>edges[i] != i</code></li> </ul>
Graph; Memoization; Dynamic Programming
Java
class Solution { public int[] countVisitedNodes(List<Integer> edges) { int n = edges.size(); int[] ans = new int[n]; int[] vis = new int[n]; for (int i = 0; i < n; ++i) { if (ans[i] == 0) { int cnt = 0, j = i; while (vis[j] == 0) { vis[j] = ++cnt; j = edges.get(j); } int cycle = 0, total = cnt + ans[j]; if (ans[j] == 0) { cycle = cnt - vis[j] + 1; } j = i; while (ans[j] == 0) { ans[j] = Math.max(total--, cycle); j = edges.get(j); } } } return ans; } }
2,876
Count Visited Nodes in a Directed Graph
Hard
<p>There is a <strong>directed</strong> graph consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and <code>n</code> directed edges.</p> <p>You are given a <strong>0-indexed</strong> array <code>edges</code> where <code>edges[i]</code> indicates that there is an edge from node <code>i</code> to node <code>edges[i]</code>.</p> <p>Consider the following process on the graph:</p> <ul> <li>You start from a node <code>x</code> and keep visiting other nodes through edges until you reach a node that you have already visited before on this <strong>same</strong> process.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the number of <strong>different</strong> nodes that you will visit if you perform the process starting from node </em><code>i</code>.</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/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaphdrawio-1.png" /> <pre> <strong>Input:</strong> edges = [1,2,0,0] <strong>Output:</strong> [3,3,3,4] <strong>Explanation:</strong> We perform the process starting from each node in the following way: - Starting from node 0, we visit the nodes 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 3. - Starting from node 1, we visit the nodes 1 -&gt; 2 -&gt; 0 -&gt; 1. The number of different nodes we visit is 3. - Starting from node 2, we visit the nodes 2 -&gt; 0 -&gt; 1 -&gt; 2. The number of different nodes we visit is 3. - Starting from node 3, we visit the nodes 3 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaph2drawio.png" style="width: 191px; height: 251px;" /> <pre> <strong>Input:</strong> edges = [1,2,3,4,0] <strong>Output:</strong> [5,5,5,5,5] <strong>Explanation:</strong> Starting from any node we can visit every node in the graph in the process. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == edges.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges[i] &lt;= n - 1</code></li> <li><code>edges[i] != i</code></li> </ul>
Graph; Memoization; Dynamic Programming
Python
class Solution: def countVisitedNodes(self, edges: List[int]) -> List[int]: n = len(edges) ans = [0] * n vis = [0] * n for i in range(n): if not ans[i]: cnt, j = 0, i while not vis[j]: cnt += 1 vis[j] = cnt j = edges[j] cycle, total = 0, cnt + ans[j] if not ans[j]: cycle = cnt - vis[j] + 1 total = cnt j = i while not ans[j]: ans[j] = max(total, cycle) total -= 1 j = edges[j] return ans
2,876
Count Visited Nodes in a Directed Graph
Hard
<p>There is a <strong>directed</strong> graph consisting of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code> and <code>n</code> directed edges.</p> <p>You are given a <strong>0-indexed</strong> array <code>edges</code> where <code>edges[i]</code> indicates that there is an edge from node <code>i</code> to node <code>edges[i]</code>.</p> <p>Consider the following process on the graph:</p> <ul> <li>You start from a node <code>x</code> and keep visiting other nodes through edges until you reach a node that you have already visited before on this <strong>same</strong> process.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the number of <strong>different</strong> nodes that you will visit if you perform the process starting from node </em><code>i</code>.</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/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaphdrawio-1.png" /> <pre> <strong>Input:</strong> edges = [1,2,0,0] <strong>Output:</strong> [3,3,3,4] <strong>Explanation:</strong> We perform the process starting from each node in the following way: - Starting from node 0, we visit the nodes 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 3. - Starting from node 1, we visit the nodes 1 -&gt; 2 -&gt; 0 -&gt; 1. The number of different nodes we visit is 3. - Starting from node 2, we visit the nodes 2 -&gt; 0 -&gt; 1 -&gt; 2. The number of different nodes we visit is 3. - Starting from node 3, we visit the nodes 3 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 0. The number of different nodes we visit is 4. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2876.Count%20Visited%20Nodes%20in%20a%20Directed%20Graph/images/graaph2drawio.png" style="width: 191px; height: 251px;" /> <pre> <strong>Input:</strong> edges = [1,2,3,4,0] <strong>Output:</strong> [5,5,5,5,5] <strong>Explanation:</strong> Starting from any node we can visit every node in the graph in the process. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == edges.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges[i] &lt;= n - 1</code></li> <li><code>edges[i] != i</code></li> </ul>
Graph; Memoization; Dynamic Programming
TypeScript
function countVisitedNodes(edges: number[]): number[] { const n = edges.length; const ans: number[] = Array(n).fill(0); const vis: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { if (ans[i] === 0) { let [cnt, j] = [0, i]; while (vis[j] === 0) { vis[j] = ++cnt; j = edges[j]; } let [cycle, total] = [0, cnt + ans[j]]; if (ans[j] === 0) { cycle = cnt - vis[j] + 1; } j = i; while (ans[j] === 0) { ans[j] = Math.max(total--, cycle); j = edges[j]; } } } return ans; }
2,877
Create a DataFrame from List
Easy
<p>Write a solution to <strong>create</strong> a DataFrame from a 2D list called <code>student_data</code>. This 2D list contains the IDs and ages of some students.</p> <p>The DataFrame should have two columns, <code>student_id</code> and <code>age</code>, and be in the same order as the original 2D list.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>student_data:<strong> </strong><code>[ [1, 15], [2, 11], [3, 11], [4, 20] ]</code> <strong>Output:</strong> +------------+-----+ | student_id | age | +------------+-----+ | 1 | 15 | | 2 | 11 | | 3 | 11 | | 4 | 20 | +------------+-----+ <strong>Explanation:</strong> A DataFrame was created on top of student_data, with two columns named <code>student_id</code> and <code>age</code>. </pre>
Pandas
Python
import pandas as pd def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: return pd.DataFrame(student_data, columns=['student_id', 'age'])
2,878
Get the Size of a DataFrame
Easy
<pre> DataFrame <code>players:</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | player_id | int | | name | object | | age | int | | position | object | | ... | ... | +-------------+--------+ </pre> <p>Write a solution to calculate and display the <strong>number of rows and columns</strong> of <code>players</code>.</p> <p>Return the result as an array:</p> <p><code>[number of rows, number of columns]</code></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>+-----------+----------+-----+-------------+--------------------+ | player_id | name | age | position | team | +-----------+----------+-----+-------------+--------------------+ | 846 | Mason | 21 | Forward | RealMadrid | | 749 | Riley | 30 | Winger | Barcelona | | 155 | Bob | 28 | Striker | ManchesterUnited | | 583 | Isabella | 32 | Goalkeeper | Liverpool | | 388 | Zachary | 24 | Midfielder | BayernMunich | | 883 | Ava | 23 | Defender | Chelsea | | 355 | Violet | 18 | Striker | Juventus | | 247 | Thomas | 27 | Striker | ParisSaint-Germain | | 761 | Jack | 33 | Midfielder | ManchesterCity | | 642 | Charlie | 36 | Center-back | Arsenal | +-----------+----------+-----+-------------+--------------------+<strong> Output: </strong>[10, 5] <strong>Explanation:</strong> This DataFrame contains 10 rows and 5 columns. </pre>
Pandas
Python
import pandas as pd def getDataframeSize(players: pd.DataFrame) -> List[int]: return list(players.shape)
2,879
Display the First Three Rows
Easy
<pre> DataFrame: <code>employees</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | employee_id | int | | name | object | | department | object | | salary | int | +-------------+--------+ </pre> <p>Write a solution to display the <strong>first <code>3</code> </strong>rows<strong> </strong>of this DataFrame.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>DataFrame employees +-------------+-----------+-----------------------+--------+ | employee_id | name | department | salary | +-------------+-----------+-----------------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | | 60 | Annabelle | InformationTechnology | 37678 | | 49 | Jonathan | HumanResources | 23793 | | 43 | Khaled | Administration | 40454 | +-------------+-----------+-----------------------+--------+ <strong>Output:</strong> +-------------+---------+-------------+--------+ | employee_id | name | department | salary | +-------------+---------+-------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | +-------------+---------+-------------+--------+ <strong>Explanation:</strong> Only the first 3 rows are displayed.</pre>
Pandas
Python
import pandas as pd def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: return employees.head(3)
2,880
Select Data
Easy
<pre> DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ </pre> <p>Write a solution to select the name and age of the student with <code>student_id = 101</code>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong>Example 1: Input:</strong> +------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 101 | Ulysses | 13 | | 53 | William | 10 | | 128 | Henry | 6 | | 3 | Henry | 11 | +------------+---------+-----+ <strong>Output:</strong> +---------+-----+ | name | age | +---------+-----+ | Ulysses | 13 | +---------+-----+ <strong>Explanation: </strong>Student Ulysses has student_id = 101, we select the name and age.</pre>
Pandas
Python
import pandas as pd def selectData(students: pd.DataFrame) -> pd.DataFrame: return students[students['student_id'] == 101][['name', 'age']]
2,881
Create a New Column
Easy
<pre> DataFrame <code>employees</code> +-------------+--------+ | Column Name | Type. | +-------------+--------+ | name | object | | salary | int. | +-------------+--------+ </pre> <p>A&nbsp;company plans to provide its employees with a bonus.</p> <p>Write a solution to create a new column name <code>bonus</code> that contains the <strong>doubled values</strong> of the <code>salary</code> column.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> DataFrame employees +---------+--------+ | name | salary | +---------+--------+ | Piper | 4548 | | Grace | 28150 | | Georgia | 1103 | | Willow | 6593 | | Finn | 74576 | | Thomas | 24433 | +---------+--------+ <strong>Output:</strong> +---------+--------+--------+ | name | salary | bonus | +---------+--------+--------+ | Piper | 4548 | 9096 | | Grace | 28150 | 56300 | | Georgia | 1103 | 2206 | | Willow | 6593 | 13186 | | Finn | 74576 | 149152 | | Thomas | 24433 | 48866 | +---------+--------+--------+ <strong>Explanation:</strong> A new column bonus is created by doubling the value in the column salary.</pre>
Pandas
Python
import pandas as pd def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: employees['bonus'] = employees['salary'] * 2 return employees
2,882
Drop Duplicate Rows
Easy
<pre> DataFrame customers +-------------+--------+ | Column Name | Type | +-------------+--------+ | customer_id | int | | name | object | | email | object | +-------------+--------+ </pre> <p>There are some duplicate rows in the DataFrame based on the <code>email</code> column.</p> <p>Write a solution to remove these duplicate rows and keep only the <strong>first</strong> occurrence.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong class="example">Example 1:</strong> <strong>Input:</strong> +-------------+---------+---------------------+ | customer_id | name | email | +-------------+---------+---------------------+ | 1 | Ella | emily@example.com | | 2 | David | michael@example.com | | 3 | Zachary | sarah@example.com | | 4 | Alice | john@example.com | | 5 | Finn | john@example.com | | 6 | Violet | alice@example.com | +-------------+---------+---------------------+ <strong>Output: </strong> +-------------+---------+---------------------+ | customer_id | name | email | +-------------+---------+---------------------+ | 1 | Ella | emily@example.com | | 2 | David | michael@example.com | | 3 | Zachary | sarah@example.com | | 4 | Alice | john@example.com | | 6 | Violet | alice@example.com | +-------------+---------+---------------------+ <strong>Explanation:</strong> Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained. </pre>
Pandas
Python
import pandas as pd def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: return customers.drop_duplicates(subset=['email'])
2,883
Drop Missing Data
Easy
<pre> DataFrame students +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ </pre> <p>There are some rows having missing values in the <code>name</code> column.</p> <p>Write a solution to remove the rows with missing values.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>+------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 32 | Piper | 5 | | 217 | None | 19 | | 779 | Georgia | 20 | | 849 | Willow | 14 | +------------+---------+-----+ <strong>Output: </strong>+------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 32 | Piper | 5 | | 779 | Georgia | 20 | | 849 | Willow | 14 | +------------+---------+-----+ <strong>Explanation:</strong> Student with id 217 havs empty value in the name column, so it will be removed.</pre>
Pandas
Python
import pandas as pd def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: return students[students['name'].notnull()]
2,884
Modify Columns
Easy
<pre> DataFrame <code>employees</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | salary | int | +-------------+--------+ </pre> <p>A company intends to give its employees a pay rise.</p> <p>Write a solution to <strong>modify</strong> the <code>salary</code> column by multiplying each salary by 2.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>DataFrame employees +---------+--------+ | name | salary | +---------+--------+ | Jack | 19666 | | Piper | 74754 | | Mia | 62509 | | Ulysses | 54866 | +---------+--------+ <strong>Output: </strong>+---------+--------+ | name | salary | +---------+--------+ | Jack | 39332 | | Piper | 149508 | | Mia | 125018 | | Ulysses | 109732 | +---------+--------+ <strong>Explanation: </strong>Every salary has been doubled.</pre>
Pandas
Python
import pandas as pd def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: employees['salary'] *= 2 return employees
2,885
Rename Columns
Easy
<pre> DataFrame <code>students</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | id | int | | first | object | | last | object | | age | int | +-------------+--------+ </pre> <p>Write a solution to rename the columns as follows:</p> <ul> <li><code>id</code> to <code>student_id</code></li> <li><code>first</code> to <code>first_name</code></li> <li><code>last</code> to <code>last_name</code></li> <li><code>age</code> to <code>age_in_years</code></li> </ul> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong class="example">Example 1:</strong> <strong>Input: </strong>+----+---------+----------+-----+ | id | first | last | age | +----+---------+----------+-----+ | 1 | Mason | King | 6 | | 2 | Ava | Wright | 7 | | 3 | Taylor | Hall | 16 | | 4 | Georgia | Thompson | 18 | | 5 | Thomas | Moore | 10 | +----+---------+----------+-----+ <strong>Output:</strong> +------------+------------+-----------+--------------+ | student_id | first_name | last_name | age_in_years | +------------+------------+-----------+--------------+ | 1 | Mason | King | 6 | | 2 | Ava | Wright | 7 | | 3 | Taylor | Hall | 16 | | 4 | Georgia | Thompson | 18 | | 5 | Thomas | Moore | 10 | +------------+------------+-----------+--------------+ <strong>Explanation:</strong> The column names are changed accordingly.</pre>
Pandas
Python
import pandas as pd def renameColumns(students: pd.DataFrame) -> pd.DataFrame: students.rename( columns={ 'id': 'student_id', 'first': 'first_name', 'last': 'last_name', 'age': 'age_in_years', }, inplace=True, ) return students
2,886
Change Data Type
Easy
<pre> DataFrame <code>students</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | | grade | float | +-------------+--------+ </pre> <p>Write a solution to correct the errors:</p> <p>The <code>grade</code> column is stored as floats,&nbsp;convert it to integers.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong class="example">Example 1:</strong> <strong>Input: </strong>DataFrame students: +------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73.0 | | 2 | Kate | 15 | 87.0 | +------------+------+-----+-------+ <strong>Output: </strong>+------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73 | | 2 | Kate | 15 | 87 | +------------+------+-----+-------+ <strong>Explanation:</strong> The data types of the column grade is converted to int.</pre>
Pandas
Python
import pandas as pd def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: students['grade'] = students['grade'].astype(int) return students
2,887
Fill Missing Data
Easy
<pre> DataFrame <code>products</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | quantity | int | | price | int | +-------------+--------+ </pre> <p>Write a solution to fill in the missing value as <code><strong>0</strong></code> in the <code>quantity</code> column.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong class="example">Example 1:</strong> <strong>Input:</strong>+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | None | 135 | | WirelessEarbuds | None | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+ <strong>Output: </strong>+-----------------+----------+-------+ | name | quantity | price | +-----------------+----------+-------+ | Wristwatch | 0 | 135 | | WirelessEarbuds | 0 | 821 | | GolfClubs | 779 | 9319 | | Printer | 849 | 3051 | +-----------------+----------+-------+ <strong>Explanation:</strong> The quantity for Wristwatch and WirelessEarbuds are filled by 0.</pre>
Pandas
Python
import pandas as pd def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: products['quantity'] = products['quantity'].fillna(0) return products
2,888
Reshape Data Concatenate
Easy
<pre> DataFrame <code>df1</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ DataFrame <code>df2</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ </pre> <p>Write a solution to concatenate these two DataFrames <strong>vertically</strong> into one DataFrame.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: df1</strong> +------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 1 | Mason | 8 | | 2 | Ava | 6 | | 3 | Taylor | 15 | | 4 | Georgia | 17 | +------------+---------+-----+ <strong>df2 </strong>+------------+------+-----+ | student_id | name | age | +------------+------+-----+ | 5 | Leo | 7 | | 6 | Alex | 7 | +------------+------+-----+ <strong>Output:</strong> +------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 1 | Mason | 8 | | 2 | Ava | 6 | | 3 | Taylor | 15 | | 4 | Georgia | 17 | | 5 | Leo | 7 | | 6 | Alex | 7 | +------------+---------+-----+ <strong>Explanation: </strong>The two DataFramess are stacked vertically, and their rows are combined.</pre>
Pandas
Python
import pandas as pd def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: return pd.concat([df1, df2], ignore_index=True)
2,889
Reshape Data Pivot
Easy
<pre> DataFrame <code>weather</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | city | object | | month | object | | temperature | int | +-------------+--------+ </pre> <p>Write a solution to <strong>pivot</strong> the data so that each row represents temperatures for a specific month, and each city is a separate column.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <pre> <strong class="example">Example 1:</strong> <strong>Input:</strong> +--------------+----------+-------------+ | city | month | temperature | +--------------+----------+-------------+ | Jacksonville | January | 13 | | Jacksonville | February | 23 | | Jacksonville | March | 38 | | Jacksonville | April | 5 | | Jacksonville | May | 34 | | ElPaso | January | 20 | | ElPaso | February | 6 | | ElPaso | March | 26 | | ElPaso | April | 2 | | ElPaso | May | 43 | +--------------+----------+-------------+ <strong>Output:</strong><code> +----------+--------+--------------+ | month | ElPaso | Jacksonville | +----------+--------+--------------+ | April | 2 | 5 | | February | 6 | 23 | | January | 20 | 13 | | March | 26 | 38 | | May | 43 | 34 | +----------+--------+--------------+</code> <strong>Explanation: </strong>The table is pivoted, each column represents a city, and each row represents a specific month.</pre>
Pandas
Python
import pandas as pd def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: return weather.pivot(index='month', columns='city', values='temperature')
2,890
Reshape Data Melt
Easy
<pre> DataFrame <code>report</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | product | object | | quarter_1 | int | | quarter_2 | int | | quarter_3 | int | | quarter_4 | int | +-------------+--------+ </pre> <p>Write a solution to <strong>reshape</strong> the data so that each row represents sales data for a product in a specific quarter.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>+-------------+-----------+-----------+-----------+-----------+ | product | quarter_1 | quarter_2 | quarter_3 | quarter_4 | +-------------+-----------+-----------+-----------+-----------+ | Umbrella | 417 | 224 | 379 | 611 | | SleepingBag | 800 | 936 | 93 | 875 | +-------------+-----------+-----------+-----------+-----------+ <strong>Output:</strong> +-------------+-----------+-------+ | product | quarter | sales | +-------------+-----------+-------+ | Umbrella | quarter_1 | 417 | | SleepingBag | quarter_1 | 800 | | Umbrella | quarter_2 | 224 | | SleepingBag | quarter_2 | 936 | | Umbrella | quarter_3 | 379 | | SleepingBag | quarter_3 | 93 | | Umbrella | quarter_4 | 611 | | SleepingBag | quarter_4 | 875 | +-------------+-----------+-------+ <strong>Explanation:</strong> The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter. </pre>
Pandas
Python
import pandas as pd def meltTable(report: pd.DataFrame) -> pd.DataFrame: return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales')
2,891
Method Chaining
Easy
<pre> DataFrame <code>animals</code> +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | species | object | | age | int | | weight | int | +-------------+--------+ </pre> <p>Write a solution to list the names of animals that weigh <strong>strictly more than</strong> <code>100</code> kilograms.</p> <p>Return the&nbsp;animals sorted by weight in <strong>descending order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> DataFrame animals: +----------+---------+-----+--------+ | name | species | age | weight | +----------+---------+-----+--------+ | Tatiana | Snake | 98 | 464 | | Khaled | Giraffe | 50 | 41 | | Alex | Leopard | 6 | 328 | | Jonathan | Monkey | 45 | 463 | | Stefan | Bear | 100 | 50 | | Tommy | Panda | 26 | 349 | +----------+---------+-----+--------+ <strong>Output:</strong> +----------+ | name | +----------+ | Tatiana | | Jonathan | | Tommy | | Alex | +----------+ <strong>Explanation:</strong> All animals weighing more than 100 should be included in the results table. Tatiana&#39;s weight is 464, Jonathan&#39;s weight is 463, Tommy&#39;s weight is 349, and Alex&#39;s weight is 328. The results should be sorted in descending order of weight.</pre> <p>&nbsp;</p> <p>In Pandas, <strong>method chaining</strong> enables us to&nbsp;perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables.&nbsp;</p> <p>Can you complete this&nbsp;task in just <strong>one line </strong>of code using method chaining?</p>
Pandas
Python
import pandas as pd def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: return animals[animals['weight'] > 100].sort_values('weight', ascending=False)[ ['name'] ]
2,892
Minimizing Array After Replacing Pairs With Their Product
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you can perform the following operation on the array any number of times:</p> <ul> <li>Select two <strong>adjacent</strong> elements of the array like <code>x</code> and <code>y</code>, such that <code>x * y &lt;= k</code>, and replace both of them with a <strong>single element</strong> with value <code>x * y</code> (e.g. in one operation the array <code>[1, 2, 2, 3]</code> with <code>k = 5</code> can become <code>[1, 4, 3]</code> or <code>[2, 2, 3]</code>, but can&#39;t become <code>[1, 2, 6]</code>).</li> </ul> <p>Return <em>the <strong>minimum</strong> possible length of </em><code>nums</code><em> after any number of operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,7,3,5], k = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform these operations: 1. [<u>2,3</u>,3,7,3,5] -&gt; [<u>6</u>,3,7,3,5] 2. [<u>6,3</u>,7,3,5] -&gt; [<u>18</u>,7,3,5] 3. [18,7,<u>3,5</u>] -&gt; [18,7,<u>15</u>] It can be shown that 3 is the minimum length possible to achieve with the given operation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], k = 6 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can&#39;t perform any operations since the product of every two adjacent elements is greater than 6. Hence, the answer is 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
C++
class Solution { public: int minArrayLength(vector<int>& nums, int k) { int ans = 1; long long y = nums[0]; for (int i = 1; i < nums.size(); ++i) { int x = nums[i]; if (x == 0) { return 1; } if (x * y <= k) { y *= x; } else { y = x; ++ans; } } return ans; } };
2,892
Minimizing Array After Replacing Pairs With Their Product
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you can perform the following operation on the array any number of times:</p> <ul> <li>Select two <strong>adjacent</strong> elements of the array like <code>x</code> and <code>y</code>, such that <code>x * y &lt;= k</code>, and replace both of them with a <strong>single element</strong> with value <code>x * y</code> (e.g. in one operation the array <code>[1, 2, 2, 3]</code> with <code>k = 5</code> can become <code>[1, 4, 3]</code> or <code>[2, 2, 3]</code>, but can&#39;t become <code>[1, 2, 6]</code>).</li> </ul> <p>Return <em>the <strong>minimum</strong> possible length of </em><code>nums</code><em> after any number of operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,7,3,5], k = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform these operations: 1. [<u>2,3</u>,3,7,3,5] -&gt; [<u>6</u>,3,7,3,5] 2. [<u>6,3</u>,7,3,5] -&gt; [<u>18</u>,7,3,5] 3. [18,7,<u>3,5</u>] -&gt; [18,7,<u>15</u>] It can be shown that 3 is the minimum length possible to achieve with the given operation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], k = 6 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can&#39;t perform any operations since the product of every two adjacent elements is greater than 6. Hence, the answer is 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Go
func minArrayLength(nums []int, k int) int { ans, y := 1, nums[0] for _, x := range nums[1:] { if x == 0 { return 1 } if x*y <= k { y *= x } else { y = x ans++ } } return ans }
2,892
Minimizing Array After Replacing Pairs With Their Product
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you can perform the following operation on the array any number of times:</p> <ul> <li>Select two <strong>adjacent</strong> elements of the array like <code>x</code> and <code>y</code>, such that <code>x * y &lt;= k</code>, and replace both of them with a <strong>single element</strong> with value <code>x * y</code> (e.g. in one operation the array <code>[1, 2, 2, 3]</code> with <code>k = 5</code> can become <code>[1, 4, 3]</code> or <code>[2, 2, 3]</code>, but can&#39;t become <code>[1, 2, 6]</code>).</li> </ul> <p>Return <em>the <strong>minimum</strong> possible length of </em><code>nums</code><em> after any number of operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,7,3,5], k = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform these operations: 1. [<u>2,3</u>,3,7,3,5] -&gt; [<u>6</u>,3,7,3,5] 2. [<u>6,3</u>,7,3,5] -&gt; [<u>18</u>,7,3,5] 3. [18,7,<u>3,5</u>] -&gt; [18,7,<u>15</u>] It can be shown that 3 is the minimum length possible to achieve with the given operation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], k = 6 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can&#39;t perform any operations since the product of every two adjacent elements is greater than 6. Hence, the answer is 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Java
class Solution { public int minArrayLength(int[] nums, int k) { int ans = 1; long y = nums[0]; for (int i = 1; i < nums.length; ++i) { int x = nums[i]; if (x == 0) { return 1; } if (x * y <= k) { y *= x; } else { y = x; ++ans; } } return ans; } }
2,892
Minimizing Array After Replacing Pairs With Their Product
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you can perform the following operation on the array any number of times:</p> <ul> <li>Select two <strong>adjacent</strong> elements of the array like <code>x</code> and <code>y</code>, such that <code>x * y &lt;= k</code>, and replace both of them with a <strong>single element</strong> with value <code>x * y</code> (e.g. in one operation the array <code>[1, 2, 2, 3]</code> with <code>k = 5</code> can become <code>[1, 4, 3]</code> or <code>[2, 2, 3]</code>, but can&#39;t become <code>[1, 2, 6]</code>).</li> </ul> <p>Return <em>the <strong>minimum</strong> possible length of </em><code>nums</code><em> after any number of operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,7,3,5], k = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform these operations: 1. [<u>2,3</u>,3,7,3,5] -&gt; [<u>6</u>,3,7,3,5] 2. [<u>6,3</u>,7,3,5] -&gt; [<u>18</u>,7,3,5] 3. [18,7,<u>3,5</u>] -&gt; [18,7,<u>15</u>] It can be shown that 3 is the minimum length possible to achieve with the given operation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], k = 6 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can&#39;t perform any operations since the product of every two adjacent elements is greater than 6. Hence, the answer is 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
Python
class Solution: def minArrayLength(self, nums: List[int], k: int) -> int: ans, y = 1, nums[0] for x in nums[1:]: if x == 0: return 1 if x * y <= k: y *= x else: y = x ans += 1 return ans
2,892
Minimizing Array After Replacing Pairs With Their Product
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you can perform the following operation on the array any number of times:</p> <ul> <li>Select two <strong>adjacent</strong> elements of the array like <code>x</code> and <code>y</code>, such that <code>x * y &lt;= k</code>, and replace both of them with a <strong>single element</strong> with value <code>x * y</code> (e.g. in one operation the array <code>[1, 2, 2, 3]</code> with <code>k = 5</code> can become <code>[1, 4, 3]</code> or <code>[2, 2, 3]</code>, but can&#39;t become <code>[1, 2, 6]</code>).</li> </ul> <p>Return <em>the <strong>minimum</strong> possible length of </em><code>nums</code><em> after any number of operations</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,7,3,5], k = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform these operations: 1. [<u>2,3</u>,3,7,3,5] -&gt; [<u>6</u>,3,7,3,5] 2. [<u>6,3</u>,7,3,5] -&gt; [<u>18</u>,7,3,5] 3. [18,7,<u>3,5</u>] -&gt; [18,7,<u>15</u>] It can be shown that 3 is the minimum length possible to achieve with the given operation. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3], k = 6 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can&#39;t perform any operations since the product of every two adjacent elements is greater than 6. Hence, the answer is 4.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Dynamic Programming
TypeScript
function minArrayLength(nums: number[], k: number): number { let [ans, y] = [1, nums[0]]; for (const x of nums.slice(1)) { if (x === 0) { return 1; } if (x * y <= k) { y *= x; } else { y = x; ++ans; } } return ans; }
2,893
Calculate Orders Within Each Interval
Medium
<p>Table: <code><font face="monospace">Orders</font></code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | minute | int | | order_count | int | +-------------+------+ minute is the primary key for this table. Each row of this table contains the minute and number of orders received during that specific minute. The total number of rows will be a multiple of 6. </pre> <p>Write a query to calculate <strong>total</strong> <strong>orders</strong><b> </b>within each <strong>interval</strong>. Each interval is defined as a combination of <code>6</code> minutes.</p> <ul> <li>Minutes <code>1</code> to <code>6</code> fall within interval <code>1</code>, while minutes <code>7</code> to <code>12</code> belong to interval <code>2</code>, and so forth.</li> </ul> <p>Return<em> the result table ordered by <strong>interval_no</strong> in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Orders table: +--------+-------------+ | minute | order_count | +--------+-------------+ | 1 | 0 | | 2 | 2 | | 3 | 4 | | 4 | 6 | | 5 | 1 | | 6 | 4 | | 7 | 1 | | 8 | 2 | | 9 | 4 | | 10 | 1 | | 11 | 4 | | 12 | 6 | +--------+-------------+ <strong>Output:</strong> +-------------+--------------+ | interval_no | total_orders | +-------------+--------------+ | 1 | 17 | | 2 | 18 | +-------------+--------------+ <strong>Explanation:</strong> - Interval number 1 comprises minutes from 1 to 6. The total orders in these six minutes are (0 + 2 + 4 + 6 + 1 + 4) = 17. - Interval number 2 comprises minutes from 7 to 12. The total orders in these six minutes are (1 + 2 + 4 + 1 + 4 + 6) = 18. Returning table orderd by interval_no in ascending order.</pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT minute, SUM(order_count) OVER ( ORDER BY minute ROWS 5 PRECEDING ) AS total_orders FROM Orders ) SELECT minute / 6 AS interval_no, total_orders FROM T WHERE minute % 6 = 0;
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
C++
class Solution { public: int differenceOfSums(int n, int m) { int ans = 0; for (int i = 1; i <= n; ++i) { ans += i % m ? i : -i; } return ans; } };
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
Go
func differenceOfSums(n int, m int) (ans int) { for i := 1; i <= n; i++ { if i%m == 0 { ans -= i } else { ans += i } } return }
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
Java
class Solution { public int differenceOfSums(int n, int m) { int ans = 0; for (int i = 1; i <= n; ++i) { ans += i % m == 0 ? -i : i; } return ans; } }
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
Python
class Solution: def differenceOfSums(self, n: int, m: int) -> int: return sum(i if i % m else -i for i in range(1, n + 1))
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
Rust
impl Solution { pub fn difference_of_sums(n: i32, m: i32) -> i32 { let mut ans = 0; for i in 1..=n { if i % m != 0 { ans += i; } else { ans -= i; } } ans } }
2,894
Divisible and Non-divisible Sums Difference
Easy
<p>You are given positive integers <code>n</code> and <code>m</code>.</p> <p>Define two integers as follows:</p> <ul> <li><code>num1</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>not divisible</strong> by <code>m</code>.</li> <li><code>num2</code>: The sum of all integers in the range <code>[1, n]</code> (both <strong>inclusive</strong>) that are <strong>divisible</strong> by <code>m</code>.</li> </ul> <p>Return <em>the integer</em> <code>num1 - num2</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, m = 3 <strong>Output:</strong> 19 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. - Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. We return 37 - 18 = 19 as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. - Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. We return 15 - 0 = 15 as the answer. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 5, m = 1 <strong>Output:</strong> -15 <strong>Explanation:</strong> In the given example: - Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0. - Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15. We return 0 - 15 = -15 as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, m &lt;= 1000</code></li> </ul>
Math
TypeScript
function differenceOfSums(n: number, m: number): number { let ans = 0; for (let i = 1; i <= n; ++i) { ans += i % m ? i : -i; } return ans; }
2,895
Minimum Processing Time
Medium
<p>You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.</p> <p>You are given an array <code>processorTime</code> representing the time each processor becomes available and an array <code>tasks</code> representing how long each task takes to complete. Return the&nbsp;<em>minimum</em> time needed to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at <code>time = 8</code>, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at <code>time = 10</code>.&nbsp;</p> <p>The time taken by the first processor to finish the execution of all tasks is&nbsp;<code>max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is&nbsp;<code>max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.</p> <p>The time taken by the first processor to finish the execution of all tasks is <code>max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is <code>max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == processorTime.length &lt;= 25000</code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= processorTime[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li> <li><code>tasks.length == 4 * n</code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int minProcessingTime(vector<int>& processorTime, vector<int>& tasks) { sort(processorTime.begin(), processorTime.end()); sort(tasks.begin(), tasks.end()); int ans = 0, i = tasks.size() - 1; for (int t : processorTime) { ans = max(ans, t + tasks[i]); i -= 4; } return ans; } };
2,895
Minimum Processing Time
Medium
<p>You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.</p> <p>You are given an array <code>processorTime</code> representing the time each processor becomes available and an array <code>tasks</code> representing how long each task takes to complete. Return the&nbsp;<em>minimum</em> time needed to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at <code>time = 8</code>, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at <code>time = 10</code>.&nbsp;</p> <p>The time taken by the first processor to finish the execution of all tasks is&nbsp;<code>max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is&nbsp;<code>max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.</p> <p>The time taken by the first processor to finish the execution of all tasks is <code>max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is <code>max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == processorTime.length &lt;= 25000</code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= processorTime[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li> <li><code>tasks.length == 4 * n</code></li> </ul>
Greedy; Array; Sorting
Go
func minProcessingTime(processorTime []int, tasks []int) (ans int) { sort.Ints(processorTime) sort.Ints(tasks) i := len(tasks) - 1 for _, t := range processorTime { ans = max(ans, t+tasks[i]) i -= 4 } return }
2,895
Minimum Processing Time
Medium
<p>You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.</p> <p>You are given an array <code>processorTime</code> representing the time each processor becomes available and an array <code>tasks</code> representing how long each task takes to complete. Return the&nbsp;<em>minimum</em> time needed to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at <code>time = 8</code>, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at <code>time = 10</code>.&nbsp;</p> <p>The time taken by the first processor to finish the execution of all tasks is&nbsp;<code>max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is&nbsp;<code>max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.</p> <p>The time taken by the first processor to finish the execution of all tasks is <code>max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is <code>max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == processorTime.length &lt;= 25000</code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= processorTime[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li> <li><code>tasks.length == 4 * n</code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int minProcessingTime(List<Integer> processorTime, List<Integer> tasks) { processorTime.sort((a, b) -> a - b); tasks.sort((a, b) -> a - b); int ans = 0, i = tasks.size() - 1; for (int t : processorTime) { ans = Math.max(ans, t + tasks.get(i)); i -= 4; } return ans; } }
2,895
Minimum Processing Time
Medium
<p>You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.</p> <p>You are given an array <code>processorTime</code> representing the time each processor becomes available and an array <code>tasks</code> representing how long each task takes to complete. Return the&nbsp;<em>minimum</em> time needed to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at <code>time = 8</code>, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at <code>time = 10</code>.&nbsp;</p> <p>The time taken by the first processor to finish the execution of all tasks is&nbsp;<code>max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is&nbsp;<code>max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.</p> <p>The time taken by the first processor to finish the execution of all tasks is <code>max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is <code>max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == processorTime.length &lt;= 25000</code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= processorTime[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li> <li><code>tasks.length == 4 * n</code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: processorTime.sort() tasks.sort() ans = 0 i = len(tasks) - 1 for t in processorTime: ans = max(ans, t + tasks[i]) i -= 4 return ans
2,895
Minimum Processing Time
Medium
<p>You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.</p> <p>You are given an array <code>processorTime</code> representing the time each processor becomes available and an array <code>tasks</code> representing how long each task takes to complete. Return the&nbsp;<em>minimum</em> time needed to complete all tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at <code>time = 8</code>, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at <code>time = 10</code>.&nbsp;</p> <p>The time taken by the first processor to finish the execution of all tasks is&nbsp;<code>max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is&nbsp;<code>max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">23</span></p> <p><strong>Explanation:</strong></p> <p>Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.</p> <p>The time taken by the first processor to finish the execution of all tasks is <code>max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18</code>.</p> <p>The time taken by the second processor to finish the execution of all tasks is <code>max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == processorTime.length &lt;= 25000</code></li> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= processorTime[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= tasks[i] &lt;= 10<sup>9</sup></code></li> <li><code>tasks.length == 4 * n</code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minProcessingTime(processorTime: number[], tasks: number[]): number { processorTime.sort((a, b) => a - b); tasks.sort((a, b) => a - b); let [ans, i] = [0, tasks.length - 1]; for (const t of processorTime) { ans = Math.max(ans, t + tasks[i]); i -= 4; } return ans; }
2,896
Apply Operations to Make Two Strings Equal
Medium
<p>You are given two <strong>0-indexed</strong> binary strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, and a positive integer <code>x</code>.</p> <p>You can perform any of the following operations on the string <code>s1</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and flip both <code>s1[i]</code> and <code>s1[j]</code>. The cost of this operation is <code>x</code>.</li> <li>Choose an index <code>i</code> such that <code>i &lt; n - 1</code> and flip both <code>s1[i]</code> and <code>s1[i + 1]</code>. The cost of this operation is <code>1</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost needed to make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, or return </em><code>-1</code><em> if it is impossible.</em></p> <p><strong>Note</strong> that flipping a character means changing it from <code>0</code> to <code>1</code> or vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;1100011000&quot;, s2 = &quot;0101001010&quot;, x = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose i = 3 and apply the second operation. The resulting string is s1 = &quot;110<u><strong>11</strong></u>11000&quot;. - Choose i = 4 and apply the second operation. The resulting string is s1 = &quot;1101<strong><u>00</u></strong>1000&quot;. - Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = &quot;<u><strong>0</strong></u>1010010<u><strong>1</strong></u>0&quot; = s2. The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;10110&quot;, s2 = &quot;00011&quot;, x = 4 <strong>Output:</strong> -1 <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, x &lt;= 500</code></li> <li><code>s1</code> and <code>s2</code> consist only of the characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> </ul>
String; Dynamic Programming
C++
class Solution { public: int minOperations(string s1, string s2, int x) { vector<int> idx; for (int i = 0; i < s1.size(); ++i) { if (s1[i] != s2[i]) { idx.push_back(i); } } int m = idx.size(); if (m & 1) { return -1; } if (m == 0) { return 0; } int f[m][m]; memset(f, -1, sizeof(f)); function<int(int, int)> dfs = [&](int i, int j) { if (i > j) { return 0; } if (f[i][j] != -1) { return f[i][j]; } f[i][j] = min({dfs(i + 1, j - 1) + x, dfs(i + 2, j) + idx[i + 1] - idx[i], dfs(i, j - 2) + idx[j] - idx[j - 1]}); return f[i][j]; }; return dfs(0, m - 1); } };
2,896
Apply Operations to Make Two Strings Equal
Medium
<p>You are given two <strong>0-indexed</strong> binary strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, and a positive integer <code>x</code>.</p> <p>You can perform any of the following operations on the string <code>s1</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and flip both <code>s1[i]</code> and <code>s1[j]</code>. The cost of this operation is <code>x</code>.</li> <li>Choose an index <code>i</code> such that <code>i &lt; n - 1</code> and flip both <code>s1[i]</code> and <code>s1[i + 1]</code>. The cost of this operation is <code>1</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost needed to make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, or return </em><code>-1</code><em> if it is impossible.</em></p> <p><strong>Note</strong> that flipping a character means changing it from <code>0</code> to <code>1</code> or vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;1100011000&quot;, s2 = &quot;0101001010&quot;, x = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose i = 3 and apply the second operation. The resulting string is s1 = &quot;110<u><strong>11</strong></u>11000&quot;. - Choose i = 4 and apply the second operation. The resulting string is s1 = &quot;1101<strong><u>00</u></strong>1000&quot;. - Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = &quot;<u><strong>0</strong></u>1010010<u><strong>1</strong></u>0&quot; = s2. The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;10110&quot;, s2 = &quot;00011&quot;, x = 4 <strong>Output:</strong> -1 <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, x &lt;= 500</code></li> <li><code>s1</code> and <code>s2</code> consist only of the characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> </ul>
String; Dynamic Programming
Go
func minOperations(s1 string, s2 string, x int) int { idx := []int{} for i := range s1 { if s1[i] != s2[i] { idx = append(idx, i) } } m := len(idx) if m&1 == 1 { return -1 } f := make([][]int, m) for i := range f { f[i] = make([]int, m) for j := range f[i] { f[i][j] = -1 } } var dfs func(i, j int) int dfs = func(i, j int) int { if i > j { return 0 } if f[i][j] != -1 { return f[i][j] } f[i][j] = dfs(i+1, j-1) + x f[i][j] = min(f[i][j], dfs(i+2, j)+idx[i+1]-idx[i]) f[i][j] = min(f[i][j], dfs(i, j-2)+idx[j]-idx[j-1]) return f[i][j] } return dfs(0, m-1) }
2,896
Apply Operations to Make Two Strings Equal
Medium
<p>You are given two <strong>0-indexed</strong> binary strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, and a positive integer <code>x</code>.</p> <p>You can perform any of the following operations on the string <code>s1</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and flip both <code>s1[i]</code> and <code>s1[j]</code>. The cost of this operation is <code>x</code>.</li> <li>Choose an index <code>i</code> such that <code>i &lt; n - 1</code> and flip both <code>s1[i]</code> and <code>s1[i + 1]</code>. The cost of this operation is <code>1</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost needed to make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, or return </em><code>-1</code><em> if it is impossible.</em></p> <p><strong>Note</strong> that flipping a character means changing it from <code>0</code> to <code>1</code> or vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;1100011000&quot;, s2 = &quot;0101001010&quot;, x = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose i = 3 and apply the second operation. The resulting string is s1 = &quot;110<u><strong>11</strong></u>11000&quot;. - Choose i = 4 and apply the second operation. The resulting string is s1 = &quot;1101<strong><u>00</u></strong>1000&quot;. - Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = &quot;<u><strong>0</strong></u>1010010<u><strong>1</strong></u>0&quot; = s2. The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;10110&quot;, s2 = &quot;00011&quot;, x = 4 <strong>Output:</strong> -1 <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, x &lt;= 500</code></li> <li><code>s1</code> and <code>s2</code> consist only of the characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> </ul>
String; Dynamic Programming
Java
class Solution { private List<Integer> idx = new ArrayList<>(); private Integer[][] f; private int x; public int minOperations(String s1, String s2, int x) { int n = s1.length(); for (int i = 0; i < n; ++i) { if (s1.charAt(i) != s2.charAt(i)) { idx.add(i); } } int m = idx.size(); if (m % 2 == 1) { return -1; } this.x = x; f = new Integer[m][m]; return dfs(0, m - 1); } private int dfs(int i, int j) { if (i > j) { return 0; } if (f[i][j] != null) { return f[i][j]; } f[i][j] = dfs(i + 1, j - 1) + x; f[i][j] = Math.min(f[i][j], dfs(i + 2, j) + idx.get(i + 1) - idx.get(i)); f[i][j] = Math.min(f[i][j], dfs(i, j - 2) + idx.get(j) - idx.get(j - 1)); return f[i][j]; } }
2,896
Apply Operations to Make Two Strings Equal
Medium
<p>You are given two <strong>0-indexed</strong> binary strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, and a positive integer <code>x</code>.</p> <p>You can perform any of the following operations on the string <code>s1</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and flip both <code>s1[i]</code> and <code>s1[j]</code>. The cost of this operation is <code>x</code>.</li> <li>Choose an index <code>i</code> such that <code>i &lt; n - 1</code> and flip both <code>s1[i]</code> and <code>s1[i + 1]</code>. The cost of this operation is <code>1</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost needed to make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, or return </em><code>-1</code><em> if it is impossible.</em></p> <p><strong>Note</strong> that flipping a character means changing it from <code>0</code> to <code>1</code> or vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;1100011000&quot;, s2 = &quot;0101001010&quot;, x = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose i = 3 and apply the second operation. The resulting string is s1 = &quot;110<u><strong>11</strong></u>11000&quot;. - Choose i = 4 and apply the second operation. The resulting string is s1 = &quot;1101<strong><u>00</u></strong>1000&quot;. - Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = &quot;<u><strong>0</strong></u>1010010<u><strong>1</strong></u>0&quot; = s2. The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;10110&quot;, s2 = &quot;00011&quot;, x = 4 <strong>Output:</strong> -1 <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, x &lt;= 500</code></li> <li><code>s1</code> and <code>s2</code> consist only of the characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> </ul>
String; Dynamic Programming
Python
class Solution: def minOperations(self, s1: str, s2: str, x: int) -> int: @cache def dfs(i: int, j: int) -> int: if i > j: return 0 a = dfs(i + 1, j - 1) + x b = dfs(i + 2, j) + idx[i + 1] - idx[i] c = dfs(i, j - 2) + idx[j] - idx[j - 1] return min(a, b, c) n = len(s1) idx = [i for i in range(n) if s1[i] != s2[i]] m = len(idx) if m & 1: return -1 return dfs(0, m - 1)
2,896
Apply Operations to Make Two Strings Equal
Medium
<p>You are given two <strong>0-indexed</strong> binary strings <code>s1</code> and <code>s2</code>, both of length <code>n</code>, and a positive integer <code>x</code>.</p> <p>You can perform any of the following operations on the string <code>s1</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and flip both <code>s1[i]</code> and <code>s1[j]</code>. The cost of this operation is <code>x</code>.</li> <li>Choose an index <code>i</code> such that <code>i &lt; n - 1</code> and flip both <code>s1[i]</code> and <code>s1[i + 1]</code>. The cost of this operation is <code>1</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> cost needed to make the strings </em><code>s1</code><em> and </em><code>s2</code><em> equal, or return </em><code>-1</code><em> if it is impossible.</em></p> <p><strong>Note</strong> that flipping a character means changing it from <code>0</code> to <code>1</code> or vice-versa.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;1100011000&quot;, s2 = &quot;0101001010&quot;, x = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose i = 3 and apply the second operation. The resulting string is s1 = &quot;110<u><strong>11</strong></u>11000&quot;. - Choose i = 4 and apply the second operation. The resulting string is s1 = &quot;1101<strong><u>00</u></strong>1000&quot;. - Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = &quot;<u><strong>0</strong></u>1010010<u><strong>1</strong></u>0&quot; = s2. The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s1 = &quot;10110&quot;, s2 = &quot;00011&quot;, x = 4 <strong>Output:</strong> -1 <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, x &lt;= 500</code></li> <li><code>s1</code> and <code>s2</code> consist only of the characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> </ul>
String; Dynamic Programming
TypeScript
function minOperations(s1: string, s2: string, x: number): number { const idx: number[] = []; for (let i = 0; i < s1.length; ++i) { if (s1[i] !== s2[i]) { idx.push(i); } } const m = idx.length; if (m % 2 === 1) { return -1; } if (m === 0) { return 0; } const f: number[][] = Array.from({ length: m }, () => Array.from({ length: m }, () => -1)); const dfs = (i: number, j: number): number => { if (i > j) { return 0; } if (f[i][j] !== -1) { return f[i][j]; } f[i][j] = dfs(i + 1, j - 1) + x; f[i][j] = Math.min(f[i][j], dfs(i + 2, j) + idx[i + 1] - idx[i]); f[i][j] = Math.min(f[i][j], dfs(i, j - 2) + idx[j] - idx[j - 1]); return f[i][j]; }; return dfs(0, m - 1); }
2,897
Apply Operations on Array to Maximize Sum of Squares
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose any two distinct indices <code>i</code> and <code>j</code> and <strong>simultaneously</strong> update the values of <code>nums[i]</code> to <code>(nums[i] AND nums[j])</code> and <code>nums[j]</code> to <code>(nums[i] OR nums[j])</code>. Here, <code>OR</code> denotes the bitwise <code>OR</code> operation, and <code>AND</code> denotes the bitwise <code>AND</code> operation.</li> </ul> <p>You have to choose <code>k</code> elements from the final array and calculate the sum of their <strong>squares</strong>.</p> <p>Return <em>the <strong>maximum</strong> sum of squares you can achieve</em>.</p> <p>Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,5,8], k = 2 <strong>Output:</strong> 261 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 15<sup>2</sup> + 6<sup>2</sup> = 261. It can be shown that this is the maximum value we can get. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,5,4,7], k = 3 <strong>Output:</strong> 90 <strong>Explanation:</strong> We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 7<sup>2</sup> + 5<sup>2</sup> + 4<sup>2</sup> = 90. It can be shown that this is the maximum value we can get. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Bit Manipulation; Array; Hash Table
C++
class Solution { public: int maxSum(vector<int>& nums, int k) { int cnt[31]{}; for (int x : nums) { for (int i = 0; i < 31; ++i) { if (x >> i & 1) { ++cnt[i]; } } } long long ans = 0; const int mod = 1e9 + 7; while (k--) { int x = 0; for (int i = 0; i < 31; ++i) { if (cnt[i]) { x |= 1 << i; --cnt[i]; } } ans = (ans + 1LL * x * x) % mod; } return ans; } };
2,897
Apply Operations on Array to Maximize Sum of Squares
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose any two distinct indices <code>i</code> and <code>j</code> and <strong>simultaneously</strong> update the values of <code>nums[i]</code> to <code>(nums[i] AND nums[j])</code> and <code>nums[j]</code> to <code>(nums[i] OR nums[j])</code>. Here, <code>OR</code> denotes the bitwise <code>OR</code> operation, and <code>AND</code> denotes the bitwise <code>AND</code> operation.</li> </ul> <p>You have to choose <code>k</code> elements from the final array and calculate the sum of their <strong>squares</strong>.</p> <p>Return <em>the <strong>maximum</strong> sum of squares you can achieve</em>.</p> <p>Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,5,8], k = 2 <strong>Output:</strong> 261 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 15<sup>2</sup> + 6<sup>2</sup> = 261. It can be shown that this is the maximum value we can get. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,5,4,7], k = 3 <strong>Output:</strong> 90 <strong>Explanation:</strong> We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 7<sup>2</sup> + 5<sup>2</sup> + 4<sup>2</sup> = 90. It can be shown that this is the maximum value we can get. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Bit Manipulation; Array; Hash Table
Go
func maxSum(nums []int, k int) (ans int) { cnt := [31]int{} for _, x := range nums { for i := 0; i < 31; i++ { if x>>i&1 == 1 { cnt[i]++ } } } const mod int = 1e9 + 7 for ; k > 0; k-- { x := 0 for i := 0; i < 31; i++ { if cnt[i] > 0 { x |= 1 << i cnt[i]-- } } ans = (ans + x*x) % mod } return }
2,897
Apply Operations on Array to Maximize Sum of Squares
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose any two distinct indices <code>i</code> and <code>j</code> and <strong>simultaneously</strong> update the values of <code>nums[i]</code> to <code>(nums[i] AND nums[j])</code> and <code>nums[j]</code> to <code>(nums[i] OR nums[j])</code>. Here, <code>OR</code> denotes the bitwise <code>OR</code> operation, and <code>AND</code> denotes the bitwise <code>AND</code> operation.</li> </ul> <p>You have to choose <code>k</code> elements from the final array and calculate the sum of their <strong>squares</strong>.</p> <p>Return <em>the <strong>maximum</strong> sum of squares you can achieve</em>.</p> <p>Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,5,8], k = 2 <strong>Output:</strong> 261 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 15<sup>2</sup> + 6<sup>2</sup> = 261. It can be shown that this is the maximum value we can get. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,5,4,7], k = 3 <strong>Output:</strong> 90 <strong>Explanation:</strong> We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 7<sup>2</sup> + 5<sup>2</sup> + 4<sup>2</sup> = 90. It can be shown that this is the maximum value we can get. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Bit Manipulation; Array; Hash Table
Java
class Solution { public int maxSum(List<Integer> nums, int k) { final int mod = (int) 1e9 + 7; int[] cnt = new int[31]; for (int x : nums) { for (int i = 0; i < 31; ++i) { if ((x >> i & 1) == 1) { ++cnt[i]; } } } long ans = 0; while (k-- > 0) { int x = 0; for (int i = 0; i < 31; ++i) { if (cnt[i] > 0) { x |= 1 << i; --cnt[i]; } } ans = (ans + 1L * x * x) % mod; } return (int) ans; } }
2,897
Apply Operations on Array to Maximize Sum of Squares
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose any two distinct indices <code>i</code> and <code>j</code> and <strong>simultaneously</strong> update the values of <code>nums[i]</code> to <code>(nums[i] AND nums[j])</code> and <code>nums[j]</code> to <code>(nums[i] OR nums[j])</code>. Here, <code>OR</code> denotes the bitwise <code>OR</code> operation, and <code>AND</code> denotes the bitwise <code>AND</code> operation.</li> </ul> <p>You have to choose <code>k</code> elements from the final array and calculate the sum of their <strong>squares</strong>.</p> <p>Return <em>the <strong>maximum</strong> sum of squares you can achieve</em>.</p> <p>Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,5,8], k = 2 <strong>Output:</strong> 261 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 15<sup>2</sup> + 6<sup>2</sup> = 261. It can be shown that this is the maximum value we can get. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,5,4,7], k = 3 <strong>Output:</strong> 90 <strong>Explanation:</strong> We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 7<sup>2</sup> + 5<sup>2</sup> + 4<sup>2</sup> = 90. It can be shown that this is the maximum value we can get. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Bit Manipulation; Array; Hash Table
Python
class Solution: def maxSum(self, nums: List[int], k: int) -> int: mod = 10**9 + 7 cnt = [0] * 31 for x in nums: for i in range(31): if x >> i & 1: cnt[i] += 1 ans = 0 for _ in range(k): x = 0 for i in range(31): if cnt[i]: x |= 1 << i cnt[i] -= 1 ans = (ans + x * x) % mod return ans
2,897
Apply Operations on Array to Maximize Sum of Squares
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Choose any two distinct indices <code>i</code> and <code>j</code> and <strong>simultaneously</strong> update the values of <code>nums[i]</code> to <code>(nums[i] AND nums[j])</code> and <code>nums[j]</code> to <code>(nums[i] OR nums[j])</code>. Here, <code>OR</code> denotes the bitwise <code>OR</code> operation, and <code>AND</code> denotes the bitwise <code>AND</code> operation.</li> </ul> <p>You have to choose <code>k</code> elements from the final array and calculate the sum of their <strong>squares</strong>.</p> <p>Return <em>the <strong>maximum</strong> sum of squares you can achieve</em>.</p> <p>Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,5,8], k = 2 <strong>Output:</strong> 261 <strong>Explanation:</strong> We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 15<sup>2</sup> + 6<sup>2</sup> = 261. It can be shown that this is the maximum value we can get. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,5,4,7], k = 3 <strong>Output:</strong> 90 <strong>Explanation:</strong> We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 7<sup>2</sup> + 5<sup>2</sup> + 4<sup>2</sup> = 90. It can be shown that this is the maximum value we can get. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Bit Manipulation; Array; Hash Table
TypeScript
function maxSum(nums: number[], k: number): number { const cnt: number[] = Array(31).fill(0); for (const x of nums) { for (let i = 0; i < 31; ++i) { if ((x >> i) & 1) { ++cnt[i]; } } } let ans = 0n; const mod = 1e9 + 7; while (k-- > 0) { let x = 0; for (let i = 0; i < 31; ++i) { if (cnt[i] > 0) { x |= 1 << i; --cnt[i]; } } ans = (ans + BigInt(x) * BigInt(x)) % BigInt(mod); } return Number(ans); }
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
C++
class Solution { public: long long maxScore(vector<int>& prices) { unordered_map<int, long long> cnt; for (int i = 0; i < prices.size(); ++i) { cnt[prices[i] - i] += prices[i]; } long long ans = 0; for (auto& [_, v] : cnt) { ans = max(ans, v); } return ans; } };
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Go
func maxScore(prices []int) (ans int64) { cnt := map[int]int{} for i, x := range prices { cnt[x-i] += x } for _, v := range cnt { ans = max(ans, int64(v)) } return }
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Java
class Solution { public long maxScore(int[] prices) { Map<Integer, Long> cnt = new HashMap<>(); for (int i = 0; i < prices.length; ++i) { cnt.merge(prices[i] - i, (long) prices[i], Long::sum); } long ans = 0; for (long v : cnt.values()) { ans = Math.max(ans, v); } return ans; } }
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Python
class Solution: def maxScore(self, prices: List[int]) -> int: cnt = Counter() for i, x in enumerate(prices): cnt[x - i] += x return max(cnt.values())
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
Rust
use std::collections::HashMap; impl Solution { pub fn max_score(prices: Vec<i32>) -> i64 { let mut cnt: HashMap<i32, i64> = HashMap::new(); for (i, x) in prices.iter().enumerate() { let key = (*x as i32) - (i as i32); let count = cnt.entry(key).or_insert(0); *count += *x as i64; } *cnt.values().max().unwrap_or(&0) } }
2,898
Maximum Linear Stock Score
Medium
<p>Given a <strong>1-indexed</strong> integer array <code>prices</code>, where <code>prices[i]</code> is the price of a particular stock on the <code>i<sup>th</sup></code> day, your task is to select some of the elements of <code>prices</code> such that your selection is <strong>linear</strong>.</p> <p>A selection <code>indexes</code>, where <code>indexes</code> is a <strong>1-indexed</strong> integer array of length <code>k</code> which is a subsequence of the array <code>[1, 2, ..., n]</code>, is <strong>linear</strong> if:</p> <ul> <li>For every <code>1 &lt; j &lt;= k</code>, <code>prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]</code>.</li> </ul> <p>A <b>subsequence</b> 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>The <strong>score</strong> of a selection <code>indexes</code>, is equal to the sum of the following array: <code>[prices[indexes[1]], prices[indexes[2]], ..., prices[indexes[k]]</code>.</p> <p>Return <em>the <strong>maximum</strong> <strong>score</strong> that a linear selection can have</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,5,3,7,8] <strong>Output:</strong> 20 <strong>Explanation:</strong> We can select the indexes [2,4,5]. We show that our selection is linear: For j = 2, we have: indexes[2] - indexes[1] = 4 - 2 = 2. prices[4] - prices[2] = 7 - 5 = 2. For j = 3, we have: indexes[3] - indexes[2] = 5 - 4 = 1. prices[5] - prices[4] = 8 - 7 = 1. The sum of the elements is: prices[2] + prices[4] + prices[5] = 20. It can be shown that the maximum sum a linear selection can have is 20. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [5,6,7,8,9] <strong>Output:</strong> 35 <strong>Explanation:</strong> We can select all of the indexes [1,2,3,4,5]. Since each element has a difference of exactly 1 from its previous element, our selection is linear. The sum of all the elements is 35 which is the maximum possible some out of every selection.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table
TypeScript
function maxScore(prices: number[]): number { const cnt: Map<number, number> = new Map(); for (let i = 0; i < prices.length; ++i) { const j = prices[i] - i; cnt.set(j, (cnt.get(j) || 0) + prices[i]); } return Math.max(...cnt.values()); }
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
C++
class Solution { public: vector<int> lastVisitedIntegers(vector<string>& words) { vector<int> nums; vector<int> ans; int k = 0; for (auto& w : words) { if (w == "prev") { ++k; int i = nums.size() - k; ans.push_back(i < 0 ? -1 : nums[i]); } else { k = 0; nums.push_back(stoi(w)); } } return ans; } };
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
Go
func lastVisitedIntegers(words []string) (ans []int) { nums := []int{} k := 0 for _, w := range words { if w == "prev" { k++ i := len(nums) - k if i < 0 { ans = append(ans, -1) } else { ans = append(ans, nums[i]) } } else { k = 0 x, _ := strconv.Atoi(w) nums = append(nums, x) } } return }
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
Java
class Solution { public List<Integer> lastVisitedIntegers(List<String> words) { List<Integer> nums = new ArrayList<>(); List<Integer> ans = new ArrayList<>(); int k = 0; for (var w : words) { if ("prev".equals(w)) { ++k; int i = nums.size() - k; ans.add(i < 0 ? -1 : nums.get(i)); } else { k = 0; nums.add(Integer.valueOf(w)); } } return ans; } }
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
Python
class Solution: def lastVisitedIntegers(self, words: List[str]) -> List[int]: nums = [] ans = [] k = 0 for w in words: if w == "prev": k += 1 i = len(nums) - k ans.append(-1 if i < 0 else nums[i]) else: k = 0 nums.append(int(w)) return ans
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
Rust
impl Solution { pub fn last_visited_integers(words: Vec<String>) -> Vec<i32> { let mut nums: Vec<i32> = Vec::new(); let mut ans: Vec<i32> = Vec::new(); let mut k = 0; for w in words { if w == "prev" { k += 1; let i = (nums.len() as i32) - k; ans.push(if i < 0 { -1 } else { nums[i as usize] }); } else { k = 0; nums.push(w.parse::<i32>().unwrap()); } } ans } }
2,899
Last Visited Integers
Easy
<p>Given an integer array <code>nums</code> where <code>nums[i]</code> is either a positive integer or <code>-1</code>. We need to find for each <code>-1</code> the respective positive integer, which we call the last visited integer.</p> <p>To achieve this goal, let&#39;s define two empty arrays: <code>seen</code> and <code>ans</code>.</p> <p>Start iterating from the beginning of the array <code>nums</code>.</p> <ul> <li>If a positive integer is encountered, prepend it to the <strong>front</strong> of <code>seen</code>.</li> <li>If <code>-1</code>&nbsp;is encountered, let <code>k</code> be the number of <strong>consecutive</strong> <code>-1</code>s seen so far (including the current <code>-1</code>), <ul> <li>If <code>k</code> is less than or equal to the length of <code>seen</code>, append the <code>k</code>-th element of <code>seen</code> to <code>ans</code>.</li> <li>If <code>k</code> is strictly greater than the length of <code>seen</code>, append <code>-1</code> to <code>ans</code>.</li> </ul> </li> </ul> <p>Return the array<em> </em><code>ans</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-1,-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>2</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in seen. We append <code>2</code> to <code>ans</code>. Now, <code>ans == [2]</code>.</li> <li>Process <code>nums[3]</code>: Another <code>-1</code>. This is the second consecutive <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, so we append <code>1</code> to <code>ans</code>. Now, <code>ans == [2, 1]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>, the third in a row, making <code>k = 3</code>. However, <code>seen</code> only has two elements (<code>[2, 1]</code>). Since <code>k</code> is greater than the number of elements in <code>seen</code>, we append <code>-1</code> to <code>ans</code>. Finally, <code>ans == [2, 1, -1]</code>.</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,2,-1,-1]</span></p> <p><strong>Output:</strong><span class="example-io"> [1,2,1]</span></p> <p><strong>Explanation:</strong></p> <p>Start with <code>seen = []</code> and <code>ans = []</code>.</p> <ol> <li>Process <code>nums[0]</code>: The first element in nums is <code>1</code>. We prepend it to the front of <code>seen</code>. Now, <code>seen == [1]</code>.</li> <li>Process <code>nums[1]</code>: The next element is <code>-1</code>. This is the first occurrence of <code>-1</code>, so <code>k == 1</code>. We look for the first element in <code>seen</code>, which is <code>1</code>. Append <code>1</code> to <code>ans</code>. Now, <code>ans == [1]</code>.</li> <li>Process <code>nums[2]</code>: The next element is <code>2</code>. Prepend this to the front of <code>seen</code>. Now, <code>seen == [2, 1]</code>.</li> <li>Process <code>nums[3]</code>: The next element is <code>-1</code>. This <code>-1</code> is not consecutive to the first <code>-1</code> since <code>2</code> was in between. Thus, <code>k</code> resets to <code>1</code>. The first element in <code>seen</code> is <code>2</code>, so append <code>2</code> to <code>ans</code>. Now, <code>ans == [1, 2]</code>.</li> <li>Process <code>nums[4]</code>: Another <code>-1</code>. This is consecutive to the previous <code>-1</code>, so <code>k == 2</code>. The second element in <code>seen</code> is <code>1</code>, append <code>1</code> to <code>ans</code>. Finally, <code>ans == [1, 2, 1]</code>.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums[i] == -1</code> or <code>1 &lt;= nums[i]&nbsp;&lt;= 100</code></li> </ul>
Array; Simulation
TypeScript
function lastVisitedIntegers(words: string[]): number[] { const nums: number[] = []; const ans: number[] = []; let k = 0; for (const w of words) { if (w === 'prev') { ++k; const i = nums.length - k; ans.push(i < 0 ? -1 : nums[i]); } else { k = 0; nums.push(+w); } } return ans; }
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
C++
class Solution { public: vector<string> getLongestSubsequence(vector<string>& words, vector<int>& groups) { int n = groups.size(); vector<string> ans; for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { ans.emplace_back(words[i]); } } return ans; } };
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
Go
func getLongestSubsequence(words []string, groups []int) (ans []string) { for i, x := range groups { if i == 0 || x != groups[i-1] { ans = append(ans, words[i]) } } return }
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
Java
class Solution { public List<String> getLongestSubsequence(String[] words, int[] groups) { int n = groups.length; List<String> ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (i == 0 || groups[i] != groups[i - 1]) { ans.add(words[i]); } } return ans; } }
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
Python
class Solution: def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]]
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
Rust
impl Solution { pub fn get_longest_subsequence(words: Vec<String>, groups: Vec<i32>) -> Vec<String> { let mut ans = Vec::new(); for (i, &g) in groups.iter().enumerate() { if i == 0 || g != groups[i - 1] { ans.push(words[i].clone()); } } ans } }
2,900
Longest Unequal Adjacent Groups Subsequence I
Easy
<p>You are given a string array <code>words</code> and a <strong>binary</strong> array <code>groups</code> both of length <code>n</code>.</p> <p>A <span data-keyword="subsequence-array">subsequence</span> of <code>words</code> is <strong>alternating</strong> if for any two <em>consecutive</em> strings in the sequence, their corresponding elements at the <em>same</em> indices in <code>groups</code> are <strong>different</strong> (that is, there <em>cannot</em> be consecutive 0 or 1).</p> <p>Your task is to select the <strong>longest alternating</strong> subsequence from <code>words</code>.</p> <p>Return <em>the selected subsequence. If there are multiple answers, return <strong>any</strong> of them.</em></p> <p><strong>Note:</strong> The elements in <code>words</code> are distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;e&quot;,&quot;a&quot;,&quot;b&quot;], groups = [0,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;e&quot;,&quot;b&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;e&quot;,&quot;b&quot;]</code> because <code>groups[0] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;]</code> because <code>groups[1] != groups[2]</code>. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style=" border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem; "> <p><strong>Input:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,0,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io" style=" font-family: Menlo,sans-serif; font-size: 0.85rem; ">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</span></p> <p><strong>Explanation:</strong> A subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[2]</code>. Another subsequence that can be selected is <code>[&quot;a&quot;,&quot;b&quot;,&quot;d&quot;]</code> because <code>groups[0] != groups[1]</code> and <code>groups[1] != groups[3]</code>. It can be shown that the length of the longest subsequence of indices that satisfies the condition is <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>groups[i]</code> is either <code>0</code> or <code>1.</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Greedy; Array; String; Dynamic Programming
TypeScript
function getLongestSubsequence(words: string[], groups: number[]): string[] { const ans: string[] = []; for (let i = 0; i < groups.length; ++i) { if (i === 0 || groups[i] !== groups[i - 1]) { ans.push(words[i]); } } return ans; }
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
C++
class Solution { public: vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) { auto check = [](string& s, string& t) { if (s.size() != t.size()) { return false; } int cnt = 0; for (int i = 0; i < s.size(); ++i) { cnt += s[i] != t[i]; } return cnt == 1; }; int n = groups.size(); vector<int> f(n, 1); vector<int> g(n, -1); int mx = 1; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { f[i] = f[j] + 1; g[i] = j; mx = max(mx, f[i]); } } } vector<string> ans; for (int i = 0; i < n; ++i) { if (f[i] == mx) { for (int j = i; ~j; j = g[j]) { ans.emplace_back(words[j]); } break; } } reverse(ans.begin(), ans.end()); return ans; } };
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
Go
func getWordsInLongestSubsequence(words []string, groups []int) []string { check := func(s, t string) bool { if len(s) != len(t) { return false } cnt := 0 for i := range s { if s[i] != t[i] { cnt++ } } return cnt == 1 } n := len(groups) f := make([]int, n) g := make([]int, n) for i := range f { f[i] = 1 g[i] = -1 } mx := 1 for i, x := range groups { for j, y := range groups[:i] { if x != y && f[i] < f[j]+1 && check(words[i], words[j]) { f[i] = f[j] + 1 g[i] = j if mx < f[i] { mx = f[i] } } } } ans := make([]string, 0, mx) for i, x := range f { if x == mx { for j := i; j >= 0; j = g[j] { ans = append(ans, words[j]) } break } } slices.Reverse(ans) return ans }
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
Java
class Solution { public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) { int n = groups.length; int[] f = new int[n]; int[] g = new int[n]; Arrays.fill(f, 1); Arrays.fill(g, -1); int mx = 1; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { if (groups[i] != groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { f[i] = f[j] + 1; g[i] = j; mx = Math.max(mx, f[i]); } } } List<String> ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (f[i] == mx) { for (int j = i; j >= 0; j = g[j]) { ans.add(words[j]); } break; } } Collections.reverse(ans); return ans; } private boolean check(String s, String t) { if (s.length() != t.length()) { return false; } int cnt = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) != t.charAt(i)) { ++cnt; } } return cnt == 1; } }
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
Python
class Solution: def getWordsInLongestSubsequence( self, words: List[str], groups: List[int] ) -> List[str]: def check(s: str, t: str) -> bool: return len(s) == len(t) and sum(a != b for a, b in zip(s, t)) == 1 n = len(groups) f = [1] * n g = [-1] * n mx = 1 for i, x in enumerate(groups): for j, y in enumerate(groups[:i]): if x != y and f[i] < f[j] + 1 and check(words[i], words[j]): f[i] = f[j] + 1 g[i] = j mx = max(mx, f[i]) ans = [] for i in range(n): if f[i] == mx: j = i while j >= 0: ans.append(words[j]) j = g[j] break return ans[::-1]
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
Rust
impl Solution { pub fn get_words_in_longest_subsequence(words: Vec<String>, groups: Vec<i32>) -> Vec<String> { fn check(s: &str, t: &str) -> bool { s.len() == t.len() && s.chars().zip(t.chars()).filter(|(a, b)| a != b).count() == 1 } let n = groups.len(); let mut f = vec![1; n]; let mut g = vec![-1; n]; let mut mx = 1; for i in 0..n { let x = groups[i] as usize; for j in 0..i { let y = groups[j] as usize; if x != y && f[i] < f[j] + 1 && check(&words[i], &words[j]) { f[i] = f[j] + 1; g[i] = j as i32; mx = mx.max(f[i]); } } } let mut ans = vec![]; let mut i = n - 1; while f[i] != mx { i -= 1; } let mut j = i as i32; while j >= 0 { ans.push(words[j as usize].clone()); j = g[j as usize]; } ans.reverse(); ans } }
2,901
Longest Unequal Adjacent Groups Subsequence II
Medium
<p>You are given a string array <code>words</code>, and an array <code>groups</code>, both arrays having length <code>n</code>.</p> <p>The <strong>hamming distance</strong> between two strings of equal length is the number of positions at which the corresponding characters are <strong>different</strong>.</p> <p>You need to select the <strong>longest</strong> <span data-keyword="subsequence-array">subsequence</span> from an array of indices <code>[0, 1, ..., n - 1]</code>, such that for the subsequence denoted as <code>[i<sub>0</sub>, i<sub>1</sub>, ..., i<sub>k-1</sub>]</code> having length <code>k</code>, the following holds:</p> <ul> <li>For <strong>adjacent</strong> indices in the subsequence, their corresponding groups are <strong>unequal</strong>, i.e., <code>groups[i<sub>j</sub>] != groups[i<sub>j+1</sub>]</code>, for each <code>j</code> where <code>0 &lt; j + 1 &lt; k</code>.</li> <li><code>words[i<sub>j</sub>]</code> and <code>words[i<sub>j+1</sub>]</code> are <strong>equal</strong> in length, and the <strong>hamming distance</strong> between them is <code>1</code>, where <code>0 &lt; j + 1 &lt; k</code>, for all indices in the subsequence.</li> </ul> <p>Return <em>a string array containing the words corresponding to the indices <strong>(in order)</strong> in the selected subsequence</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Note:</strong> strings in <code>words</code> may be <strong>unequal</strong> in length.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;bab&quot;,&quot;dab&quot;,&quot;cab&quot;], groups = [1,2,2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;bab&quot;,&quot;cab&quot;]</span></p> <p><strong>Explanation: </strong>A subsequence that can be selected is <code>[0,2]</code>.</p> <ul> <li><code>groups[0] != groups[2]</code></li> <li><code>words[0].length == words[2].length</code>, and the hamming distance between them is 1.</li> </ul> <p>So, a valid answer is <code>[words[0],words[2]] = [&quot;bab&quot;,&quot;cab&quot;]</code>.</p> <p>Another subsequence that can be selected is <code>[0,1]</code>.</p> <ul> <li><code>groups[0] != groups[1]</code></li> <li><code>words[0].length == words[1].length</code>, and the hamming distance between them is <code>1</code>.</li> </ul> <p>So, another valid answer is <code>[words[0],words[1]] = [&quot;bab&quot;,&quot;dab&quot;]</code>.</p> <p>It can be shown that the length of the longest subsequence of indices that satisfies the conditions is <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">words = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], groups = [1,2,3,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</span></p> <p><strong>Explanation: </strong>We can select the subsequence <code>[0,1,2,3]</code>.</p> <p>It satisfies both conditions.</p> <p>Hence, the answer is <code>[words[0],words[1],words[2],words[3]] = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;]</code>.</p> <p>It has the longest length among all subsequences of indices that satisfy the conditions.</p> <p>Hence, it is the only answer.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == words.length == groups.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>1 &lt;= groups[i] &lt;= n</code></li> <li><code>words</code> consists of <strong>distinct</strong> strings.</li> <li><code>words[i]</code> consists of lowercase English letters.</li> </ul>
Array; String; Dynamic Programming
TypeScript
function getWordsInLongestSubsequence(words: string[], groups: number[]): string[] { const n = groups.length; const f: number[] = Array(n).fill(1); const g: number[] = Array(n).fill(-1); let mx = 1; const check = (s: string, t: string) => { if (s.length !== t.length) { return false; } let cnt = 0; for (let i = 0; i < s.length; ++i) { if (s[i] !== t[i]) { ++cnt; } } return cnt === 1; }; for (let i = 0; i < n; ++i) { for (let j = 0; j < i; ++j) { if (groups[i] !== groups[j] && f[i] < f[j] + 1 && check(words[i], words[j])) { f[i] = f[j] + 1; g[i] = j; mx = Math.max(mx, f[i]); } } } const ans: string[] = []; for (let i = 0; i < n; ++i) { if (f[i] === mx) { for (let j = i; ~j; j = g[j]) { ans.push(words[j]); } break; } } return ans.reverse(); }
2,902
Count of Sub-Multisets With Bounded Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of non-negative integers, and two integers <code>l</code> and <code>r</code>.</p> <p>Return <em>the <strong>count of sub-multisets</strong> within</em> <code>nums</code> <em>where the sum of elements in each subset falls within the inclusive range of</em> <code>[l, r]</code>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>A <strong>sub-multiset</strong> is an <strong>unordered</strong> collection of elements of the array in which a given value <code>x</code> can occur <code>0, 1, ..., occ[x]</code> times, where <code>occ[x]</code> is the number of occurrences of <code>x</code> in the array.</p> <p><strong>Note</strong> that:</p> <ul> <li>Two <strong>sub-multisets</strong> are the same if sorting both sub-multisets results in identical multisets.</li> <li>The sum of an <strong>empty</strong> multiset is <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,3], l = 6, r = 6 <strong>Output:</strong> 1 <strong>Explanation:</strong> The only subset of nums that has a sum of 6 is {1, 2, 3}. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,2,7], l = 1, r = 5 <strong>Output:</strong> 7 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,2], l = 3, r = 5 <strong>Output:</strong> 9 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.</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>0 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li> <li>Sum of <code>nums</code> does not exceed <code>2 * 10<sup>4</sup></code>.</li> <li><code>0 &lt;= l &lt;= r &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming; Sliding Window
C++
class Solution { public: int countSubMultisets(const vector<int>& nums, int l, int r) { int cnt[20001] = {}; int memo[20001] = {}; const int mod = 1000000007; for (int n : nums) { ++cnt[n]; } fill_n(memo, cnt[1] + 1, 1); for (int n = 2, total = cnt[1]; n <= r; ++n) { if (!cnt[n]) { continue; } int top = (cnt[n] + 1) * n; total += n * cnt[n]; for (int i = n, ii = min(total, r); i <= ii; ++i) { memo[i] = (memo[i] + memo[i - n]) % mod; } for (int i = min(total, r); i >= top; --i) { memo[i] = (mod + memo[i] - memo[i - top]) % mod; } } return accumulate(memo + l, memo + r + 1, 0LL) * (cnt[0] + 1) % mod; } };
2,902
Count of Sub-Multisets With Bounded Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of non-negative integers, and two integers <code>l</code> and <code>r</code>.</p> <p>Return <em>the <strong>count of sub-multisets</strong> within</em> <code>nums</code> <em>where the sum of elements in each subset falls within the inclusive range of</em> <code>[l, r]</code>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>A <strong>sub-multiset</strong> is an <strong>unordered</strong> collection of elements of the array in which a given value <code>x</code> can occur <code>0, 1, ..., occ[x]</code> times, where <code>occ[x]</code> is the number of occurrences of <code>x</code> in the array.</p> <p><strong>Note</strong> that:</p> <ul> <li>Two <strong>sub-multisets</strong> are the same if sorting both sub-multisets results in identical multisets.</li> <li>The sum of an <strong>empty</strong> multiset is <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,3], l = 6, r = 6 <strong>Output:</strong> 1 <strong>Explanation:</strong> The only subset of nums that has a sum of 6 is {1, 2, 3}. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,2,7], l = 1, r = 5 <strong>Output:</strong> 7 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,2], l = 3, r = 5 <strong>Output:</strong> 9 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.</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>0 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li> <li>Sum of <code>nums</code> does not exceed <code>2 * 10<sup>4</sup></code>.</li> <li><code>0 &lt;= l &lt;= r &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming; Sliding Window
Go
func countSubMultisets(nums []int, l int, r int) int { multiset := make(map[int]int) for _, num := range nums { multiset[num]++ } mem := make([]int, r+1) mem[0] = 1 prefix := make([]int, len(mem)) for num, occ := range multiset { copy(prefix, mem) for sum := num; sum <= r; sum++ { prefix[sum] = (prefix[sum] + prefix[sum-num]) % mod } for sum := r; sum >= 0; sum-- { if num > 0 { mem[sum] = prefix[sum] if sum >= num*(occ+1) { mem[sum] = (mem[sum] - prefix[sum-num*(occ+1)] + mod) % mod } } else { mem[sum] = (mem[sum] * (occ + 1)) % mod } } } var result int for sum := l; sum <= r; sum++ { result = (result + mem[sum]) % mod } return result } var mod int = 1e9 + 7
2,902
Count of Sub-Multisets With Bounded Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of non-negative integers, and two integers <code>l</code> and <code>r</code>.</p> <p>Return <em>the <strong>count of sub-multisets</strong> within</em> <code>nums</code> <em>where the sum of elements in each subset falls within the inclusive range of</em> <code>[l, r]</code>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>A <strong>sub-multiset</strong> is an <strong>unordered</strong> collection of elements of the array in which a given value <code>x</code> can occur <code>0, 1, ..., occ[x]</code> times, where <code>occ[x]</code> is the number of occurrences of <code>x</code> in the array.</p> <p><strong>Note</strong> that:</p> <ul> <li>Two <strong>sub-multisets</strong> are the same if sorting both sub-multisets results in identical multisets.</li> <li>The sum of an <strong>empty</strong> multiset is <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,3], l = 6, r = 6 <strong>Output:</strong> 1 <strong>Explanation:</strong> The only subset of nums that has a sum of 6 is {1, 2, 3}. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,2,7], l = 1, r = 5 <strong>Output:</strong> 7 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,2], l = 3, r = 5 <strong>Output:</strong> 9 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.</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>0 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li> <li>Sum of <code>nums</code> does not exceed <code>2 * 10<sup>4</sup></code>.</li> <li><code>0 &lt;= l &lt;= r &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming; Sliding Window
Java
class Solution { static final int MOD = 1_000_000_007; public int countSubMultisets(List<Integer> nums, int l, int r) { Map<Integer, Integer> count = new HashMap<>(); int total = 0; for (int num : nums) { total += num; if (num <= r) { count.merge(num, 1, Integer::sum); } } if (total < l) { return 0; } r = Math.min(r, total); int[] dp = new int[r + 1]; dp[0] = count.getOrDefault(0, 0) + 1; count.remove(Integer.valueOf(0)); int sum = 0; for (Map.Entry<Integer, Integer> e : count.entrySet()) { int num = e.getKey(); int c = e.getValue(); sum = Math.min(sum + c * num, r); // prefix part // dp[i] = dp[i] + dp[i - num] + ... + dp[i - c*num] + dp[i-(c+1)*num] + ... + dp[i % // num] for (int i = num; i <= sum; i++) { dp[i] = (dp[i] + dp[i - num]) % MOD; } int temp = (c + 1) * num; // correction part // subtract dp[i - (freq + 1) * num] to the end part. // leves dp[i] = dp[i] + dp[i-num] +...+ dp[i - c*num]; for (int i = sum; i >= temp; i--) { dp[i] = (dp[i] - dp[i - temp] + MOD) % MOD; } } int ans = 0; for (int i = l; i <= r; i++) { ans += dp[i]; ans %= MOD; } return ans; } }
2,902
Count of Sub-Multisets With Bounded Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of non-negative integers, and two integers <code>l</code> and <code>r</code>.</p> <p>Return <em>the <strong>count of sub-multisets</strong> within</em> <code>nums</code> <em>where the sum of elements in each subset falls within the inclusive range of</em> <code>[l, r]</code>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>A <strong>sub-multiset</strong> is an <strong>unordered</strong> collection of elements of the array in which a given value <code>x</code> can occur <code>0, 1, ..., occ[x]</code> times, where <code>occ[x]</code> is the number of occurrences of <code>x</code> in the array.</p> <p><strong>Note</strong> that:</p> <ul> <li>Two <strong>sub-multisets</strong> are the same if sorting both sub-multisets results in identical multisets.</li> <li>The sum of an <strong>empty</strong> multiset is <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,3], l = 6, r = 6 <strong>Output:</strong> 1 <strong>Explanation:</strong> The only subset of nums that has a sum of 6 is {1, 2, 3}. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,2,7], l = 1, r = 5 <strong>Output:</strong> 7 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,2], l = 3, r = 5 <strong>Output:</strong> 9 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.</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>0 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li> <li>Sum of <code>nums</code> does not exceed <code>2 * 10<sup>4</sup></code>.</li> <li><code>0 &lt;= l &lt;= r &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming; Sliding Window
Python
class Solution: def countSubMultisets(self, nums: List[int], l: int, r: int) -> int: kMod = 1_000_000_007 # dp[i] := # of submultisets of nums with sum i dp = [1] + [0] * r count = collections.Counter(nums) zeros = count.pop(0, 0) for num, freq in count.items(): # stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... stride = dp.copy() for i in range(num, r + 1): stride[i] += stride[i - num] for i in range(r, 0, -1): if i >= num * (freq + 1): # dp[i] + dp[i - num] + dp[i - freq * num] dp[i] = stride[i] - stride[i - num * (freq + 1)] else: dp[i] = stride[i] return (zeros + 1) * sum(dp[l : r + 1]) % kMod
2,902
Count of Sub-Multisets With Bounded Sum
Hard
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of non-negative integers, and two integers <code>l</code> and <code>r</code>.</p> <p>Return <em>the <strong>count of sub-multisets</strong> within</em> <code>nums</code> <em>where the sum of elements in each subset falls within the inclusive range of</em> <code>[l, r]</code>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>A <strong>sub-multiset</strong> is an <strong>unordered</strong> collection of elements of the array in which a given value <code>x</code> can occur <code>0, 1, ..., occ[x]</code> times, where <code>occ[x]</code> is the number of occurrences of <code>x</code> in the array.</p> <p><strong>Note</strong> that:</p> <ul> <li>Two <strong>sub-multisets</strong> are the same if sorting both sub-multisets results in identical multisets.</li> <li>The sum of an <strong>empty</strong> multiset is <code>0</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,2,3], l = 6, r = 6 <strong>Output:</strong> 1 <strong>Explanation:</strong> The only subset of nums that has a sum of 6 is {1, 2, 3}. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4,2,7], l = 1, r = 5 <strong>Output:</strong> 7 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,2], l = 3, r = 5 <strong>Output:</strong> 9 <strong>Explanation:</strong> The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.</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>0 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li> <li>Sum of <code>nums</code> does not exceed <code>2 * 10<sup>4</sup></code>.</li> <li><code>0 &lt;= l &lt;= r &lt;= 2 * 10<sup>4</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming; Sliding Window
TypeScript
function countSubMultisets(nums: number[], l: number, r: number): number { const cnt: number[] = Array(20001).fill(0); const memo: number[] = Array(20001).fill(0); const mod: number = 1000000007; for (const n of nums) { cnt[n]++; } memo.fill(1, 0, cnt[1] + 1); let total: number = cnt[1]; for (let n = 2; n <= r; ++n) { if (!cnt[n]) { continue; } const top: number = (cnt[n] + 1) * n; total += n * cnt[n]; for (let i = n, ii = Math.min(total, r); i <= ii; ++i) { memo[i] = (memo[i] + memo[i - n]) % mod; } for (let i = Math.min(total, r); i >= top; --i) { memo[i] = (mod + memo[i] - memo[i - top]) % mod; } } let result: number = 0; for (let i = l; i <= r; i++) { result = (result + memo[i]) % mod; } return (result * (cnt[0] + 1)) % mod; }
2,903
Find Indices With Index and Value Difference I
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p> <p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p> <ul> <li><code>abs(i - j) &gt;= indexDifference</code>, and</li> <li><code>abs(nums[i] - nums[j]) &gt;= valueDifference</code></li> </ul> <p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4 <strong>Output:</strong> [0,3] <strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected. abs(0 - 3) &gt;= 2 and abs(nums[0] - nums[3]) &gt;= 4. Hence, a valid answer is [0,3]. [3,0] is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0 <strong>Output:</strong> [0,0] <strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected. abs(0 - 0) &gt;= 0 and abs(nums[0] - nums[0]) &gt;= 0. Hence, a valid answer is [0,0]. Other valid answers are [0,1], [1,0], and [1,1]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4 <strong>Output:</strong> [-1,-1] <strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions. Hence, [-1,-1] is returned.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= indexDifference &lt;= 100</code></li> <li><code>0 &lt;= valueDifference &lt;= 50</code></li> </ul>
Array; Two Pointers
C++
class Solution { public: vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) { int mi = 0, mx = 0; for (int i = indexDifference; i < nums.size(); ++i) { int j = i - indexDifference; if (nums[j] < nums[mi]) { mi = j; } if (nums[j] > nums[mx]) { mx = j; } if (nums[i] - nums[mi] >= valueDifference) { return {mi, i}; } if (nums[mx] - nums[i] >= valueDifference) { return {mx, i}; } } return {-1, -1}; } };