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,923
|
Find Champion I
|
Easy
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament.</p>
<p>Given a <strong>0-indexed</strong> 2D boolean matrix <code>grid</code> of size <code>n * n</code>. For all <code>i, j</code> that <code>0 <= i, j <= n - 1</code> and <code>i != j</code> team <code>i</code> is <strong>stronger</strong> than team <code>j</code> if <code>grid[i][j] == 1</code>, otherwise, team <code>j</code> is <strong>stronger</strong> than team <code>i</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is stronger than team <code>a</code>.</p>
<p>Return <em>the team that will be the champion of the tournament.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,1],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are two teams in this tournament.
grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are three teams in this tournament.
grid[1][0] == 1 means that team 1 is stronger than team 0.
grid[1][2] == 1 means that team 1 is stronger than team 2.
So team 1 will be the champion.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>For all <code>i grid[i][i]</code> is <code>0.</code></li>
<li>For all <code>i, j</code> that <code>i != j</code>, <code>grid[i][j] != grid[j][i]</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Array; Matrix
|
Go
|
func findChampion(grid [][]int) int {
n := len(grid)
for i := 0; ; i++ {
cnt := 0
for j, x := range grid[i] {
if i != j && x == 1 {
cnt++
}
}
if cnt == n-1 {
return i
}
}
}
|
2,923
|
Find Champion I
|
Easy
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament.</p>
<p>Given a <strong>0-indexed</strong> 2D boolean matrix <code>grid</code> of size <code>n * n</code>. For all <code>i, j</code> that <code>0 <= i, j <= n - 1</code> and <code>i != j</code> team <code>i</code> is <strong>stronger</strong> than team <code>j</code> if <code>grid[i][j] == 1</code>, otherwise, team <code>j</code> is <strong>stronger</strong> than team <code>i</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is stronger than team <code>a</code>.</p>
<p>Return <em>the team that will be the champion of the tournament.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,1],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are two teams in this tournament.
grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are three teams in this tournament.
grid[1][0] == 1 means that team 1 is stronger than team 0.
grid[1][2] == 1 means that team 1 is stronger than team 2.
So team 1 will be the champion.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>For all <code>i grid[i][i]</code> is <code>0.</code></li>
<li>For all <code>i, j</code> that <code>i != j</code>, <code>grid[i][j] != grid[j][i]</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Array; Matrix
|
Java
|
class Solution {
public int findChampion(int[][] grid) {
int n = grid.length;
for (int i = 0;; ++i) {
int cnt = 0;
for (int j = 0; j < n; ++j) {
if (i != j && grid[i][j] == 1) {
++cnt;
}
}
if (cnt == n - 1) {
return i;
}
}
}
}
|
2,923
|
Find Champion I
|
Easy
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament.</p>
<p>Given a <strong>0-indexed</strong> 2D boolean matrix <code>grid</code> of size <code>n * n</code>. For all <code>i, j</code> that <code>0 <= i, j <= n - 1</code> and <code>i != j</code> team <code>i</code> is <strong>stronger</strong> than team <code>j</code> if <code>grid[i][j] == 1</code>, otherwise, team <code>j</code> is <strong>stronger</strong> than team <code>i</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is stronger than team <code>a</code>.</p>
<p>Return <em>the team that will be the champion of the tournament.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,1],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are two teams in this tournament.
grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are three teams in this tournament.
grid[1][0] == 1 means that team 1 is stronger than team 0.
grid[1][2] == 1 means that team 1 is stronger than team 2.
So team 1 will be the champion.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>For all <code>i grid[i][i]</code> is <code>0.</code></li>
<li>For all <code>i, j</code> that <code>i != j</code>, <code>grid[i][j] != grid[j][i]</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Array; Matrix
|
Python
|
class Solution:
def findChampion(self, grid: List[List[int]]) -> int:
for i, row in enumerate(grid):
if all(x == 1 for j, x in enumerate(row) if i != j):
return i
|
2,923
|
Find Champion I
|
Easy
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament.</p>
<p>Given a <strong>0-indexed</strong> 2D boolean matrix <code>grid</code> of size <code>n * n</code>. For all <code>i, j</code> that <code>0 <= i, j <= n - 1</code> and <code>i != j</code> team <code>i</code> is <strong>stronger</strong> than team <code>j</code> if <code>grid[i][j] == 1</code>, otherwise, team <code>j</code> is <strong>stronger</strong> than team <code>i</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is stronger than team <code>a</code>.</p>
<p>Return <em>the team that will be the champion of the tournament.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,1],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are two teams in this tournament.
grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are three teams in this tournament.
grid[1][0] == 1 means that team 1 is stronger than team 0.
grid[1][2] == 1 means that team 1 is stronger than team 2.
So team 1 will be the champion.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>For all <code>i grid[i][i]</code> is <code>0.</code></li>
<li>For all <code>i, j</code> that <code>i != j</code>, <code>grid[i][j] != grid[j][i]</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Array; Matrix
|
TypeScript
|
function findChampion(grid: number[][]): number {
for (let i = 0, n = grid.length; ; ++i) {
let cnt = 0;
for (let j = 0; j < n; ++j) {
if (i !== j && grid[i][j] === 1) {
++cnt;
}
}
if (cnt === n - 1) {
return i;
}
}
}
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
C++
|
class Solution {
public:
int findChampion(int n, vector<vector<int>>& edges) {
int indeg[n];
memset(indeg, 0, sizeof(indeg));
for (auto& e : edges) {
++indeg[e[1]];
}
int ans = -1, cnt = 0;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) {
++cnt;
ans = i;
}
}
return cnt == 1 ? ans : -1;
}
};
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
Go
|
func findChampion(n int, edges [][]int) int {
indeg := make([]int, n)
for _, e := range edges {
indeg[e[1]]++
}
ans, cnt := -1, 0
for i, x := range indeg {
if x == 0 {
cnt++
ans = i
}
}
if cnt == 1 {
return ans
}
return -1
}
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
Java
|
class Solution {
public int findChampion(int n, int[][] edges) {
int[] indeg = new int[n];
for (var e : edges) {
++indeg[e[1]];
}
int ans = -1, cnt = 0;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) {
++cnt;
ans = i;
}
}
return cnt == 1 ? ans : -1;
}
}
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
JavaScript
|
function findChampion(n, edges) {
const indeg = Array(n).fill(0);
for (const [_, v] of edges) {
++indeg[v];
}
let [ans, cnt] = [-1, 0];
for (let i = 0; i < n; ++i) {
if (indeg[i] === 0) {
++cnt;
ans = i;
}
}
return cnt === 1 ? ans : -1;
}
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
Python
|
class Solution:
def findChampion(self, n: int, edges: List[List[int]]) -> int:
indeg = [0] * n
for _, v in edges:
indeg[v] += 1
return -1 if indeg.count(0) != 1 else indeg.index(0)
|
2,924
|
Find Champion II
|
Medium
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament; each team is also a node in a <strong>DAG</strong>.</p>
<p>You are given the integer <code>n</code> and a <strong>0-indexed</strong> 2D integer array <code>edges</code> of length <code><font face="monospace">m</font></code> representing the <strong>DAG</strong>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is a directed edge from team <code>u<sub>i</sub></code> to team <code>v<sub>i</sub></code> in the graph.</p>
<p>A directed edge from <code>a</code> to <code>b</code> in the graph means that team <code>a</code> is <strong>stronger</strong> than team <code>b</code> and team <code>b</code> is <strong>weaker</strong> than team <code>a</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is <strong>stronger</strong> than team <code>a</code>.</p>
<p>Return <em>the team that will be the <strong>champion</strong> of the tournament if there is a <strong>unique</strong> champion, otherwise, return </em><code>-1</code><em>.</em></p>
<p><strong>Notes</strong></p>
<ul>
<li>A <strong>cycle</strong> is a series of nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, a<sub>n+1</sub></code> such that node <code>a<sub>1</sub></code> is the same node as node <code>a<sub>n+1</sub></code>, the nodes <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code> are distinct, and there is a directed edge from the node <code>a<sub>i</sub></code> to node <code>a<sub>i+1</sub></code> for every <code>i</code> in the range <code>[1, n]</code>.</li>
<li>A <strong>DAG</strong> is a directed graph that does not have any <strong>cycle</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-3.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation: </strong>Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img height="300" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2924.Find%20Champion%20II/images/graph-4.png" width="300" /></p>
<pre>
<strong>Input:</strong> n = 4, edges = [[0,2],[1,3],[1,2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>m == edges.length</code></li>
<li><code>0 <= m <= n * (n - 1) / 2</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= edge[i][j] <= n - 1</code></li>
<li><code>edges[i][0] != edges[i][1]</code></li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code>, team <code>b</code> is not stronger than team <code>a</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Graph
|
TypeScript
|
function findChampion(n: number, edges: number[][]): number {
const indeg: number[] = Array(n).fill(0);
for (const [_, v] of edges) {
++indeg[v];
}
let [ans, cnt] = [-1, 0];
for (let i = 0; i < n; ++i) {
if (indeg[i] === 0) {
++cnt;
ans = i;
}
}
return cnt === 1 ? ans : -1;
}
|
2,925
|
Maximum Score After Applying Operations on a Tree
|
Medium
|
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>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.</p>
<p>You start with a score of <code>0</code>. In one operation, you can:</p>
<ul>
<li>Pick any node <code>i</code>.</li>
<li>Add <code>values[i]</code> to your score.</li>
<li>Set <code>values[i]</code> to <code>0</code>.</li>
</ul>
<p>A tree is <strong>healthy</strong> if the sum of values on the path from the root to any leaf node is different than zero.</p>
<p>Return <em>the <strong>maximum score</strong> you can obtain after performing these operations on the tree any number of times so that it remains <strong>healthy</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-13-1.png" style="width: 515px; height: 443px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-14-2.png" style="width: 522px; height: 245px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong> We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>values.length == n</code></li>
<li><code>1 <= values[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
C++
|
class Solution {
public:
long long maximumScoreAfterOperations(vector<vector<int>>& edges, vector<int>& values) {
int n = values.size();
vector<int> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].emplace_back(b);
g[b].emplace_back(a);
}
using ll = long long;
function<pair<ll, ll>(int, int)> dfs = [&](int i, int fa) -> pair<ll, ll> {
ll a = 0, b = 0;
bool leaf = true;
for (int j : g[i]) {
if (j != fa) {
auto [aa, bb] = dfs(j, i);
a += aa;
b += bb;
leaf = false;
}
}
if (leaf) {
return {values[i], 0LL};
}
return {values[i] + a, max(values[i] + b, a)};
};
auto [_, b] = dfs(0, -1);
return b;
}
};
|
2,925
|
Maximum Score After Applying Operations on a Tree
|
Medium
|
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>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.</p>
<p>You start with a score of <code>0</code>. In one operation, you can:</p>
<ul>
<li>Pick any node <code>i</code>.</li>
<li>Add <code>values[i]</code> to your score.</li>
<li>Set <code>values[i]</code> to <code>0</code>.</li>
</ul>
<p>A tree is <strong>healthy</strong> if the sum of values on the path from the root to any leaf node is different than zero.</p>
<p>Return <em>the <strong>maximum score</strong> you can obtain after performing these operations on the tree any number of times so that it remains <strong>healthy</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-13-1.png" style="width: 515px; height: 443px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-14-2.png" style="width: 522px; height: 245px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong> We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>values.length == n</code></li>
<li><code>1 <= values[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Go
|
func maximumScoreAfterOperations(edges [][]int, values []int) int64 {
g := make([][]int, len(values))
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) (int64, int64)
dfs = func(i, fa int) (int64, int64) {
a, b := int64(0), int64(0)
leaf := true
for _, j := range g[i] {
if j != fa {
leaf = false
aa, bb := dfs(j, i)
a += aa
b += bb
}
}
if leaf {
return int64(values[i]), int64(0)
}
return int64(values[i]) + a, max(int64(values[i])+b, a)
}
_, b := dfs(0, -1)
return b
}
|
2,925
|
Maximum Score After Applying Operations on a Tree
|
Medium
|
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>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.</p>
<p>You start with a score of <code>0</code>. In one operation, you can:</p>
<ul>
<li>Pick any node <code>i</code>.</li>
<li>Add <code>values[i]</code> to your score.</li>
<li>Set <code>values[i]</code> to <code>0</code>.</li>
</ul>
<p>A tree is <strong>healthy</strong> if the sum of values on the path from the root to any leaf node is different than zero.</p>
<p>Return <em>the <strong>maximum score</strong> you can obtain after performing these operations on the tree any number of times so that it remains <strong>healthy</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-13-1.png" style="width: 515px; height: 443px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-14-2.png" style="width: 522px; height: 245px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong> We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>values.length == n</code></li>
<li><code>1 <= values[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Java
|
class Solution {
private List<Integer>[] g;
private int[] values;
public long maximumScoreAfterOperations(int[][] edges, int[] values) {
int n = values.length;
g = new List[n];
this.values = values;
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
return dfs(0, -1)[1];
}
private long[] dfs(int i, int fa) {
long a = 0, b = 0;
boolean leaf = true;
for (int j : g[i]) {
if (j != fa) {
leaf = false;
var t = dfs(j, i);
a += t[0];
b += t[1];
}
}
if (leaf) {
return new long[] {values[i], 0};
}
return new long[] {values[i] + a, Math.max(values[i] + b, a)};
}
}
|
2,925
|
Maximum Score After Applying Operations on a Tree
|
Medium
|
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>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.</p>
<p>You start with a score of <code>0</code>. In one operation, you can:</p>
<ul>
<li>Pick any node <code>i</code>.</li>
<li>Add <code>values[i]</code> to your score.</li>
<li>Set <code>values[i]</code> to <code>0</code>.</li>
</ul>
<p>A tree is <strong>healthy</strong> if the sum of values on the path from the root to any leaf node is different than zero.</p>
<p>Return <em>the <strong>maximum score</strong> you can obtain after performing these operations on the tree any number of times so that it remains <strong>healthy</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-13-1.png" style="width: 515px; height: 443px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-14-2.png" style="width: 522px; height: 245px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong> We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>values.length == n</code></li>
<li><code>1 <= values[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
Python
|
class Solution:
def maximumScoreAfterOperations(
self, edges: List[List[int]], values: List[int]
) -> int:
def dfs(i: int, fa: int = -1) -> (int, int):
a = b = 0
leaf = True
for j in g[i]:
if j != fa:
leaf = False
aa, bb = dfs(j, i)
a += aa
b += bb
if leaf:
return values[i], 0
return values[i] + a, max(values[i] + b, a)
g = [[] for _ in range(len(values))]
for a, b in edges:
g[a].append(b)
g[b].append(a)
return dfs(0)[1]
|
2,925
|
Maximum Score After Applying Operations on a Tree
|
Medium
|
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>You are also given a <strong>0-indexed</strong> integer array <code>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.</p>
<p>You start with a score of <code>0</code>. In one operation, you can:</p>
<ul>
<li>Pick any node <code>i</code>.</li>
<li>Add <code>values[i]</code> to your score.</li>
<li>Set <code>values[i]</code> to <code>0</code>.</li>
</ul>
<p>A tree is <strong>healthy</strong> if the sum of values on the path from the root to any leaf node is different than zero.</p>
<p>Return <em>the <strong>maximum score</strong> you can obtain after performing these operations on the tree any number of times so that it remains <strong>healthy</strong>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-13-1.png" style="width: 515px; height: 443px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]
<strong>Output:</strong> 11
<strong>Explanation:</strong> We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.
It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2925.Maximum%20Score%20After%20Applying%20Operations%20on%20a%20Tree/images/graph-14-2.png" style="width: 522px; height: 245px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong> We can choose nodes 0, 2, 3, and 4.
- The sum of values on the path from 0 to 4 is equal to 10.
- The sum of values on the path from 0 to 3 is equal to 10.
- The sum of values on the path from 0 to 5 is equal to 3.
- The sum of values on the path from 0 to 6 is equal to 5.
Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.
It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 2 * 10<sup>4</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>edges[i].length == 2</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code></li>
<li><code>values.length == n</code></li>
<li><code>1 <= values[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>
|
Tree; Depth-First Search; Dynamic Programming
|
TypeScript
|
function maximumScoreAfterOperations(edges: number[][], values: number[]): number {
const g: number[][] = Array.from({ length: values.length }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const dfs = (i: number, fa: number): [number, number] => {
let [a, b] = [0, 0];
let leaf = true;
for (const j of g[i]) {
if (j !== fa) {
const [aa, bb] = dfs(j, i);
a += aa;
b += bb;
leaf = false;
}
}
if (leaf) {
return [values[i], 0];
}
return [values[i] + a, Math.max(values[i] + b, a)];
};
return dfs(0, -1)[1];
}
|
2,926
|
Maximum Balanced Subsequence Sum
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>k</code> and consisting of <strong>indices</strong> <code>i<sub>0</sub> < i<sub>1</sub> < ... < i<sub>k-1</sub></code> is <strong>balanced</strong> if the following holds:</p>
<ul>
<li><code>nums[i<sub>j</sub>] - nums[i<sub>j-1</sub>] >= i<sub>j</sub> - i<sub>j-1</sub></code>, for every <code>j</code> in the range <code>[1, k - 1]</code>.</li>
</ul>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>1</code> is considered balanced.</p>
<p>Return <em>an integer denoting the <strong>maximum</strong> possible <strong>sum of elements</strong> in a <strong>balanced</strong> subsequence of </em><code>nums</code>.</p>
<p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,5,6]
<strong>Output:</strong> 14
<strong>Explanation:</strong> In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,-1,-3,8]
<strong>Output:</strong> 13
<strong>Explanation:</strong> In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.
nums[3] - nums[0] >= 3 - 0.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, the subsequence [-1] can be selected.
It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Dynamic Programming
|
C++
|
class BinaryIndexedTree {
private:
int n;
vector<long long> c;
const long long inf = 1e18;
public:
BinaryIndexedTree(int n) {
this->n = n;
c.resize(n + 1, -inf);
}
void update(int x, long long v) {
while (x <= n) {
c[x] = max(c[x], v);
x += x & -x;
}
}
long long query(int x) {
long long mx = -inf;
while (x > 0) {
mx = max(mx, c[x]);
x -= x & -x;
}
return mx;
}
};
class Solution {
public:
long long maxBalancedSubsequenceSum(vector<int>& nums) {
int n = nums.size();
vector<int> arr(n);
for (int i = 0; i < n; ++i) {
arr[i] = nums[i] - i;
}
sort(arr.begin(), arr.end());
arr.erase(unique(arr.begin(), arr.end()), arr.end());
int m = arr.size();
BinaryIndexedTree tree(m);
for (int i = 0; i < n; ++i) {
int j = lower_bound(arr.begin(), arr.end(), nums[i] - i) - arr.begin() + 1;
long long v = max(tree.query(j), 0LL) + nums[i];
tree.update(j, v);
}
return tree.query(m);
}
};
|
2,926
|
Maximum Balanced Subsequence Sum
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>k</code> and consisting of <strong>indices</strong> <code>i<sub>0</sub> < i<sub>1</sub> < ... < i<sub>k-1</sub></code> is <strong>balanced</strong> if the following holds:</p>
<ul>
<li><code>nums[i<sub>j</sub>] - nums[i<sub>j-1</sub>] >= i<sub>j</sub> - i<sub>j-1</sub></code>, for every <code>j</code> in the range <code>[1, k - 1]</code>.</li>
</ul>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>1</code> is considered balanced.</p>
<p>Return <em>an integer denoting the <strong>maximum</strong> possible <strong>sum of elements</strong> in a <strong>balanced</strong> subsequence of </em><code>nums</code>.</p>
<p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,5,6]
<strong>Output:</strong> 14
<strong>Explanation:</strong> In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,-1,-3,8]
<strong>Output:</strong> 13
<strong>Explanation:</strong> In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.
nums[3] - nums[0] >= 3 - 0.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, the subsequence [-1] can be selected.
It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Dynamic Programming
|
Go
|
const inf int = 1e18
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
c := make([]int, n+1)
for i := range c {
c[i] = -inf
}
return BinaryIndexedTree{n: n, c: c}
}
func (bit *BinaryIndexedTree) update(x, v int) {
for x <= bit.n {
bit.c[x] = max(bit.c[x], v)
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) int {
mx := -inf
for x > 0 {
mx = max(mx, bit.c[x])
x -= x & -x
}
return mx
}
func maxBalancedSubsequenceSum(nums []int) int64 {
n := len(nums)
arr := make([]int, n)
for i, x := range nums {
arr[i] = x - i
}
sort.Ints(arr)
m := 0
for i, x := range arr {
if i == 0 || x != arr[i-1] {
arr[m] = x
m++
}
}
arr = arr[:m]
tree := NewBinaryIndexedTree(m)
for i, x := range nums {
j := sort.SearchInts(arr, x-i) + 1
v := max(tree.query(j), 0) + x
tree.update(j, v)
}
return int64(tree.query(m))
}
|
2,926
|
Maximum Balanced Subsequence Sum
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>k</code> and consisting of <strong>indices</strong> <code>i<sub>0</sub> < i<sub>1</sub> < ... < i<sub>k-1</sub></code> is <strong>balanced</strong> if the following holds:</p>
<ul>
<li><code>nums[i<sub>j</sub>] - nums[i<sub>j-1</sub>] >= i<sub>j</sub> - i<sub>j-1</sub></code>, for every <code>j</code> in the range <code>[1, k - 1]</code>.</li>
</ul>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>1</code> is considered balanced.</p>
<p>Return <em>an integer denoting the <strong>maximum</strong> possible <strong>sum of elements</strong> in a <strong>balanced</strong> subsequence of </em><code>nums</code>.</p>
<p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,5,6]
<strong>Output:</strong> 14
<strong>Explanation:</strong> In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,-1,-3,8]
<strong>Output:</strong> 13
<strong>Explanation:</strong> In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.
nums[3] - nums[0] >= 3 - 0.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, the subsequence [-1] can be selected.
It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Dynamic Programming
|
Java
|
class BinaryIndexedTree {
private int n;
private long[] c;
private final long inf = 1L << 60;
public BinaryIndexedTree(int n) {
this.n = n;
c = new long[n + 1];
Arrays.fill(c, -inf);
}
public void update(int x, long v) {
while (x <= n) {
c[x] = Math.max(c[x], v);
x += x & -x;
}
}
public long query(int x) {
long mx = -inf;
while (x > 0) {
mx = Math.max(mx, c[x]);
x -= x & -x;
}
return mx;
}
}
class Solution {
public long maxBalancedSubsequenceSum(int[] nums) {
int n = nums.length;
int[] arr = new int[n];
for (int i = 0; i < n; ++i) {
arr[i] = nums[i] - i;
}
Arrays.sort(arr);
int m = 0;
for (int i = 0; i < n; ++i) {
if (i == 0 || arr[i] != arr[i - 1]) {
arr[m++] = arr[i];
}
}
BinaryIndexedTree tree = new BinaryIndexedTree(m);
for (int i = 0; i < n; ++i) {
int j = search(arr, nums[i] - i, m) + 1;
long v = Math.max(tree.query(j), 0) + nums[i];
tree.update(j, v);
}
return tree.query(m);
}
private int search(int[] nums, int x, int r) {
int l = 0;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
|
2,926
|
Maximum Balanced Subsequence Sum
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>k</code> and consisting of <strong>indices</strong> <code>i<sub>0</sub> < i<sub>1</sub> < ... < i<sub>k-1</sub></code> is <strong>balanced</strong> if the following holds:</p>
<ul>
<li><code>nums[i<sub>j</sub>] - nums[i<sub>j-1</sub>] >= i<sub>j</sub> - i<sub>j-1</sub></code>, for every <code>j</code> in the range <code>[1, k - 1]</code>.</li>
</ul>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>1</code> is considered balanced.</p>
<p>Return <em>an integer denoting the <strong>maximum</strong> possible <strong>sum of elements</strong> in a <strong>balanced</strong> subsequence of </em><code>nums</code>.</p>
<p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,5,6]
<strong>Output:</strong> 14
<strong>Explanation:</strong> In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,-1,-3,8]
<strong>Output:</strong> 13
<strong>Explanation:</strong> In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.
nums[3] - nums[0] >= 3 - 0.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, the subsequence [-1] can be selected.
It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Dynamic Programming
|
Python
|
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [-inf] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = -inf
while x:
mx = max(mx, self.c[x])
x -= x & -x
return mx
class Solution:
def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:
arr = [x - i for i, x in enumerate(nums)]
s = sorted(set(arr))
tree = BinaryIndexedTree(len(s))
for i, x in enumerate(nums):
j = bisect_left(s, x - i) + 1
v = max(tree.query(j), 0) + x
tree.update(j, v)
return tree.query(len(s))
|
2,926
|
Maximum Balanced Subsequence Sum
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>k</code> and consisting of <strong>indices</strong> <code>i<sub>0</sub> < i<sub>1</sub> < ... < i<sub>k-1</sub></code> is <strong>balanced</strong> if the following holds:</p>
<ul>
<li><code>nums[i<sub>j</sub>] - nums[i<sub>j-1</sub>] >= i<sub>j</sub> - i<sub>j-1</sub></code>, for every <code>j</code> in the range <code>[1, k - 1]</code>.</li>
</ul>
<p>A <strong>subsequence</strong> of <code>nums</code> having length <code>1</code> is considered balanced.</p>
<p>Return <em>an integer denoting the <strong>maximum</strong> possible <strong>sum of elements</strong> in a <strong>balanced</strong> subsequence of </em><code>nums</code>.</p>
<p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,5,6]
<strong>Output:</strong> 14
<strong>Explanation:</strong> In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.
nums[2] - nums[0] >= 2 - 0.
nums[3] - nums[2] >= 3 - 2.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
The subsequence consisting of indices 1, 2, and 3 is also valid.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,-1,-3,8]
<strong>Output:</strong> 13
<strong>Explanation:</strong> In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.
nums[3] - nums[0] >= 3 - 0.
Hence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
It can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, the subsequence [-1] can be selected.
It is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Dynamic Programming
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(-Infinity);
}
update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] = Math.max(this.c[x], v);
x += x & -x;
}
}
query(x: number): number {
let mx = -Infinity;
while (x > 0) {
mx = Math.max(mx, this.c[x]);
x -= x & -x;
}
return mx;
}
}
function maxBalancedSubsequenceSum(nums: number[]): number {
const n = nums.length;
const arr = Array(n).fill(0);
for (let i = 0; i < n; ++i) {
arr[i] = nums[i] - i;
}
arr.sort((a, b) => a - b);
let m = 0;
for (let i = 0; i < n; ++i) {
if (i === 0 || arr[i] !== arr[i - 1]) {
arr[m++] = arr[i];
}
}
arr.length = m;
const tree = new BinaryIndexedTree(m);
const search = (nums: number[], x: number): number => {
let [l, r] = [0, nums.length];
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
for (let i = 0; i < n; ++i) {
const j = search(arr, nums[i] - i) + 1;
const v = Math.max(tree.query(j), 0) + nums[i];
tree.update(j, v);
}
return tree.query(m);
}
|
2,927
|
Distribute Candies Among Children III
|
Hard
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>8</sup></code></li>
<li><code>1 <= limit <= 10<sup>8</sup></code></li>
</ul>
|
Math; Combinatorics
|
C++
|
class Solution {
public:
long long distributeCandies(int n, int limit) {
auto comb2 = [](int n) {
return 1LL * n * (n - 1) / 2;
};
if (n > 3 * limit) {
return 0;
}
long long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
};
|
2,927
|
Distribute Candies Among Children III
|
Hard
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>8</sup></code></li>
<li><code>1 <= limit <= 10<sup>8</sup></code></li>
</ul>
|
Math; Combinatorics
|
Go
|
func distributeCandies(n int, limit int) int64 {
comb2 := func(n int) int {
return n * (n - 1) / 2
}
if n > 3*limit {
return 0
}
ans := comb2(n + 2)
if n > limit {
ans -= 3 * comb2(n-limit+1)
}
if n-2 >= 2*limit {
ans += 3 * comb2(n-2*limit)
}
return int64(ans)
}
|
2,927
|
Distribute Candies Among Children III
|
Hard
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>8</sup></code></li>
<li><code>1 <= limit <= 10<sup>8</sup></code></li>
</ul>
|
Math; Combinatorics
|
Java
|
class Solution {
public long distributeCandies(int n, int limit) {
if (n > 3 * limit) {
return 0;
}
long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
private long comb2(int n) {
return 1L * n * (n - 1) / 2;
}
}
|
2,927
|
Distribute Candies Among Children III
|
Hard
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>8</sup></code></li>
<li><code>1 <= limit <= 10<sup>8</sup></code></li>
</ul>
|
Math; Combinatorics
|
Python
|
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans
|
2,927
|
Distribute Candies Among Children III
|
Hard
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>8</sup></code></li>
<li><code>1 <= limit <= 10<sup>8</sup></code></li>
</ul>
|
Math; Combinatorics
|
TypeScript
|
function distributeCandies(n: number, limit: number): number {
const comb2 = (n: number) => (n * (n - 1)) / 2;
if (n > 3 * limit) {
return 0;
}
let ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
|
2,928
|
Distribute Candies Among Children I
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 50</code></li>
<li><code>1 <= limit <= 50</code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
C++
|
class Solution {
public:
int distributeCandies(int n, int limit) {
auto comb2 = [](int n) {
return 1LL * n * (n - 1) / 2;
};
if (n > 3 * limit) {
return 0;
}
long long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
};
|
2,928
|
Distribute Candies Among Children I
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 50</code></li>
<li><code>1 <= limit <= 50</code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Go
|
func distributeCandies(n int, limit int) int {
comb2 := func(n int) int {
return n * (n - 1) / 2
}
if n > 3*limit {
return 0
}
ans := comb2(n + 2)
if n > limit {
ans -= 3 * comb2(n-limit+1)
}
if n-2 >= 2*limit {
ans += 3 * comb2(n-2*limit)
}
return ans
}
|
2,928
|
Distribute Candies Among Children I
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 50</code></li>
<li><code>1 <= limit <= 50</code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Java
|
class Solution {
public int distributeCandies(int n, int limit) {
if (n > 3 * limit) {
return 0;
}
long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return (int) ans;
}
private long comb2(int n) {
return 1L * n * (n - 1) / 2;
}
}
|
2,928
|
Distribute Candies Among Children I
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 50</code></li>
<li><code>1 <= limit <= 50</code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Python
|
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans
|
2,928
|
Distribute Candies Among Children I
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 50</code></li>
<li><code>1 <= limit <= 50</code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
TypeScript
|
function distributeCandies(n: number, limit: number): number {
const comb2 = (n: number) => (n * (n - 1)) / 2;
if (n > 3 * limit) {
return 0;
}
let ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
C++
|
class Solution {
public:
long long distributeCandies(int n, int limit) {
auto comb2 = [](int n) {
return 1LL * n * (n - 1) / 2;
};
if (n > 3 * limit) {
return 0;
}
long long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
};
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Go
|
func distributeCandies(n int, limit int) int64 {
comb2 := func(n int) int {
return n * (n - 1) / 2
}
if n > 3*limit {
return 0
}
ans := comb2(n + 2)
if n > limit {
ans -= 3 * comb2(n-limit+1)
}
if n-2 >= 2*limit {
ans += 3 * comb2(n-2*limit)
}
return int64(ans)
}
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Java
|
class Solution {
public long distributeCandies(int n, int limit) {
if (n > 3 * limit) {
return 0;
}
long ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
private long comb2(int n) {
return 1L * n * (n - 1) / 2;
}
}
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Python
|
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
Rust
|
impl Solution {
pub fn distribute_candies(n: i32, limit: i32) -> i64 {
if n > 3 * limit {
return 0;
}
let mut ans = Self::comb2(n + 2);
if n > limit {
ans -= 3 * Self::comb2(n - limit + 1);
}
if n - 2 >= 2 * limit {
ans += 3 * Self::comb2(n - 2 * limit);
}
ans
}
fn comb2(n: i32) -> i64 {
(n as i64) * (n as i64 - 1) / 2
}
}
|
2,929
|
Distribute Candies Among Children II
|
Medium
|
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, limit = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, limit = 3
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>6</sup></code></li>
<li><code>1 <= limit <= 10<sup>6</sup></code></li>
</ul>
|
Math; Combinatorics; Enumeration
|
TypeScript
|
function distributeCandies(n: number, limit: number): number {
const comb2 = (n: number) => (n * (n - 1)) / 2;
if (n > 3 * limit) {
return 0;
}
let ans = comb2(n + 2);
if (n > limit) {
ans -= 3 * comb2(n - limit + 1);
}
if (n - 2 >= 2 * limit) {
ans += 3 * comb2(n - 2 * limit);
}
return ans;
}
|
2,930
|
Number of Strings Which Can Be Rearranged to Contain Substring
|
Medium
|
<p>You are given an integer <code>n</code>.</p>
<p>A string <code>s</code> is called <strong>good </strong>if it contains only lowercase English characters <strong>and</strong> it is possible to rearrange the characters of <code>s</code> such that the new string contains <code>"leet"</code> as a <strong>substring</strong>.</p>
<p>For example:</p>
<ul>
<li>The string <code>"lteer"</code> is good because we can rearrange it to form <code>"leetr"</code> .</li>
<li><code>"letl"</code> is not good because we cannot rearrange it to contain <code>"leet"</code> as a substring.</li>
</ul>
<p>Return <em>the <strong>total</strong> number of good strings of length </em><code>n</code>.</p>
<p>Since the answer may be large, return it <strong>modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 12
<strong>Explanation:</strong> The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 83943898
<strong>Explanation:</strong> The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10<sup>9</sup> + 7) = 83943898.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
C++
|
class Solution {
public:
int stringCount(int n) {
const int mod = 1e9 + 7;
using ll = long long;
ll f[n + 1][2][3][2];
memset(f, -1, sizeof(f));
function<ll(int, int, int, int)> dfs = [&](int i, int l, int e, int t) -> ll {
if (i == 0) {
return l == 1 && e == 2 && t == 1 ? 1 : 0;
}
if (f[i][l][e][t] != -1) {
return f[i][l][e][t];
}
ll a = dfs(i - 1, l, e, t) * 23 % mod;
ll b = dfs(i - 1, min(1, l + 1), e, t) % mod;
ll c = dfs(i - 1, l, min(2, e + 1), t) % mod;
ll d = dfs(i - 1, l, e, min(1, t + 1)) % mod;
return f[i][l][e][t] = (a + b + c + d) % mod;
};
return dfs(n, 0, 0, 0);
}
};
|
2,930
|
Number of Strings Which Can Be Rearranged to Contain Substring
|
Medium
|
<p>You are given an integer <code>n</code>.</p>
<p>A string <code>s</code> is called <strong>good </strong>if it contains only lowercase English characters <strong>and</strong> it is possible to rearrange the characters of <code>s</code> such that the new string contains <code>"leet"</code> as a <strong>substring</strong>.</p>
<p>For example:</p>
<ul>
<li>The string <code>"lteer"</code> is good because we can rearrange it to form <code>"leetr"</code> .</li>
<li><code>"letl"</code> is not good because we cannot rearrange it to contain <code>"leet"</code> as a substring.</li>
</ul>
<p>Return <em>the <strong>total</strong> number of good strings of length </em><code>n</code>.</p>
<p>Since the answer may be large, return it <strong>modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 12
<strong>Explanation:</strong> The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 83943898
<strong>Explanation:</strong> The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10<sup>9</sup> + 7) = 83943898.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Go
|
func stringCount(n int) int {
const mod int = 1e9 + 7
f := make([][2][3][2]int, n+1)
for i := range f {
for j := range f[i] {
for k := range f[i][j] {
for l := range f[i][j][k] {
f[i][j][k][l] = -1
}
}
}
}
var dfs func(i, l, e, t int) int
dfs = func(i, l, e, t int) int {
if i == 0 {
if l == 1 && e == 2 && t == 1 {
return 1
}
return 0
}
if f[i][l][e][t] == -1 {
a := dfs(i-1, l, e, t) * 23 % mod
b := dfs(i-1, min(1, l+1), e, t)
c := dfs(i-1, l, min(2, e+1), t)
d := dfs(i-1, l, e, min(1, t+1))
f[i][l][e][t] = (a + b + c + d) % mod
}
return f[i][l][e][t]
}
return dfs(n, 0, 0, 0)
}
|
2,930
|
Number of Strings Which Can Be Rearranged to Contain Substring
|
Medium
|
<p>You are given an integer <code>n</code>.</p>
<p>A string <code>s</code> is called <strong>good </strong>if it contains only lowercase English characters <strong>and</strong> it is possible to rearrange the characters of <code>s</code> such that the new string contains <code>"leet"</code> as a <strong>substring</strong>.</p>
<p>For example:</p>
<ul>
<li>The string <code>"lteer"</code> is good because we can rearrange it to form <code>"leetr"</code> .</li>
<li><code>"letl"</code> is not good because we cannot rearrange it to contain <code>"leet"</code> as a substring.</li>
</ul>
<p>Return <em>the <strong>total</strong> number of good strings of length </em><code>n</code>.</p>
<p>Since the answer may be large, return it <strong>modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 12
<strong>Explanation:</strong> The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 83943898
<strong>Explanation:</strong> The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10<sup>9</sup> + 7) = 83943898.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Java
|
class Solution {
private final int mod = (int) 1e9 + 7;
private Long[][][][] f;
public int stringCount(int n) {
f = new Long[n + 1][2][3][2];
return (int) dfs(n, 0, 0, 0);
}
private long dfs(int i, int l, int e, int t) {
if (i == 0) {
return l == 1 && e == 2 && t == 1 ? 1 : 0;
}
if (f[i][l][e][t] != null) {
return f[i][l][e][t];
}
long a = dfs(i - 1, l, e, t) * 23 % mod;
long b = dfs(i - 1, Math.min(1, l + 1), e, t);
long c = dfs(i - 1, l, Math.min(2, e + 1), t);
long d = dfs(i - 1, l, e, Math.min(1, t + 1));
return f[i][l][e][t] = (a + b + c + d) % mod;
}
}
|
2,930
|
Number of Strings Which Can Be Rearranged to Contain Substring
|
Medium
|
<p>You are given an integer <code>n</code>.</p>
<p>A string <code>s</code> is called <strong>good </strong>if it contains only lowercase English characters <strong>and</strong> it is possible to rearrange the characters of <code>s</code> such that the new string contains <code>"leet"</code> as a <strong>substring</strong>.</p>
<p>For example:</p>
<ul>
<li>The string <code>"lteer"</code> is good because we can rearrange it to form <code>"leetr"</code> .</li>
<li><code>"letl"</code> is not good because we cannot rearrange it to contain <code>"leet"</code> as a substring.</li>
</ul>
<p>Return <em>the <strong>total</strong> number of good strings of length </em><code>n</code>.</p>
<p>Since the answer may be large, return it <strong>modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 12
<strong>Explanation:</strong> The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 83943898
<strong>Explanation:</strong> The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10<sup>9</sup> + 7) = 83943898.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def stringCount(self, n: int) -> int:
@cache
def dfs(i: int, l: int, e: int, t: int) -> int:
if i == 0:
return int(l == 1 and e == 2 and t == 1)
a = dfs(i - 1, l, e, t) * 23 % mod
b = dfs(i - 1, min(1, l + 1), e, t)
c = dfs(i - 1, l, min(2, e + 1), t)
d = dfs(i - 1, l, e, min(1, t + 1))
return (a + b + c + d) % mod
mod = 10**9 + 7
return dfs(n, 0, 0, 0)
|
2,930
|
Number of Strings Which Can Be Rearranged to Contain Substring
|
Medium
|
<p>You are given an integer <code>n</code>.</p>
<p>A string <code>s</code> is called <strong>good </strong>if it contains only lowercase English characters <strong>and</strong> it is possible to rearrange the characters of <code>s</code> such that the new string contains <code>"leet"</code> as a <strong>substring</strong>.</p>
<p>For example:</p>
<ul>
<li>The string <code>"lteer"</code> is good because we can rearrange it to form <code>"leetr"</code> .</li>
<li><code>"letl"</code> is not good because we cannot rearrange it to contain <code>"leet"</code> as a substring.</li>
</ul>
<p>Return <em>the <strong>total</strong> number of good strings of length </em><code>n</code>.</p>
<p>Since the answer may be large, return it <strong>modulo </strong><code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p>
<div class="notranslate" style="all: initial;"> </div>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 12
<strong>Explanation:</strong> The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 83943898
<strong>Explanation:</strong> The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10<sup>9</sup> + 7) = 83943898.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
TypeScript
|
function stringCount(n: number): number {
const mod = 10 ** 9 + 7;
const f: number[][][][] = Array.from({ length: n + 1 }, () =>
Array.from({ length: 2 }, () =>
Array.from({ length: 3 }, () => Array.from({ length: 2 }, () => -1)),
),
);
const dfs = (i: number, l: number, e: number, t: number): number => {
if (i === 0) {
return l === 1 && e === 2 && t === 1 ? 1 : 0;
}
if (f[i][l][e][t] !== -1) {
return f[i][l][e][t];
}
const a = (dfs(i - 1, l, e, t) * 23) % mod;
const b = dfs(i - 1, Math.min(1, l + 1), e, t);
const c = dfs(i - 1, l, Math.min(2, e + 1), t);
const d = dfs(i - 1, l, e, Math.min(1, t + 1));
return (f[i][l][e][t] = (a + b + c + d) % mod);
};
return dfs(n, 0, 0, 0);
}
|
2,931
|
Maximum Spending After Buying Items
|
Hard
|
<p>You are given a <strong>0-indexed</strong> <code>m * n</code> integer matrix <code>values</code>, representing the values of <code>m * n</code> different items in <code>m</code> different shops. Each shop has <code>n</code> items where the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> shop has a value of <code>values[i][j]</code>. Additionally, the items in the <code>i<sup>th</sup></code> shop are sorted in non-increasing order of value. That is, <code>values[i][j] >= values[i][j + 1]</code> for all <code>0 <= j < n - 1</code>.</p>
<p>On each day, you would like to buy a single item from one of the shops. Specifically, On the <code>d<sup>th</sup></code> day you can:</p>
<ul>
<li>Pick any shop <code>i</code>.</li>
<li>Buy the rightmost available item <code>j</code> for the price of <code>values[i][j] * d</code>. That is, find the greatest index <code>j</code> such that item <code>j</code> was never bought before, and buy it for the price of <code>values[i][j] * d</code>.</li>
</ul>
<p><strong>Note</strong> that all items are pairwise different. For example, if you have bought item <code>0</code> from shop <code>1</code>, you can still buy item <code>0</code> from any other shop.</p>
<p>Return <em>the <strong>maximum amount of money that can be spent</strong> on buying all </em> <code>m * n</code> <em>products</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> values = [[8,5,2],[6,4,1],[9,7,3]]
<strong>Output:</strong> 285
<strong>Explanation:</strong> On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.
On the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.
On the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.
On the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.
On the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.
On the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.
On the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.
On the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.
On the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.
Hence, our total spending is equal to 285.
It can be shown that 285 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> values = [[10,8,6,4,2],[9,7,5,3,2]]
<strong>Output:</strong> 386
<strong>Explanation:</strong> On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.
On the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.
On the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.
On the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.
On the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.
On the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.
On the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.
On the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64
On the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.
On the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.
Hence, our total spending is equal to 386.
It can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m == values.length <= 10</code></li>
<li><code>1 <= n == values[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= values[i][j] <= 10<sup>6</sup></code></li>
<li><code>values[i]</code> are sorted in non-increasing order.</li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long maxSpending(vector<vector<int>>& values) {
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;
int m = values.size(), n = values[0].size();
for (int i = 0; i < m; ++i) {
pq.emplace(values[i][n - 1], i, n - 1);
}
long long ans = 0;
for (int d = 1; pq.size(); ++d) {
auto [v, i, j] = pq.top();
pq.pop();
ans += 1LL * v * d;
if (j) {
pq.emplace(values[i][j - 1], i, j - 1);
}
}
return ans;
}
};
|
2,931
|
Maximum Spending After Buying Items
|
Hard
|
<p>You are given a <strong>0-indexed</strong> <code>m * n</code> integer matrix <code>values</code>, representing the values of <code>m * n</code> different items in <code>m</code> different shops. Each shop has <code>n</code> items where the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> shop has a value of <code>values[i][j]</code>. Additionally, the items in the <code>i<sup>th</sup></code> shop are sorted in non-increasing order of value. That is, <code>values[i][j] >= values[i][j + 1]</code> for all <code>0 <= j < n - 1</code>.</p>
<p>On each day, you would like to buy a single item from one of the shops. Specifically, On the <code>d<sup>th</sup></code> day you can:</p>
<ul>
<li>Pick any shop <code>i</code>.</li>
<li>Buy the rightmost available item <code>j</code> for the price of <code>values[i][j] * d</code>. That is, find the greatest index <code>j</code> such that item <code>j</code> was never bought before, and buy it for the price of <code>values[i][j] * d</code>.</li>
</ul>
<p><strong>Note</strong> that all items are pairwise different. For example, if you have bought item <code>0</code> from shop <code>1</code>, you can still buy item <code>0</code> from any other shop.</p>
<p>Return <em>the <strong>maximum amount of money that can be spent</strong> on buying all </em> <code>m * n</code> <em>products</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> values = [[8,5,2],[6,4,1],[9,7,3]]
<strong>Output:</strong> 285
<strong>Explanation:</strong> On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.
On the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.
On the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.
On the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.
On the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.
On the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.
On the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.
On the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.
On the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.
Hence, our total spending is equal to 285.
It can be shown that 285 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> values = [[10,8,6,4,2],[9,7,5,3,2]]
<strong>Output:</strong> 386
<strong>Explanation:</strong> On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.
On the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.
On the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.
On the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.
On the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.
On the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.
On the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.
On the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64
On the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.
On the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.
Hence, our total spending is equal to 386.
It can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m == values.length <= 10</code></li>
<li><code>1 <= n == values[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= values[i][j] <= 10<sup>6</sup></code></li>
<li><code>values[i]</code> are sorted in non-increasing order.</li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Go
|
func maxSpending(values [][]int) (ans int64) {
pq := hp{}
n := len(values[0])
for i, row := range values {
heap.Push(&pq, tuple{row[n-1], i, n - 1})
}
for d := 1; len(pq) > 0; d++ {
p := heap.Pop(&pq).(tuple)
ans += int64(p.v * d)
if p.j > 0 {
heap.Push(&pq, tuple{values[p.i][p.j-1], p.i, p.j - 1})
}
}
return
}
type tuple struct{ v, i, j int }
type hp []tuple
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].v < h[j].v }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
2,931
|
Maximum Spending After Buying Items
|
Hard
|
<p>You are given a <strong>0-indexed</strong> <code>m * n</code> integer matrix <code>values</code>, representing the values of <code>m * n</code> different items in <code>m</code> different shops. Each shop has <code>n</code> items where the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> shop has a value of <code>values[i][j]</code>. Additionally, the items in the <code>i<sup>th</sup></code> shop are sorted in non-increasing order of value. That is, <code>values[i][j] >= values[i][j + 1]</code> for all <code>0 <= j < n - 1</code>.</p>
<p>On each day, you would like to buy a single item from one of the shops. Specifically, On the <code>d<sup>th</sup></code> day you can:</p>
<ul>
<li>Pick any shop <code>i</code>.</li>
<li>Buy the rightmost available item <code>j</code> for the price of <code>values[i][j] * d</code>. That is, find the greatest index <code>j</code> such that item <code>j</code> was never bought before, and buy it for the price of <code>values[i][j] * d</code>.</li>
</ul>
<p><strong>Note</strong> that all items are pairwise different. For example, if you have bought item <code>0</code> from shop <code>1</code>, you can still buy item <code>0</code> from any other shop.</p>
<p>Return <em>the <strong>maximum amount of money that can be spent</strong> on buying all </em> <code>m * n</code> <em>products</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> values = [[8,5,2],[6,4,1],[9,7,3]]
<strong>Output:</strong> 285
<strong>Explanation:</strong> On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.
On the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.
On the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.
On the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.
On the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.
On the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.
On the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.
On the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.
On the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.
Hence, our total spending is equal to 285.
It can be shown that 285 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> values = [[10,8,6,4,2],[9,7,5,3,2]]
<strong>Output:</strong> 386
<strong>Explanation:</strong> On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.
On the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.
On the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.
On the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.
On the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.
On the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.
On the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.
On the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64
On the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.
On the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.
Hence, our total spending is equal to 386.
It can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m == values.length <= 10</code></li>
<li><code>1 <= n == values[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= values[i][j] <= 10<sup>6</sup></code></li>
<li><code>values[i]</code> are sorted in non-increasing order.</li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long maxSpending(int[][] values) {
int m = values.length, n = values[0].length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < m; ++i) {
pq.offer(new int[] {values[i][n - 1], i, n - 1});
}
long ans = 0;
for (int d = 1; !pq.isEmpty(); ++d) {
var p = pq.poll();
int v = p[0], i = p[1], j = p[2];
ans += (long) v * d;
if (j > 0) {
pq.offer(new int[] {values[i][j - 1], i, j - 1});
}
}
return ans;
}
}
|
2,931
|
Maximum Spending After Buying Items
|
Hard
|
<p>You are given a <strong>0-indexed</strong> <code>m * n</code> integer matrix <code>values</code>, representing the values of <code>m * n</code> different items in <code>m</code> different shops. Each shop has <code>n</code> items where the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> shop has a value of <code>values[i][j]</code>. Additionally, the items in the <code>i<sup>th</sup></code> shop are sorted in non-increasing order of value. That is, <code>values[i][j] >= values[i][j + 1]</code> for all <code>0 <= j < n - 1</code>.</p>
<p>On each day, you would like to buy a single item from one of the shops. Specifically, On the <code>d<sup>th</sup></code> day you can:</p>
<ul>
<li>Pick any shop <code>i</code>.</li>
<li>Buy the rightmost available item <code>j</code> for the price of <code>values[i][j] * d</code>. That is, find the greatest index <code>j</code> such that item <code>j</code> was never bought before, and buy it for the price of <code>values[i][j] * d</code>.</li>
</ul>
<p><strong>Note</strong> that all items are pairwise different. For example, if you have bought item <code>0</code> from shop <code>1</code>, you can still buy item <code>0</code> from any other shop.</p>
<p>Return <em>the <strong>maximum amount of money that can be spent</strong> on buying all </em> <code>m * n</code> <em>products</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> values = [[8,5,2],[6,4,1],[9,7,3]]
<strong>Output:</strong> 285
<strong>Explanation:</strong> On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.
On the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.
On the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.
On the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.
On the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.
On the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.
On the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.
On the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.
On the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.
Hence, our total spending is equal to 285.
It can be shown that 285 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> values = [[10,8,6,4,2],[9,7,5,3,2]]
<strong>Output:</strong> 386
<strong>Explanation:</strong> On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.
On the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.
On the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.
On the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.
On the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.
On the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.
On the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.
On the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64
On the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.
On the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.
Hence, our total spending is equal to 386.
It can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m == values.length <= 10</code></li>
<li><code>1 <= n == values[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= values[i][j] <= 10<sup>6</sup></code></li>
<li><code>values[i]</code> are sorted in non-increasing order.</li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def maxSpending(self, values: List[List[int]]) -> int:
n = len(values[0])
pq = [(row[-1], i, n - 1) for i, row in enumerate(values)]
heapify(pq)
ans = d = 0
while pq:
d += 1
v, i, j = heappop(pq)
ans += v * d
if j:
heappush(pq, (values[i][j - 1], i, j - 1))
return ans
|
2,931
|
Maximum Spending After Buying Items
|
Hard
|
<p>You are given a <strong>0-indexed</strong> <code>m * n</code> integer matrix <code>values</code>, representing the values of <code>m * n</code> different items in <code>m</code> different shops. Each shop has <code>n</code> items where the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> shop has a value of <code>values[i][j]</code>. Additionally, the items in the <code>i<sup>th</sup></code> shop are sorted in non-increasing order of value. That is, <code>values[i][j] >= values[i][j + 1]</code> for all <code>0 <= j < n - 1</code>.</p>
<p>On each day, you would like to buy a single item from one of the shops. Specifically, On the <code>d<sup>th</sup></code> day you can:</p>
<ul>
<li>Pick any shop <code>i</code>.</li>
<li>Buy the rightmost available item <code>j</code> for the price of <code>values[i][j] * d</code>. That is, find the greatest index <code>j</code> such that item <code>j</code> was never bought before, and buy it for the price of <code>values[i][j] * d</code>.</li>
</ul>
<p><strong>Note</strong> that all items are pairwise different. For example, if you have bought item <code>0</code> from shop <code>1</code>, you can still buy item <code>0</code> from any other shop.</p>
<p>Return <em>the <strong>maximum amount of money that can be spent</strong> on buying all </em> <code>m * n</code> <em>products</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> values = [[8,5,2],[6,4,1],[9,7,3]]
<strong>Output:</strong> 285
<strong>Explanation:</strong> On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.
On the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.
On the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.
On the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.
On the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.
On the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.
On the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.
On the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.
On the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.
Hence, our total spending is equal to 285.
It can be shown that 285 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> values = [[10,8,6,4,2],[9,7,5,3,2]]
<strong>Output:</strong> 386
<strong>Explanation:</strong> On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.
On the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.
On the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.
On the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.
On the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.
On the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.
On the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.
On the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64
On the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.
On the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.
Hence, our total spending is equal to 386.
It can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m == values.length <= 10</code></li>
<li><code>1 <= n == values[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= values[i][j] <= 10<sup>6</sup></code></li>
<li><code>values[i]</code> are sorted in non-increasing order.</li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
TypeScript
|
function maxSpending(values: number[][]): number {
const m = values.length;
const n = values[0].length;
const pq = new PriorityQueue({ compare: (a, b) => a[0] - b[0] });
for (let i = 0; i < m; ++i) {
pq.enqueue([values[i][n - 1], i, n - 1]);
}
let ans = 0;
for (let d = 1; !pq.isEmpty(); ++d) {
const [v, i, j] = pq.dequeue()!;
ans += v * d;
if (j > 0) {
pq.enqueue([values[i][j - 1], i, j - 1]);
}
}
return ans;
}
|
2,932
|
Maximum Strong Pair XOR I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array <code>nums</code>: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,6,25,30]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 6 strong pairs in the array <code>nums</code>: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).
The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
C++
|
class Solution {
public:
int maximumStrongPairXor(vector<int>& nums) {
int ans = 0;
for (int x : nums) {
for (int y : nums) {
if (abs(x - y) <= min(x, y)) {
ans = max(ans, x ^ y);
}
}
}
return ans;
}
};
|
2,932
|
Maximum Strong Pair XOR I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array <code>nums</code>: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,6,25,30]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 6 strong pairs in the array <code>nums</code>: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).
The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Go
|
func maximumStrongPairXor(nums []int) (ans int) {
for _, x := range nums {
for _, y := range nums {
if abs(x-y) <= min(x, y) {
ans = max(ans, x^y)
}
}
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
2,932
|
Maximum Strong Pair XOR I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array <code>nums</code>: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,6,25,30]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 6 strong pairs in the array <code>nums</code>: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).
The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Java
|
class Solution {
public int maximumStrongPairXor(int[] nums) {
int ans = 0;
for (int x : nums) {
for (int y : nums) {
if (Math.abs(x - y) <= Math.min(x, y)) {
ans = Math.max(ans, x ^ y);
}
}
}
return ans;
}
}
|
2,932
|
Maximum Strong Pair XOR I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array <code>nums</code>: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,6,25,30]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 6 strong pairs in the array <code>nums</code>: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).
The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Python
|
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y))
|
2,932
|
Maximum Strong Pair XOR I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array <code>nums</code>: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,6,25,30]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 6 strong pairs in the array <code>nums</code>: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).
The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
TypeScript
|
function maximumStrongPairXor(nums: number[]): number {
let ans = 0;
for (const x of nums) {
for (const y of nums) {
if (Math.abs(x - y) <= Math.min(x, y)) {
ans = Math.max(ans, x ^ y);
}
}
}
return ans;
}
|
2,933
|
High-Access Employees
|
Medium
|
<p>You are given a 2D <strong>0-indexed</strong> array of strings, <code>access_times</code>, with size <code>n</code>. For each <code>i</code> where <code>0 <= i <= n - 1</code>, <code>access_times[i][0]</code> represents the name of an employee, and <code>access_times[i][1]</code> represents the access time of that employee. All entries in <code>access_times</code> are within the same day.</p>
<p>The access time is represented as <strong>four digits</strong> using a <strong>24-hour</strong> time format, for example, <code>"0800"</code> or <code>"2250"</code>.</p>
<p>An employee is said to be <strong>high-access</strong> if he has accessed the system <strong>three or more</strong> times within a <strong>one-hour period</strong>.</p>
<p>Times with exactly one hour of difference are <strong>not</strong> considered part of the same one-hour period. For example, <code>"0815"</code> and <code>"0915"</code> are not part of the same one-hour period.</p>
<p>Access times at the start and end of the day are <strong>not</strong> counted within the same one-hour period. For example, <code>"0005"</code> and <code>"2350"</code> are not part of the same one-hour period.</p>
<p>Return <em>a list that contains the names of <strong>high-access</strong> employees with any order you want.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]
<strong>Output:</strong> ["a"]
<strong>Explanation:</strong> "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.
But "b" does not have more than two access times at all.
So the answer is ["a"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]
<strong>Output:</strong> ["c","d"]
<strong>Explanation:</strong> "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.
"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.
However, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]
<strong>Output:</strong> ["ab","cd"]
<strong>Explanation:</strong> "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.
"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.
So the answer is ["ab","cd"].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= access_times.length <= 100</code></li>
<li><code>access_times[i].length == 2</code></li>
<li><code>1 <= access_times[i][0].length <= 10</code></li>
<li><code>access_times[i][0]</code> consists only of English small letters.</li>
<li><code>access_times[i][1].length == 4</code></li>
<li><code>access_times[i][1]</code> is in 24-hour time format.</li>
<li><code>access_times[i][1]</code> consists only of <code>'0'</code> to <code>'9'</code>.</li>
</ul>
|
Array; Hash Table; String; Sorting
|
C++
|
class Solution {
public:
vector<string> findHighAccessEmployees(vector<vector<string>>& access_times) {
unordered_map<string, vector<int>> d;
for (auto& e : access_times) {
auto name = e[0];
auto s = e[1];
int t = stoi(s.substr(0, 2)) * 60 + stoi(s.substr(2, 2));
d[name].emplace_back(t);
}
vector<string> ans;
for (auto& [name, ts] : d) {
sort(ts.begin(), ts.end());
for (int i = 2; i < ts.size(); ++i) {
if (ts[i] - ts[i - 2] < 60) {
ans.emplace_back(name);
break;
}
}
}
return ans;
}
};
|
2,933
|
High-Access Employees
|
Medium
|
<p>You are given a 2D <strong>0-indexed</strong> array of strings, <code>access_times</code>, with size <code>n</code>. For each <code>i</code> where <code>0 <= i <= n - 1</code>, <code>access_times[i][0]</code> represents the name of an employee, and <code>access_times[i][1]</code> represents the access time of that employee. All entries in <code>access_times</code> are within the same day.</p>
<p>The access time is represented as <strong>four digits</strong> using a <strong>24-hour</strong> time format, for example, <code>"0800"</code> or <code>"2250"</code>.</p>
<p>An employee is said to be <strong>high-access</strong> if he has accessed the system <strong>three or more</strong> times within a <strong>one-hour period</strong>.</p>
<p>Times with exactly one hour of difference are <strong>not</strong> considered part of the same one-hour period. For example, <code>"0815"</code> and <code>"0915"</code> are not part of the same one-hour period.</p>
<p>Access times at the start and end of the day are <strong>not</strong> counted within the same one-hour period. For example, <code>"0005"</code> and <code>"2350"</code> are not part of the same one-hour period.</p>
<p>Return <em>a list that contains the names of <strong>high-access</strong> employees with any order you want.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]
<strong>Output:</strong> ["a"]
<strong>Explanation:</strong> "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.
But "b" does not have more than two access times at all.
So the answer is ["a"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]
<strong>Output:</strong> ["c","d"]
<strong>Explanation:</strong> "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.
"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.
However, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]
<strong>Output:</strong> ["ab","cd"]
<strong>Explanation:</strong> "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.
"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.
So the answer is ["ab","cd"].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= access_times.length <= 100</code></li>
<li><code>access_times[i].length == 2</code></li>
<li><code>1 <= access_times[i][0].length <= 10</code></li>
<li><code>access_times[i][0]</code> consists only of English small letters.</li>
<li><code>access_times[i][1].length == 4</code></li>
<li><code>access_times[i][1]</code> is in 24-hour time format.</li>
<li><code>access_times[i][1]</code> consists only of <code>'0'</code> to <code>'9'</code>.</li>
</ul>
|
Array; Hash Table; String; Sorting
|
Go
|
func findHighAccessEmployees(access_times [][]string) (ans []string) {
d := map[string][]int{}
for _, e := range access_times {
name, s := e[0], e[1]
h, _ := strconv.Atoi(s[:2])
m, _ := strconv.Atoi(s[2:])
t := h*60 + m
d[name] = append(d[name], t)
}
for name, ts := range d {
sort.Ints(ts)
for i := 2; i < len(ts); i++ {
if ts[i]-ts[i-2] < 60 {
ans = append(ans, name)
break
}
}
}
return
}
|
2,933
|
High-Access Employees
|
Medium
|
<p>You are given a 2D <strong>0-indexed</strong> array of strings, <code>access_times</code>, with size <code>n</code>. For each <code>i</code> where <code>0 <= i <= n - 1</code>, <code>access_times[i][0]</code> represents the name of an employee, and <code>access_times[i][1]</code> represents the access time of that employee. All entries in <code>access_times</code> are within the same day.</p>
<p>The access time is represented as <strong>four digits</strong> using a <strong>24-hour</strong> time format, for example, <code>"0800"</code> or <code>"2250"</code>.</p>
<p>An employee is said to be <strong>high-access</strong> if he has accessed the system <strong>three or more</strong> times within a <strong>one-hour period</strong>.</p>
<p>Times with exactly one hour of difference are <strong>not</strong> considered part of the same one-hour period. For example, <code>"0815"</code> and <code>"0915"</code> are not part of the same one-hour period.</p>
<p>Access times at the start and end of the day are <strong>not</strong> counted within the same one-hour period. For example, <code>"0005"</code> and <code>"2350"</code> are not part of the same one-hour period.</p>
<p>Return <em>a list that contains the names of <strong>high-access</strong> employees with any order you want.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]
<strong>Output:</strong> ["a"]
<strong>Explanation:</strong> "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.
But "b" does not have more than two access times at all.
So the answer is ["a"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]
<strong>Output:</strong> ["c","d"]
<strong>Explanation:</strong> "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.
"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.
However, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]
<strong>Output:</strong> ["ab","cd"]
<strong>Explanation:</strong> "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.
"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.
So the answer is ["ab","cd"].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= access_times.length <= 100</code></li>
<li><code>access_times[i].length == 2</code></li>
<li><code>1 <= access_times[i][0].length <= 10</code></li>
<li><code>access_times[i][0]</code> consists only of English small letters.</li>
<li><code>access_times[i][1].length == 4</code></li>
<li><code>access_times[i][1]</code> is in 24-hour time format.</li>
<li><code>access_times[i][1]</code> consists only of <code>'0'</code> to <code>'9'</code>.</li>
</ul>
|
Array; Hash Table; String; Sorting
|
Java
|
class Solution {
public List<String> findHighAccessEmployees(List<List<String>> access_times) {
Map<String, List<Integer>> d = new HashMap<>();
for (var e : access_times) {
String name = e.get(0), s = e.get(1);
int t = Integer.valueOf(s.substring(0, 2)) * 60 + Integer.valueOf(s.substring(2));
d.computeIfAbsent(name, k -> new ArrayList<>()).add(t);
}
List<String> ans = new ArrayList<>();
for (var e : d.entrySet()) {
String name = e.getKey();
var ts = e.getValue();
Collections.sort(ts);
for (int i = 2; i < ts.size(); ++i) {
if (ts.get(i) - ts.get(i - 2) < 60) {
ans.add(name);
break;
}
}
}
return ans;
}
}
|
2,933
|
High-Access Employees
|
Medium
|
<p>You are given a 2D <strong>0-indexed</strong> array of strings, <code>access_times</code>, with size <code>n</code>. For each <code>i</code> where <code>0 <= i <= n - 1</code>, <code>access_times[i][0]</code> represents the name of an employee, and <code>access_times[i][1]</code> represents the access time of that employee. All entries in <code>access_times</code> are within the same day.</p>
<p>The access time is represented as <strong>four digits</strong> using a <strong>24-hour</strong> time format, for example, <code>"0800"</code> or <code>"2250"</code>.</p>
<p>An employee is said to be <strong>high-access</strong> if he has accessed the system <strong>three or more</strong> times within a <strong>one-hour period</strong>.</p>
<p>Times with exactly one hour of difference are <strong>not</strong> considered part of the same one-hour period. For example, <code>"0815"</code> and <code>"0915"</code> are not part of the same one-hour period.</p>
<p>Access times at the start and end of the day are <strong>not</strong> counted within the same one-hour period. For example, <code>"0005"</code> and <code>"2350"</code> are not part of the same one-hour period.</p>
<p>Return <em>a list that contains the names of <strong>high-access</strong> employees with any order you want.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]
<strong>Output:</strong> ["a"]
<strong>Explanation:</strong> "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.
But "b" does not have more than two access times at all.
So the answer is ["a"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]
<strong>Output:</strong> ["c","d"]
<strong>Explanation:</strong> "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.
"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.
However, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]
<strong>Output:</strong> ["ab","cd"]
<strong>Explanation:</strong> "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.
"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.
So the answer is ["ab","cd"].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= access_times.length <= 100</code></li>
<li><code>access_times[i].length == 2</code></li>
<li><code>1 <= access_times[i][0].length <= 10</code></li>
<li><code>access_times[i][0]</code> consists only of English small letters.</li>
<li><code>access_times[i][1].length == 4</code></li>
<li><code>access_times[i][1]</code> is in 24-hour time format.</li>
<li><code>access_times[i][1]</code> consists only of <code>'0'</code> to <code>'9'</code>.</li>
</ul>
|
Array; Hash Table; String; Sorting
|
Python
|
class Solution:
def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]:
d = defaultdict(list)
for name, t in access_times:
d[name].append(int(t[:2]) * 60 + int(t[2:]))
ans = []
for name, ts in d.items():
ts.sort()
if any(ts[i] - ts[i - 2] < 60 for i in range(2, len(ts))):
ans.append(name)
return ans
|
2,933
|
High-Access Employees
|
Medium
|
<p>You are given a 2D <strong>0-indexed</strong> array of strings, <code>access_times</code>, with size <code>n</code>. For each <code>i</code> where <code>0 <= i <= n - 1</code>, <code>access_times[i][0]</code> represents the name of an employee, and <code>access_times[i][1]</code> represents the access time of that employee. All entries in <code>access_times</code> are within the same day.</p>
<p>The access time is represented as <strong>four digits</strong> using a <strong>24-hour</strong> time format, for example, <code>"0800"</code> or <code>"2250"</code>.</p>
<p>An employee is said to be <strong>high-access</strong> if he has accessed the system <strong>three or more</strong> times within a <strong>one-hour period</strong>.</p>
<p>Times with exactly one hour of difference are <strong>not</strong> considered part of the same one-hour period. For example, <code>"0815"</code> and <code>"0915"</code> are not part of the same one-hour period.</p>
<p>Access times at the start and end of the day are <strong>not</strong> counted within the same one-hour period. For example, <code>"0005"</code> and <code>"2350"</code> are not part of the same one-hour period.</p>
<p>Return <em>a list that contains the names of <strong>high-access</strong> employees with any order you want.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]
<strong>Output:</strong> ["a"]
<strong>Explanation:</strong> "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.
But "b" does not have more than two access times at all.
So the answer is ["a"].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]
<strong>Output:</strong> ["c","d"]
<strong>Explanation:</strong> "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.
"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.
However, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]
<strong>Output:</strong> ["ab","cd"]
<strong>Explanation:</strong> "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.
"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.
So the answer is ["ab","cd"].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= access_times.length <= 100</code></li>
<li><code>access_times[i].length == 2</code></li>
<li><code>1 <= access_times[i][0].length <= 10</code></li>
<li><code>access_times[i][0]</code> consists only of English small letters.</li>
<li><code>access_times[i][1].length == 4</code></li>
<li><code>access_times[i][1]</code> is in 24-hour time format.</li>
<li><code>access_times[i][1]</code> consists only of <code>'0'</code> to <code>'9'</code>.</li>
</ul>
|
Array; Hash Table; String; Sorting
|
TypeScript
|
function findHighAccessEmployees(access_times: string[][]): string[] {
const d: Map<string, number[]> = new Map();
for (const [name, s] of access_times) {
const h = parseInt(s.slice(0, 2), 10);
const m = parseInt(s.slice(2), 10);
const t = h * 60 + m;
if (!d.has(name)) {
d.set(name, []);
}
d.get(name)!.push(t);
}
const ans: string[] = [];
for (const [name, ts] of d) {
ts.sort((a, b) => a - b);
for (let i = 2; i < ts.length; ++i) {
if (ts[i] - ts[i - 2] < 60) {
ans.push(name);
break;
}
}
}
return ans;
}
|
2,934
|
Minimum Operations to Maximize Last Elements in Arrays
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>nums1</code> and <code>nums2</code>, both having length <code>n</code>.</p>
<p>You are allowed to perform a series of <strong>operations</strong> (<strong>possibly none</strong>).</p>
<p>In an operation, you select an index <code>i</code> in the range <code>[0, n - 1]</code> and <strong>swap</strong> the values of <code>nums1[i]</code> and <code>nums2[i]</code>.</p>
<p>Your task is to find the <strong>minimum</strong> number of operations required to satisfy the following conditions:</p>
<ul>
<li><code>nums1[n - 1]</code> is equal to the <strong>maximum value</strong> among all elements of <code>nums1</code>, i.e., <code>nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])</code>.</li>
<li><code>nums2[n - 1]</code> is equal to the <strong>maximum</strong> <strong>value</strong> among all elements of <code>nums2</code>, i.e., <code>nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of operations needed to meet <strong>both</strong> conditions</em>, <em>or </em><code>-1</code><em> if it is <strong>impossible</strong> to satisfy both conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,7], nums2 = [4,5,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, an operation can be performed using index i = 2.
When nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 1.
So, the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the following operations can be performed:
First operation using index i = 4.
When nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].
Another operation using index i = 3.
When nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 2.
So, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,5,4], nums2 = [2,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is not possible to satisfy both conditions.
So, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums1.length == nums2.length <= 1000</code></li>
<li><code>1 <= nums1[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
auto f = [&](int x, int y) {
int cnt = 0;
for (int i = 0; i < n - 1; ++i) {
if (nums1[i] <= x && nums2[i] <= y) {
continue;
}
if (!(nums1[i] <= y && nums2[i] <= x)) {
return -1;
}
++cnt;
}
return cnt;
};
int a = f(nums1.back(), nums2.back());
int b = f(nums2.back(), nums1.back());
return a + b == -2 ? -1 : min(a, b + 1);
}
};
|
2,934
|
Minimum Operations to Maximize Last Elements in Arrays
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>nums1</code> and <code>nums2</code>, both having length <code>n</code>.</p>
<p>You are allowed to perform a series of <strong>operations</strong> (<strong>possibly none</strong>).</p>
<p>In an operation, you select an index <code>i</code> in the range <code>[0, n - 1]</code> and <strong>swap</strong> the values of <code>nums1[i]</code> and <code>nums2[i]</code>.</p>
<p>Your task is to find the <strong>minimum</strong> number of operations required to satisfy the following conditions:</p>
<ul>
<li><code>nums1[n - 1]</code> is equal to the <strong>maximum value</strong> among all elements of <code>nums1</code>, i.e., <code>nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])</code>.</li>
<li><code>nums2[n - 1]</code> is equal to the <strong>maximum</strong> <strong>value</strong> among all elements of <code>nums2</code>, i.e., <code>nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of operations needed to meet <strong>both</strong> conditions</em>, <em>or </em><code>-1</code><em> if it is <strong>impossible</strong> to satisfy both conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,7], nums2 = [4,5,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, an operation can be performed using index i = 2.
When nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 1.
So, the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the following operations can be performed:
First operation using index i = 4.
When nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].
Another operation using index i = 3.
When nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 2.
So, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,5,4], nums2 = [2,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is not possible to satisfy both conditions.
So, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums1.length == nums2.length <= 1000</code></li>
<li><code>1 <= nums1[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Go
|
func minOperations(nums1 []int, nums2 []int) int {
n := len(nums1)
f := func(x, y int) (cnt int) {
for i, a := range nums1[:n-1] {
b := nums2[i]
if a <= x && b <= y {
continue
}
if !(a <= y && b <= x) {
return -1
}
cnt++
}
return
}
a, b := f(nums1[n-1], nums2[n-1]), f(nums2[n-1], nums1[n-1])
if a+b == -2 {
return -1
}
return min(a, b+1)
}
|
2,934
|
Minimum Operations to Maximize Last Elements in Arrays
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>nums1</code> and <code>nums2</code>, both having length <code>n</code>.</p>
<p>You are allowed to perform a series of <strong>operations</strong> (<strong>possibly none</strong>).</p>
<p>In an operation, you select an index <code>i</code> in the range <code>[0, n - 1]</code> and <strong>swap</strong> the values of <code>nums1[i]</code> and <code>nums2[i]</code>.</p>
<p>Your task is to find the <strong>minimum</strong> number of operations required to satisfy the following conditions:</p>
<ul>
<li><code>nums1[n - 1]</code> is equal to the <strong>maximum value</strong> among all elements of <code>nums1</code>, i.e., <code>nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])</code>.</li>
<li><code>nums2[n - 1]</code> is equal to the <strong>maximum</strong> <strong>value</strong> among all elements of <code>nums2</code>, i.e., <code>nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of operations needed to meet <strong>both</strong> conditions</em>, <em>or </em><code>-1</code><em> if it is <strong>impossible</strong> to satisfy both conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,7], nums2 = [4,5,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, an operation can be performed using index i = 2.
When nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 1.
So, the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the following operations can be performed:
First operation using index i = 4.
When nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].
Another operation using index i = 3.
When nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 2.
So, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,5,4], nums2 = [2,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is not possible to satisfy both conditions.
So, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums1.length == nums2.length <= 1000</code></li>
<li><code>1 <= nums1[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Java
|
class Solution {
private int n;
public int minOperations(int[] nums1, int[] nums2) {
n = nums1.length;
int a = f(nums1, nums2, nums1[n - 1], nums2[n - 1]);
int b = f(nums1, nums2, nums2[n - 1], nums1[n - 1]);
return a + b == -2 ? -1 : Math.min(a, b + 1);
}
private int f(int[] nums1, int[] nums2, int x, int y) {
int cnt = 0;
for (int i = 0; i < n - 1; ++i) {
if (nums1[i] <= x && nums2[i] <= y) {
continue;
}
if (!(nums1[i] <= y && nums2[i] <= x)) {
return -1;
}
++cnt;
}
return cnt;
}
}
|
2,934
|
Minimum Operations to Maximize Last Elements in Arrays
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>nums1</code> and <code>nums2</code>, both having length <code>n</code>.</p>
<p>You are allowed to perform a series of <strong>operations</strong> (<strong>possibly none</strong>).</p>
<p>In an operation, you select an index <code>i</code> in the range <code>[0, n - 1]</code> and <strong>swap</strong> the values of <code>nums1[i]</code> and <code>nums2[i]</code>.</p>
<p>Your task is to find the <strong>minimum</strong> number of operations required to satisfy the following conditions:</p>
<ul>
<li><code>nums1[n - 1]</code> is equal to the <strong>maximum value</strong> among all elements of <code>nums1</code>, i.e., <code>nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])</code>.</li>
<li><code>nums2[n - 1]</code> is equal to the <strong>maximum</strong> <strong>value</strong> among all elements of <code>nums2</code>, i.e., <code>nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of operations needed to meet <strong>both</strong> conditions</em>, <em>or </em><code>-1</code><em> if it is <strong>impossible</strong> to satisfy both conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,7], nums2 = [4,5,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, an operation can be performed using index i = 2.
When nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 1.
So, the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the following operations can be performed:
First operation using index i = 4.
When nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].
Another operation using index i = 3.
When nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 2.
So, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,5,4], nums2 = [2,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is not possible to satisfy both conditions.
So, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums1.length == nums2.length <= 1000</code></li>
<li><code>1 <= nums1[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
Python
|
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
def f(x: int, y: int) -> int:
cnt = 0
for a, b in zip(nums1[:-1], nums2[:-1]):
if a <= x and b <= y:
continue
if not (a <= y and b <= x):
return -1
cnt += 1
return cnt
a, b = f(nums1[-1], nums2[-1]), f(nums2[-1], nums1[-1])
return -1 if a + b == -2 else min(a, b + 1)
|
2,934
|
Minimum Operations to Maximize Last Elements in Arrays
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays, <code>nums1</code> and <code>nums2</code>, both having length <code>n</code>.</p>
<p>You are allowed to perform a series of <strong>operations</strong> (<strong>possibly none</strong>).</p>
<p>In an operation, you select an index <code>i</code> in the range <code>[0, n - 1]</code> and <strong>swap</strong> the values of <code>nums1[i]</code> and <code>nums2[i]</code>.</p>
<p>Your task is to find the <strong>minimum</strong> number of operations required to satisfy the following conditions:</p>
<ul>
<li><code>nums1[n - 1]</code> is equal to the <strong>maximum value</strong> among all elements of <code>nums1</code>, i.e., <code>nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])</code>.</li>
<li><code>nums2[n - 1]</code> is equal to the <strong>maximum</strong> <strong>value</strong> among all elements of <code>nums2</code>, i.e., <code>nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of operations needed to meet <strong>both</strong> conditions</em>, <em>or </em><code>-1</code><em> if it is <strong>impossible</strong> to satisfy both conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,7], nums2 = [4,5,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, an operation can be performed using index i = 2.
When nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 1.
So, the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> In this example, the following operations can be performed:
First operation using index i = 4.
When nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].
Another operation using index i = 3.
When nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].
Both conditions are now satisfied.
It can be shown that the minimum number of operations needed to be performed is 2.
So, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,5,4], nums2 = [2,5,3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> In this example, it is not possible to satisfy both conditions.
So, the answer is -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums1.length == nums2.length <= 1000</code></li>
<li><code>1 <= nums1[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Enumeration
|
TypeScript
|
function minOperations(nums1: number[], nums2: number[]): number {
const n = nums1.length;
const f = (x: number, y: number): number => {
let cnt = 0;
for (let i = 0; i < n - 1; ++i) {
if (nums1[i] <= x && nums2[i] <= y) {
continue;
}
if (!(nums1[i] <= y && nums2[i] <= x)) {
return -1;
}
++cnt;
}
return cnt;
};
const a = f(nums1.at(-1), nums2.at(-1));
const b = f(nums2.at(-1), nums1.at(-1));
return a + b === -2 ? -1 : Math.min(a, b + 1);
}
|
2,935
|
Maximum Strong Pair XOR II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array nums: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [500,520,2500,3000]
<strong>Output:</strong> 1020
<strong>Explanation:</strong> There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).
The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 2<sup>20</sup> - 1</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
C++
|
class Trie {
public:
Trie* children[2];
int cnt;
Trie()
: cnt(0) {
children[0] = nullptr;
children[1] = nullptr;
}
void insert(int x) {
Trie* node = this;
for (int i = 20; ~i; --i) {
int v = (x >> i) & 1;
if (node->children[v] == nullptr) {
node->children[v] = new Trie();
}
node = node->children[v];
++node->cnt;
}
}
int search(int x) {
Trie* node = this;
int ans = 0;
for (int i = 20; ~i; --i) {
int v = (x >> i) & 1;
if (node->children[v ^ 1] != nullptr && node->children[v ^ 1]->cnt > 0) {
ans |= 1 << i;
node = node->children[v ^ 1];
} else {
node = node->children[v];
}
}
return ans;
}
void remove(int x) {
Trie* node = this;
for (int i = 20; ~i; --i) {
int v = (x >> i) & 1;
node = node->children[v];
--node->cnt;
}
}
};
class Solution {
public:
int maximumStrongPairXor(vector<int>& nums) {
sort(nums.begin(), nums.end());
Trie* tree = new Trie();
int ans = 0, i = 0;
for (int y : nums) {
tree->insert(y);
while (y > nums[i] * 2) {
tree->remove(nums[i++]);
}
ans = max(ans, tree->search(y));
}
return ans;
}
};
|
2,935
|
Maximum Strong Pair XOR II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array nums: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [500,520,2500,3000]
<strong>Output:</strong> 1020
<strong>Explanation:</strong> There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).
The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 2<sup>20</sup> - 1</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Go
|
type Trie struct {
children [2]*Trie
cnt int
}
func newTrie() *Trie {
return &Trie{}
}
func (t *Trie) insert(x int) {
node := t
for i := 20; i >= 0; i-- {
v := (x >> uint(i)) & 1
if node.children[v] == nil {
node.children[v] = newTrie()
}
node = node.children[v]
node.cnt++
}
}
func (t *Trie) search(x int) int {
node := t
ans := 0
for i := 20; i >= 0; i-- {
v := (x >> uint(i)) & 1
if node.children[v^1] != nil && node.children[v^1].cnt > 0 {
ans |= 1 << uint(i)
node = node.children[v^1]
} else {
node = node.children[v]
}
}
return ans
}
func (t *Trie) remove(x int) {
node := t
for i := 20; i >= 0; i-- {
v := (x >> uint(i)) & 1
node = node.children[v]
node.cnt--
}
}
func maximumStrongPairXor(nums []int) (ans int) {
sort.Ints(nums)
tree := newTrie()
i := 0
for _, y := range nums {
tree.insert(y)
for ; y > nums[i]*2; i++ {
tree.remove(nums[i])
}
ans = max(ans, tree.search(y))
}
return ans
}
|
2,935
|
Maximum Strong Pair XOR II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array nums: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [500,520,2500,3000]
<strong>Output:</strong> 1020
<strong>Explanation:</strong> There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).
The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 2<sup>20</sup> - 1</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Java
|
class Trie {
private Trie[] children = new Trie[2];
private int cnt = 0;
public Trie() {
}
public void insert(int x) {
Trie node = this;
for (int i = 20; i >= 0; --i) {
int v = x >> i & 1;
if (node.children[v] == null) {
node.children[v] = new Trie();
}
node = node.children[v];
++node.cnt;
}
}
public int search(int x) {
Trie node = this;
int ans = 0;
for (int i = 20; i >= 0; --i) {
int v = x >> i & 1;
if (node.children[v ^ 1] != null && node.children[v ^ 1].cnt > 0) {
ans |= 1 << i;
node = node.children[v ^ 1];
} else {
node = node.children[v];
}
}
return ans;
}
public void remove(int x) {
Trie node = this;
for (int i = 20; i >= 0; --i) {
int v = x >> i & 1;
node = node.children[v];
--node.cnt;
}
}
}
class Solution {
public int maximumStrongPairXor(int[] nums) {
Arrays.sort(nums);
Trie tree = new Trie();
int ans = 0, i = 0;
for (int y : nums) {
tree.insert(y);
while (y > nums[i] * 2) {
tree.remove(nums[i++]);
}
ans = Math.max(ans, tree.search(y));
}
return ans;
}
}
|
2,935
|
Maximum Strong Pair XOR II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array nums: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [500,520,2500,3000]
<strong>Output:</strong> 1020
<strong>Explanation:</strong> There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).
The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 2<sup>20</sup> - 1</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
Python
|
class Trie:
__slots__ = ("children", "cnt")
def __init__(self):
self.children: List[Trie | None] = [None, None]
self.cnt = 0
def insert(self, x: int):
node = self
for i in range(20, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
node.cnt += 1
def search(self, x: int) -> int:
node = self
ans = 0
for i in range(20, -1, -1):
v = x >> i & 1
if node.children[v ^ 1] and node.children[v ^ 1].cnt:
ans |= 1 << i
node = node.children[v ^ 1]
else:
node = node.children[v]
return ans
def remove(self, x: int):
node = self
for i in range(20, -1, -1):
v = x >> i & 1
node = node.children[v]
node.cnt -= 1
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
nums.sort()
tree = Trie()
ans = i = 0
for y in nums:
tree.insert(y)
while y > nums[i] * 2:
tree.remove(nums[i])
i += 1
ans = max(ans, tree.search(y))
return ans
|
2,935
|
Maximum Strong Pair XOR II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of integers <code>x</code> and <code>y</code> is called a <strong>strong</strong> pair if it satisfies the condition:</p>
<ul>
<li><code>|x - y| <= min(x, y)</code></li>
</ul>
<p>You need to select two integers from <code>nums</code> such that they form a strong pair and their bitwise <code>XOR</code> is the <strong>maximum</strong> among all strong pairs in the array.</p>
<p>Return <em>the <strong>maximum</strong> </em><code>XOR</code><em> value out of all possible strong pairs in the array</em> <code>nums</code>.</p>
<p><strong>Note</strong> that you can pick the same integer twice to form a pair.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 11 strong pairs in the array <code>nums</code>: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).
The maximum XOR possible from these pairs is 3 XOR 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,100]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 2 strong pairs in the array nums: (10, 10) and (100, 100).
The maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [500,520,2500,3000]
<strong>Output:</strong> 1020
<strong>Explanation:</strong> There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).
The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 2<sup>20</sup> - 1</code></li>
</ul>
|
Bit Manipulation; Trie; Array; Hash Table; Sliding Window
|
TypeScript
|
class Trie {
children: (Trie | null)[];
cnt: number;
constructor() {
this.children = [null, null];
this.cnt = 0;
}
insert(x: number): void {
let node: Trie | null = this;
for (let i = 20; i >= 0; i--) {
const v = (x >> i) & 1;
if (node.children[v] === null) {
node.children[v] = new Trie();
}
node = node.children[v] as Trie;
node.cnt++;
}
}
search(x: number): number {
let node: Trie | null = this;
let ans = 0;
for (let i = 20; i >= 0; i--) {
const v = (x >> i) & 1;
if (node.children[v ^ 1] !== null && (node.children[v ^ 1] as Trie).cnt > 0) {
ans |= 1 << i;
node = node.children[v ^ 1] as Trie;
} else {
node = node.children[v] as Trie;
}
}
return ans;
}
remove(x: number): void {
let node: Trie | null = this;
for (let i = 20; i >= 0; i--) {
const v = (x >> i) & 1;
node = node.children[v] as Trie;
node.cnt--;
}
}
}
function maximumStrongPairXor(nums: number[]): number {
nums.sort((a, b) => a - b);
const tree = new Trie();
let ans = 0;
let i = 0;
for (const y of nums) {
tree.insert(y);
while (y > nums[i] * 2) {
tree.remove(nums[i++]);
}
ans = Math.max(ans, tree.search(y));
}
return ans;
}
|
2,936
|
Number of Equal Numbers Blocks
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers, <code>nums</code>. The following property holds for <code>nums</code>:</p>
<ul>
<li>All occurrences of a value are adjacent. In other words, if there are two indices <code>i < j</code> such that <code>nums[i] == nums[j]</code>, then for every index <code>k</code> that <code>i < k < j</code>, <code>nums[k] == nums[i]</code>.</li>
</ul>
<p>Since <code>nums</code> is a very large array, you are given an instance of the class <code>BigArray</code> which has the following functions:</p>
<ul>
<li><code>int at(long long index)</code>: Returns the value of <code>nums[i]</code>.</li>
<li><code>void size()</code>: Returns <code>nums.length</code>.</li>
</ul>
<p>Let's partition the array into <strong>maximal</strong> blocks such that each block contains <strong>equal values</strong>. Return<em> the number of these blocks.</em></p>
<p><strong>Note</strong> that if you want to test your solution using a custom test, behavior for tests with <code>nums.length > 10</code> is undefined.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only one block here which is the whole array (because all numbers are equal) and that is: [<u>3,3,3,3,3</u>]. So the answer would be 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,3,9,9,9,2,10,10]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 blocks here:
Block number 1: [<u>1,1,1</u>,3,9,9,9,2,10,10]
Block number 2: [1,1,1,<u>3</u>,9,9,9,2,10,10]
Block number 3: [1,1,1,3,<u>9,9,9</u>,2,10,10]
Block number 4: [1,1,1,3,9,9,9,<u>2</u>,10,10]
Block number 5: [1,1,1,3,9,9,9,2,<u>10,10</u>]
So the answer would be 5.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Since all numbers are distinct, there are 7 blocks here and each element representing one block. So the answer would be 7.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>15</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that all equal values are adjacent.</li>
<li>The sum of the elements of <code>nums</code> is at most <code>10<sup>15</sup></code>.</li>
</ul>
|
Array; Binary Search; Interactive
|
C++
|
/**
* Definition for BigArray.
* class BigArray {
* public:
* BigArray(vector<int> elements);
* int at(long long index);
* long long size();
* };
*/
class Solution {
public:
int countBlocks(BigArray* nums) {
int ans = 0;
using ll = long long;
ll n = nums->size();
auto search = [&](ll l) {
ll r = n;
int x = nums->at(l);
while (l < r) {
ll mid = (l + r) >> 1;
if (nums->at(mid) != x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
for (long long i = 0; i < n; ++ans) {
i = search(i);
}
return ans;
}
};
|
2,936
|
Number of Equal Numbers Blocks
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers, <code>nums</code>. The following property holds for <code>nums</code>:</p>
<ul>
<li>All occurrences of a value are adjacent. In other words, if there are two indices <code>i < j</code> such that <code>nums[i] == nums[j]</code>, then for every index <code>k</code> that <code>i < k < j</code>, <code>nums[k] == nums[i]</code>.</li>
</ul>
<p>Since <code>nums</code> is a very large array, you are given an instance of the class <code>BigArray</code> which has the following functions:</p>
<ul>
<li><code>int at(long long index)</code>: Returns the value of <code>nums[i]</code>.</li>
<li><code>void size()</code>: Returns <code>nums.length</code>.</li>
</ul>
<p>Let's partition the array into <strong>maximal</strong> blocks such that each block contains <strong>equal values</strong>. Return<em> the number of these blocks.</em></p>
<p><strong>Note</strong> that if you want to test your solution using a custom test, behavior for tests with <code>nums.length > 10</code> is undefined.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only one block here which is the whole array (because all numbers are equal) and that is: [<u>3,3,3,3,3</u>]. So the answer would be 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,3,9,9,9,2,10,10]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 blocks here:
Block number 1: [<u>1,1,1</u>,3,9,9,9,2,10,10]
Block number 2: [1,1,1,<u>3</u>,9,9,9,2,10,10]
Block number 3: [1,1,1,3,<u>9,9,9</u>,2,10,10]
Block number 4: [1,1,1,3,9,9,9,<u>2</u>,10,10]
Block number 5: [1,1,1,3,9,9,9,2,<u>10,10</u>]
So the answer would be 5.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Since all numbers are distinct, there are 7 blocks here and each element representing one block. So the answer would be 7.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>15</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that all equal values are adjacent.</li>
<li>The sum of the elements of <code>nums</code> is at most <code>10<sup>15</sup></code>.</li>
</ul>
|
Array; Binary Search; Interactive
|
Java
|
/**
* Definition for BigArray.
* class BigArray {
* public BigArray(int[] elements);
* public int at(long index);
* public long size();
* }
*/
class Solution {
public int countBlocks(BigArray nums) {
int ans = 0;
for (long i = 0, n = nums.size(); i < n; ++ans) {
i = search(nums, i, n);
}
return ans;
}
private long search(BigArray nums, long l, long n) {
long r = n;
int x = nums.at(l);
while (l < r) {
long mid = (l + r) >> 1;
if (nums.at(mid) != x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
|
2,936
|
Number of Equal Numbers Blocks
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers, <code>nums</code>. The following property holds for <code>nums</code>:</p>
<ul>
<li>All occurrences of a value are adjacent. In other words, if there are two indices <code>i < j</code> such that <code>nums[i] == nums[j]</code>, then for every index <code>k</code> that <code>i < k < j</code>, <code>nums[k] == nums[i]</code>.</li>
</ul>
<p>Since <code>nums</code> is a very large array, you are given an instance of the class <code>BigArray</code> which has the following functions:</p>
<ul>
<li><code>int at(long long index)</code>: Returns the value of <code>nums[i]</code>.</li>
<li><code>void size()</code>: Returns <code>nums.length</code>.</li>
</ul>
<p>Let's partition the array into <strong>maximal</strong> blocks such that each block contains <strong>equal values</strong>. Return<em> the number of these blocks.</em></p>
<p><strong>Note</strong> that if you want to test your solution using a custom test, behavior for tests with <code>nums.length > 10</code> is undefined.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only one block here which is the whole array (because all numbers are equal) and that is: [<u>3,3,3,3,3</u>]. So the answer would be 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,3,9,9,9,2,10,10]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 blocks here:
Block number 1: [<u>1,1,1</u>,3,9,9,9,2,10,10]
Block number 2: [1,1,1,<u>3</u>,9,9,9,2,10,10]
Block number 3: [1,1,1,3,<u>9,9,9</u>,2,10,10]
Block number 4: [1,1,1,3,9,9,9,<u>2</u>,10,10]
Block number 5: [1,1,1,3,9,9,9,2,<u>10,10</u>]
So the answer would be 5.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Since all numbers are distinct, there are 7 blocks here and each element representing one block. So the answer would be 7.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>15</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that all equal values are adjacent.</li>
<li>The sum of the elements of <code>nums</code> is at most <code>10<sup>15</sup></code>.</li>
</ul>
|
Array; Binary Search; Interactive
|
Python
|
# Definition for BigArray.
# class BigArray:
# def at(self, index: long) -> int:
# pass
# def size(self) -> long:
# pass
class Solution(object):
def countBlocks(self, nums: Optional["BigArray"]) -> int:
i, n = 0, nums.size()
ans = 0
while i < n:
ans += 1
x = nums.at(i)
if i + 1 < n and nums.at(i + 1) != x:
i += 1
else:
i += bisect_left(range(i, n), True, key=lambda j: nums.at(j) != x)
return ans
|
2,936
|
Number of Equal Numbers Blocks
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers, <code>nums</code>. The following property holds for <code>nums</code>:</p>
<ul>
<li>All occurrences of a value are adjacent. In other words, if there are two indices <code>i < j</code> such that <code>nums[i] == nums[j]</code>, then for every index <code>k</code> that <code>i < k < j</code>, <code>nums[k] == nums[i]</code>.</li>
</ul>
<p>Since <code>nums</code> is a very large array, you are given an instance of the class <code>BigArray</code> which has the following functions:</p>
<ul>
<li><code>int at(long long index)</code>: Returns the value of <code>nums[i]</code>.</li>
<li><code>void size()</code>: Returns <code>nums.length</code>.</li>
</ul>
<p>Let's partition the array into <strong>maximal</strong> blocks such that each block contains <strong>equal values</strong>. Return<em> the number of these blocks.</em></p>
<p><strong>Note</strong> that if you want to test your solution using a custom test, behavior for tests with <code>nums.length > 10</code> is undefined.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3,3,3]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only one block here which is the whole array (because all numbers are equal) and that is: [<u>3,3,3,3,3</u>]. So the answer would be 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,3,9,9,9,2,10,10]
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 blocks here:
Block number 1: [<u>1,1,1</u>,3,9,9,9,2,10,10]
Block number 2: [1,1,1,<u>3</u>,9,9,9,2,10,10]
Block number 3: [1,1,1,3,<u>9,9,9</u>,2,10,10]
Block number 4: [1,1,1,3,9,9,9,<u>2</u>,10,10]
Block number 5: [1,1,1,3,9,9,9,2,<u>10,10</u>]
So the answer would be 5.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6,7]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Since all numbers are distinct, there are 7 blocks here and each element representing one block. So the answer would be 7.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>15</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The input is generated such that all equal values are adjacent.</li>
<li>The sum of the elements of <code>nums</code> is at most <code>10<sup>15</sup></code>.</li>
</ul>
|
Array; Binary Search; Interactive
|
TypeScript
|
/**
* Definition for BigArray.
* class BigArray {
* constructor(elements: number[]);
* public at(index: number): number;
* public size(): number;
* }
*/
function countBlocks(nums: BigArray | null): number {
const n = nums.size();
const search = (l: number): number => {
let r = n;
const x = nums.at(l);
while (l < r) {
const mid = l + Math.floor((r - l) / 2);
if (nums.at(mid) !== x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
let ans = 0;
for (let i = 0; i < n; ++ans) {
i = search(i);
}
return ans;
}
|
2,937
|
Make Three Strings Equal
|
Easy
|
<p>You are given three strings: <code>s1</code>, <code>s2</code>, and <code>s3</code>. In one operation you can choose one of these strings and delete its <strong>rightmost</strong> character. Note that you <strong>cannot</strong> completely empty a string.</p>
<p>Return the <em>minimum number of operations</em> required to make the strings equal<em>. </em>If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </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;">s1 = "abc", s2 = "abb", s3 = "ab"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation: </strong>Deleting the rightmost character from both <code>s1</code> and <code>s2</code> will result in three equal strings.</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;">s1 = "dac", s2 = "bac", s3 = "cac"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">-1</span></p>
<p><strong>Explanation:</strong> Since the first letters of <code>s1</code> and <code>s2</code> differ, they cannot be made equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length, s3.length <= 100</code></li>
<li><font face="monospace"><code>s1</code>,</font> <code><font face="monospace">s2</font></code><font face="monospace"> and</font> <code><font face="monospace">s3</font></code> consist only of lowercase English letters.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
int findMinimumOperations(string s1, string s2, string s3) {
int s = s1.size() + s2.size() + s3.size();
int n = min({s1.size(), s2.size(), s3.size()});
for (int i = 0; i < n; ++i) {
if (!(s1[i] == s2[i] && s2[i] == s3[i])) {
return i == 0 ? -1 : s - 3 * i;
}
}
return s - 3 * n;
}
};
|
2,937
|
Make Three Strings Equal
|
Easy
|
<p>You are given three strings: <code>s1</code>, <code>s2</code>, and <code>s3</code>. In one operation you can choose one of these strings and delete its <strong>rightmost</strong> character. Note that you <strong>cannot</strong> completely empty a string.</p>
<p>Return the <em>minimum number of operations</em> required to make the strings equal<em>. </em>If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </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;">s1 = "abc", s2 = "abb", s3 = "ab"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation: </strong>Deleting the rightmost character from both <code>s1</code> and <code>s2</code> will result in three equal strings.</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;">s1 = "dac", s2 = "bac", s3 = "cac"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">-1</span></p>
<p><strong>Explanation:</strong> Since the first letters of <code>s1</code> and <code>s2</code> differ, they cannot be made equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length, s3.length <= 100</code></li>
<li><font face="monospace"><code>s1</code>,</font> <code><font face="monospace">s2</font></code><font face="monospace"> and</font> <code><font face="monospace">s3</font></code> consist only of lowercase English letters.</li>
</ul>
|
String
|
Go
|
func findMinimumOperations(s1 string, s2 string, s3 string) int {
s := len(s1) + len(s2) + len(s3)
n := min(len(s1), len(s2), len(s3))
for i := range s1[:n] {
if !(s1[i] == s2[i] && s2[i] == s3[i]) {
if i == 0 {
return -1
}
return s - 3*i
}
}
return s - 3*n
}
|
2,937
|
Make Three Strings Equal
|
Easy
|
<p>You are given three strings: <code>s1</code>, <code>s2</code>, and <code>s3</code>. In one operation you can choose one of these strings and delete its <strong>rightmost</strong> character. Note that you <strong>cannot</strong> completely empty a string.</p>
<p>Return the <em>minimum number of operations</em> required to make the strings equal<em>. </em>If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </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;">s1 = "abc", s2 = "abb", s3 = "ab"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation: </strong>Deleting the rightmost character from both <code>s1</code> and <code>s2</code> will result in three equal strings.</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;">s1 = "dac", s2 = "bac", s3 = "cac"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">-1</span></p>
<p><strong>Explanation:</strong> Since the first letters of <code>s1</code> and <code>s2</code> differ, they cannot be made equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length, s3.length <= 100</code></li>
<li><font face="monospace"><code>s1</code>,</font> <code><font face="monospace">s2</font></code><font face="monospace"> and</font> <code><font face="monospace">s3</font></code> consist only of lowercase English letters.</li>
</ul>
|
String
|
Java
|
class Solution {
public int findMinimumOperations(String s1, String s2, String s3) {
int s = s1.length() + s2.length() + s3.length();
int n = Math.min(Math.min(s1.length(), s2.length()), s3.length());
for (int i = 0; i < n; ++i) {
if (!(s1.charAt(i) == s2.charAt(i) && s2.charAt(i) == s3.charAt(i))) {
return i == 0 ? -1 : s - 3 * i;
}
}
return s - 3 * n;
}
}
|
2,937
|
Make Three Strings Equal
|
Easy
|
<p>You are given three strings: <code>s1</code>, <code>s2</code>, and <code>s3</code>. In one operation you can choose one of these strings and delete its <strong>rightmost</strong> character. Note that you <strong>cannot</strong> completely empty a string.</p>
<p>Return the <em>minimum number of operations</em> required to make the strings equal<em>. </em>If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </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;">s1 = "abc", s2 = "abb", s3 = "ab"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation: </strong>Deleting the rightmost character from both <code>s1</code> and <code>s2</code> will result in three equal strings.</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;">s1 = "dac", s2 = "bac", s3 = "cac"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">-1</span></p>
<p><strong>Explanation:</strong> Since the first letters of <code>s1</code> and <code>s2</code> differ, they cannot be made equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length, s3.length <= 100</code></li>
<li><font face="monospace"><code>s1</code>,</font> <code><font face="monospace">s2</font></code><font face="monospace"> and</font> <code><font face="monospace">s3</font></code> consist only of lowercase English letters.</li>
</ul>
|
String
|
Python
|
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
s = len(s1) + len(s2) + len(s3)
n = min(len(s1), len(s2), len(s3))
for i in range(n):
if not s1[i] == s2[i] == s3[i]:
return -1 if i == 0 else s - 3 * i
return s - 3 * n
|
2,937
|
Make Three Strings Equal
|
Easy
|
<p>You are given three strings: <code>s1</code>, <code>s2</code>, and <code>s3</code>. In one operation you can choose one of these strings and delete its <strong>rightmost</strong> character. Note that you <strong>cannot</strong> completely empty a string.</p>
<p>Return the <em>minimum number of operations</em> required to make the strings equal<em>. </em>If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </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;">s1 = "abc", s2 = "abb", s3 = "ab"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p>
<p><strong>Explanation: </strong>Deleting the rightmost character from both <code>s1</code> and <code>s2</code> will result in three equal strings.</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;">s1 = "dac", s2 = "bac", s3 = "cac"</span></p>
<p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">-1</span></p>
<p><strong>Explanation:</strong> Since the first letters of <code>s1</code> and <code>s2</code> differ, they cannot be made equal.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length, s3.length <= 100</code></li>
<li><font face="monospace"><code>s1</code>,</font> <code><font face="monospace">s2</font></code><font face="monospace"> and</font> <code><font face="monospace">s3</font></code> consist only of lowercase English letters.</li>
</ul>
|
String
|
TypeScript
|
function findMinimumOperations(s1: string, s2: string, s3: string): number {
const s = s1.length + s2.length + s3.length;
const n = Math.min(s1.length, s2.length, s3.length);
for (let i = 0; i < n; ++i) {
if (!(s1[i] === s2[i] && s2[i] === s3[i])) {
return i === 0 ? -1 : s - 3 * i;
}
}
return s - 3 * n;
}
|
2,938
|
Separate Black and White Balls
|
Medium
|
<p>There are <code>n</code> balls on a table, each ball has a color black or white.</p>
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code>, where <code>1</code> and <code>0</code> represent black and white balls, respectively.</p>
<p>In each step, you can choose two adjacent balls and swap them.</p>
<p>Return <em>the <strong>minimum</strong> number of steps to group all the black balls to the right and all the white balls to the left</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "101"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "011".
Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "100"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "010".
- Swap s[1] and s[2], s = "001".
It can be proven that the minimum number of steps needed is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0111"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the black balls are already grouped to the right.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
Greedy; Two Pointers; String
|
C++
|
class Solution {
public:
long long minimumSteps(string s) {
long long ans = 0;
int cnt = 0;
int n = s.size();
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '1') {
++cnt;
ans += n - i - cnt;
}
}
return ans;
}
};
|
2,938
|
Separate Black and White Balls
|
Medium
|
<p>There are <code>n</code> balls on a table, each ball has a color black or white.</p>
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code>, where <code>1</code> and <code>0</code> represent black and white balls, respectively.</p>
<p>In each step, you can choose two adjacent balls and swap them.</p>
<p>Return <em>the <strong>minimum</strong> number of steps to group all the black balls to the right and all the white balls to the left</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "101"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "011".
Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "100"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "010".
- Swap s[1] and s[2], s = "001".
It can be proven that the minimum number of steps needed is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0111"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the black balls are already grouped to the right.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
Greedy; Two Pointers; String
|
Go
|
func minimumSteps(s string) (ans int64) {
n := len(s)
cnt := 0
for i := n - 1; i >= 0; i-- {
if s[i] == '1' {
cnt++
ans += int64(n - i - cnt)
}
}
return
}
|
2,938
|
Separate Black and White Balls
|
Medium
|
<p>There are <code>n</code> balls on a table, each ball has a color black or white.</p>
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code>, where <code>1</code> and <code>0</code> represent black and white balls, respectively.</p>
<p>In each step, you can choose two adjacent balls and swap them.</p>
<p>Return <em>the <strong>minimum</strong> number of steps to group all the black balls to the right and all the white balls to the left</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "101"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "011".
Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "100"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "010".
- Swap s[1] and s[2], s = "001".
It can be proven that the minimum number of steps needed is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0111"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the black balls are already grouped to the right.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
Greedy; Two Pointers; String
|
Java
|
class Solution {
public long minimumSteps(String s) {
long ans = 0;
int cnt = 0;
int n = s.length();
for (int i = n - 1; i >= 0; --i) {
if (s.charAt(i) == '1') {
++cnt;
ans += n - i - cnt;
}
}
return ans;
}
}
|
2,938
|
Separate Black and White Balls
|
Medium
|
<p>There are <code>n</code> balls on a table, each ball has a color black or white.</p>
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code>, where <code>1</code> and <code>0</code> represent black and white balls, respectively.</p>
<p>In each step, you can choose two adjacent balls and swap them.</p>
<p>Return <em>the <strong>minimum</strong> number of steps to group all the black balls to the right and all the white balls to the left</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "101"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "011".
Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "100"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "010".
- Swap s[1] and s[2], s = "001".
It can be proven that the minimum number of steps needed is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0111"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the black balls are already grouped to the right.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
Greedy; Two Pointers; String
|
Python
|
class Solution:
def minimumSteps(self, s: str) -> int:
n = len(s)
ans = cnt = 0
for i in range(n - 1, -1, -1):
if s[i] == '1':
cnt += 1
ans += n - i - cnt
return ans
|
2,938
|
Separate Black and White Balls
|
Medium
|
<p>There are <code>n</code> balls on a table, each ball has a color black or white.</p>
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> of length <code>n</code>, where <code>1</code> and <code>0</code> represent black and white balls, respectively.</p>
<p>In each step, you can choose two adjacent balls and swap them.</p>
<p>Return <em>the <strong>minimum</strong> number of steps to group all the black balls to the right and all the white balls to the left</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "101"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "011".
Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "100"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can group all the black balls to the right in the following way:
- Swap s[0] and s[1], s = "010".
- Swap s[1] and s[2], s = "001".
It can be proven that the minimum number of steps needed is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0111"
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the black balls are already grouped to the right.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
Greedy; Two Pointers; String
|
TypeScript
|
function minimumSteps(s: string): number {
const n = s.length;
let [ans, cnt] = [0, 0];
for (let i = n - 1; ~i; --i) {
if (s[i] === '1') {
++cnt;
ans += n - i - cnt;
}
}
return ans;
}
|
2,939
|
Maximum Xor Product
|
Medium
|
<p>Given three integers <code>a</code>, <code>b</code>, and <code>n</code>, return <em>the <strong>maximum value</strong> of</em> <code>(a XOR x) * (b XOR x)</code> <em>where</em> <code>0 <= x < 2<sup>n</sup></code>.</p>
<p>Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p>
<p><strong>Note</strong> that <code>XOR</code> is the bitwise XOR operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 12, b = 5, n = 4
<strong>Output:</strong> 98
<strong>Explanation:</strong> For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup><span style="font-size: 10.8333px;">.</span>
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 6, b = 7 , n = 5
<strong>Output:</strong> 930
<strong>Explanation:</strong> For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 6, n = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong> For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= a, b < 2<sup>50</sup></code></li>
<li><code>0 <= n <= 50</code></li>
</ul>
|
Greedy; Bit Manipulation; Math
|
C++
|
class Solution {
public:
int maximumXorProduct(long long a, long long b, int n) {
const int mod = 1e9 + 7;
long long ax = (a >> n) << n, bx = (b >> n) << n;
for (int i = n - 1; ~i; --i) {
int x = a >> i & 1, y = b >> i & 1;
if (x == y) {
ax |= 1LL << i;
bx |= 1LL << i;
} else if (ax < bx) {
ax |= 1LL << i;
} else {
bx |= 1LL << i;
}
}
ax %= mod;
bx %= mod;
return ax * bx % mod;
}
};
|
2,939
|
Maximum Xor Product
|
Medium
|
<p>Given three integers <code>a</code>, <code>b</code>, and <code>n</code>, return <em>the <strong>maximum value</strong> of</em> <code>(a XOR x) * (b XOR x)</code> <em>where</em> <code>0 <= x < 2<sup>n</sup></code>.</p>
<p>Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p>
<p><strong>Note</strong> that <code>XOR</code> is the bitwise XOR operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 12, b = 5, n = 4
<strong>Output:</strong> 98
<strong>Explanation:</strong> For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup><span style="font-size: 10.8333px;">.</span>
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 6, b = 7 , n = 5
<strong>Output:</strong> 930
<strong>Explanation:</strong> For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 6, n = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong> For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= a, b < 2<sup>50</sup></code></li>
<li><code>0 <= n <= 50</code></li>
</ul>
|
Greedy; Bit Manipulation; Math
|
Go
|
func maximumXorProduct(a int64, b int64, n int) int {
const mod int64 = 1e9 + 7
ax := (a >> n) << n
bx := (b >> n) << n
for i := n - 1; i >= 0; i-- {
x, y := (a>>i)&1, (b>>i)&1
if x == y {
ax |= 1 << i
bx |= 1 << i
} else if ax < bx {
ax |= 1 << i
} else {
bx |= 1 << i
}
}
ax %= mod
bx %= mod
return int(ax * bx % mod)
}
|
2,939
|
Maximum Xor Product
|
Medium
|
<p>Given three integers <code>a</code>, <code>b</code>, and <code>n</code>, return <em>the <strong>maximum value</strong> of</em> <code>(a XOR x) * (b XOR x)</code> <em>where</em> <code>0 <= x < 2<sup>n</sup></code>.</p>
<p>Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p>
<p><strong>Note</strong> that <code>XOR</code> is the bitwise XOR operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 12, b = 5, n = 4
<strong>Output:</strong> 98
<strong>Explanation:</strong> For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup><span style="font-size: 10.8333px;">.</span>
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 6, b = 7 , n = 5
<strong>Output:</strong> 930
<strong>Explanation:</strong> For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 6, n = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong> For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= a, b < 2<sup>50</sup></code></li>
<li><code>0 <= n <= 50</code></li>
</ul>
|
Greedy; Bit Manipulation; Math
|
Java
|
class Solution {
public int maximumXorProduct(long a, long b, int n) {
final int mod = (int) 1e9 + 7;
long ax = (a >> n) << n;
long bx = (b >> n) << n;
for (int i = n - 1; i >= 0; --i) {
long x = a >> i & 1;
long y = b >> i & 1;
if (x == y) {
ax |= 1L << i;
bx |= 1L << i;
} else if (ax < bx) {
ax |= 1L << i;
} else {
bx |= 1L << i;
}
}
ax %= mod;
bx %= mod;
return (int) (ax * bx % mod);
}
}
|
2,939
|
Maximum Xor Product
|
Medium
|
<p>Given three integers <code>a</code>, <code>b</code>, and <code>n</code>, return <em>the <strong>maximum value</strong> of</em> <code>(a XOR x) * (b XOR x)</code> <em>where</em> <code>0 <= x < 2<sup>n</sup></code>.</p>
<p>Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p>
<p><strong>Note</strong> that <code>XOR</code> is the bitwise XOR operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 12, b = 5, n = 4
<strong>Output:</strong> 98
<strong>Explanation:</strong> For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup><span style="font-size: 10.8333px;">.</span>
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 6, b = 7 , n = 5
<strong>Output:</strong> 930
<strong>Explanation:</strong> For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 6, n = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong> For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= a, b < 2<sup>50</sup></code></li>
<li><code>0 <= n <= 50</code></li>
</ul>
|
Greedy; Bit Manipulation; Math
|
Python
|
class Solution:
def maximumXorProduct(self, a: int, b: int, n: int) -> int:
mod = 10**9 + 7
ax, bx = (a >> n) << n, (b >> n) << n
for i in range(n - 1, -1, -1):
x = a >> i & 1
y = b >> i & 1
if x == y:
ax |= 1 << i
bx |= 1 << i
elif ax > bx:
bx |= 1 << i
else:
ax |= 1 << i
return ax * bx % mod
|
2,939
|
Maximum Xor Product
|
Medium
|
<p>Given three integers <code>a</code>, <code>b</code>, and <code>n</code>, return <em>the <strong>maximum value</strong> of</em> <code>(a XOR x) * (b XOR x)</code> <em>where</em> <code>0 <= x < 2<sup>n</sup></code>.</p>
<p>Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p>
<p><strong>Note</strong> that <code>XOR</code> is the bitwise XOR operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 12, b = 5, n = 4
<strong>Output:</strong> 98
<strong>Explanation:</strong> For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup><span style="font-size: 10.8333px;">.</span>
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 6, b = 7 , n = 5
<strong>Output:</strong> 930
<strong>Explanation:</strong> For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 6, n = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong> For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2<sup>n</sup>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= a, b < 2<sup>50</sup></code></li>
<li><code>0 <= n <= 50</code></li>
</ul>
|
Greedy; Bit Manipulation; Math
|
TypeScript
|
function maximumXorProduct(a: number, b: number, n: number): number {
const mod = BigInt(1e9 + 7);
let ax = (BigInt(a) >> BigInt(n)) << BigInt(n);
let bx = (BigInt(b) >> BigInt(n)) << BigInt(n);
for (let i = BigInt(n - 1); ~i; --i) {
const x = (BigInt(a) >> i) & 1n;
const y = (BigInt(b) >> i) & 1n;
if (x === y) {
ax |= 1n << i;
bx |= 1n << i;
} else if (ax < bx) {
ax |= 1n << i;
} else {
bx |= 1n << i;
}
}
ax %= mod;
bx %= mod;
return Number((ax * bx) % mod);
}
|
2,940
|
Find Building Where Alice and Bob Can Meet
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>heights</code> of positive integers, where <code>heights[i]</code> represents the height of the <code>i<sup>th</sup></code> building.</p>
<p>If a person is in building <code>i</code>, they can move to any other building <code>j</code> if and only if <code>i < j</code> and <code>heights[i] < heights[j]</code>.</p>
<p>You are also given another array <code>queries</code> where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. On the <code>i<sup>th</sup></code> query, Alice is in building <code>a<sub>i</sub></code> while Bob is in building <code>b<sub>i</sub></code>.</p>
<p>Return <em>an array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is <strong>the index of the leftmost building</strong> where Alice and Bob can meet on the</em> <code>i<sup>th</sup></code> <em>query</em>. <em>If Alice and Bob cannot move to a common building on query</em> <code>i</code>, <em>set</em> <code>ans[i]</code> <em>to</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
<strong>Output:</strong> [2,5,-1,5,2]
<strong>Explanation:</strong> In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2].
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5].
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
<strong>Output:</strong> [7,6,-1,4,6]
<strong>Explanation:</strong> In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= heights.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= heights[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= heights.length - 1</code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Monotonic Stack; Heap (Priority Queue)
|
C++
|
class BinaryIndexedTree {
private:
int inf = 1 << 30;
int n;
vector<int> c;
public:
BinaryIndexedTree(int n) {
this->n = n;
c.resize(n + 1, inf);
}
void update(int x, int v) {
while (x <= n) {
c[x] = min(c[x], v);
x += x & -x;
}
}
int query(int x) {
int mi = inf;
while (x > 0) {
mi = min(mi, c[x]);
x -= x & -x;
}
return mi == inf ? -1 : mi;
}
};
class Solution {
public:
vector<int> leftmostBuildingQueries(vector<int>& heights, vector<vector<int>>& queries) {
int n = heights.size(), m = queries.size();
for (auto& q : queries) {
if (q[0] > q[1]) {
swap(q[0], q[1]);
}
}
vector<int> idx(m);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) {
return queries[j][1] < queries[i][1];
});
vector<int> s = heights;
sort(s.begin(), s.end());
s.erase(unique(s.begin(), s.end()), s.end());
vector<int> ans(m);
int j = n - 1;
BinaryIndexedTree tree(n);
for (int i : idx) {
int l = queries[i][0], r = queries[i][1];
while (j > r) {
int k = s.end() - lower_bound(s.begin(), s.end(), heights[j]) + 1;
tree.update(k, j);
--j;
}
if (l == r || heights[l] < heights[r]) {
ans[i] = r;
} else {
int k = s.end() - lower_bound(s.begin(), s.end(), heights[l]);
ans[i] = tree.query(k);
}
}
return ans;
}
};
|
2,940
|
Find Building Where Alice and Bob Can Meet
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>heights</code> of positive integers, where <code>heights[i]</code> represents the height of the <code>i<sup>th</sup></code> building.</p>
<p>If a person is in building <code>i</code>, they can move to any other building <code>j</code> if and only if <code>i < j</code> and <code>heights[i] < heights[j]</code>.</p>
<p>You are also given another array <code>queries</code> where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. On the <code>i<sup>th</sup></code> query, Alice is in building <code>a<sub>i</sub></code> while Bob is in building <code>b<sub>i</sub></code>.</p>
<p>Return <em>an array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is <strong>the index of the leftmost building</strong> where Alice and Bob can meet on the</em> <code>i<sup>th</sup></code> <em>query</em>. <em>If Alice and Bob cannot move to a common building on query</em> <code>i</code>, <em>set</em> <code>ans[i]</code> <em>to</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
<strong>Output:</strong> [2,5,-1,5,2]
<strong>Explanation:</strong> In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2].
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5].
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
<strong>Output:</strong> [7,6,-1,4,6]
<strong>Explanation:</strong> In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= heights.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= heights[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= heights.length - 1</code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Monotonic Stack; Heap (Priority Queue)
|
Go
|
const inf int = 1 << 30
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
c := make([]int, n+1)
for i := range c {
c[i] = inf
}
return BinaryIndexedTree{n: n, c: c}
}
func (bit *BinaryIndexedTree) update(x, v int) {
for x <= bit.n {
bit.c[x] = min(bit.c[x], v)
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) int {
mi := inf
for x > 0 {
mi = min(mi, bit.c[x])
x -= x & -x
}
if mi == inf {
return -1
}
return mi
}
func leftmostBuildingQueries(heights []int, queries [][]int) []int {
n, m := len(heights), len(queries)
for _, q := range queries {
if q[0] > q[1] {
q[0], q[1] = q[1], q[0]
}
}
idx := make([]int, m)
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(i, j int) bool { return queries[idx[j]][1] < queries[idx[i]][1] })
s := make([]int, n)
copy(s, heights)
sort.Ints(s)
ans := make([]int, m)
tree := NewBinaryIndexedTree(n)
j := n - 1
for _, i := range idx {
l, r := queries[i][0], queries[i][1]
for ; j > r; j-- {
k := n - sort.SearchInts(s, heights[j]) + 1
tree.update(k, j)
}
if l == r || heights[l] < heights[r] {
ans[i] = r
} else {
k := n - sort.SearchInts(s, heights[l])
ans[i] = tree.query(k)
}
}
return ans
}
|
2,940
|
Find Building Where Alice and Bob Can Meet
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>heights</code> of positive integers, where <code>heights[i]</code> represents the height of the <code>i<sup>th</sup></code> building.</p>
<p>If a person is in building <code>i</code>, they can move to any other building <code>j</code> if and only if <code>i < j</code> and <code>heights[i] < heights[j]</code>.</p>
<p>You are also given another array <code>queries</code> where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. On the <code>i<sup>th</sup></code> query, Alice is in building <code>a<sub>i</sub></code> while Bob is in building <code>b<sub>i</sub></code>.</p>
<p>Return <em>an array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is <strong>the index of the leftmost building</strong> where Alice and Bob can meet on the</em> <code>i<sup>th</sup></code> <em>query</em>. <em>If Alice and Bob cannot move to a common building on query</em> <code>i</code>, <em>set</em> <code>ans[i]</code> <em>to</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
<strong>Output:</strong> [2,5,-1,5,2]
<strong>Explanation:</strong> In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2].
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5].
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
<strong>Output:</strong> [7,6,-1,4,6]
<strong>Explanation:</strong> In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= heights.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= heights[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= heights.length - 1</code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Monotonic Stack; Heap (Priority Queue)
|
Java
|
class BinaryIndexedTree {
private final int inf = 1 << 30;
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
Arrays.fill(c, inf);
}
public void update(int x, int v) {
while (x <= n) {
c[x] = Math.min(c[x], v);
x += x & -x;
}
}
public int query(int x) {
int mi = inf;
while (x > 0) {
mi = Math.min(mi, c[x]);
x -= x & -x;
}
return mi == inf ? -1 : mi;
}
}
class Solution {
public int[] leftmostBuildingQueries(int[] heights, int[][] queries) {
int n = heights.length;
int m = queries.length;
for (int i = 0; i < m; ++i) {
if (queries[i][0] > queries[i][1]) {
queries[i] = new int[] {queries[i][1], queries[i][0]};
}
}
Integer[] idx = new Integer[m];
for (int i = 0; i < m; ++i) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> queries[j][1] - queries[i][1]);
int[] s = heights.clone();
Arrays.sort(s);
int[] ans = new int[m];
int j = n - 1;
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int i : idx) {
int l = queries[i][0], r = queries[i][1];
while (j > r) {
int k = n - Arrays.binarySearch(s, heights[j]) + 1;
tree.update(k, j);
--j;
}
if (l == r || heights[l] < heights[r]) {
ans[i] = r;
} else {
int k = n - Arrays.binarySearch(s, heights[l]);
ans[i] = tree.query(k);
}
}
return ans;
}
}
|
2,940
|
Find Building Where Alice and Bob Can Meet
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>heights</code> of positive integers, where <code>heights[i]</code> represents the height of the <code>i<sup>th</sup></code> building.</p>
<p>If a person is in building <code>i</code>, they can move to any other building <code>j</code> if and only if <code>i < j</code> and <code>heights[i] < heights[j]</code>.</p>
<p>You are also given another array <code>queries</code> where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. On the <code>i<sup>th</sup></code> query, Alice is in building <code>a<sub>i</sub></code> while Bob is in building <code>b<sub>i</sub></code>.</p>
<p>Return <em>an array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is <strong>the index of the leftmost building</strong> where Alice and Bob can meet on the</em> <code>i<sup>th</sup></code> <em>query</em>. <em>If Alice and Bob cannot move to a common building on query</em> <code>i</code>, <em>set</em> <code>ans[i]</code> <em>to</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
<strong>Output:</strong> [2,5,-1,5,2]
<strong>Explanation:</strong> In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2].
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5].
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
<strong>Output:</strong> [7,6,-1,4,6]
<strong>Explanation:</strong> In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= heights.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= heights[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= heights.length - 1</code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Monotonic Stack; Heap (Priority Queue)
|
Python
|
class BinaryIndexedTree:
__slots__ = ["n", "c"]
def __init__(self, n: int):
self.n = n
self.c = [inf] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = min(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mi = inf
while x:
mi = min(mi, self.c[x])
x -= x & -x
return -1 if mi == inf else mi
class Solution:
def leftmostBuildingQueries(
self, heights: List[int], queries: List[List[int]]
) -> List[int]:
n, m = len(heights), len(queries)
for i in range(m):
queries[i] = [min(queries[i]), max(queries[i])]
j = n - 1
s = sorted(set(heights))
ans = [-1] * m
tree = BinaryIndexedTree(n)
for i in sorted(range(m), key=lambda i: -queries[i][1]):
l, r = queries[i]
while j > r:
k = n - bisect_left(s, heights[j]) + 1
tree.update(k, j)
j -= 1
if l == r or heights[l] < heights[r]:
ans[i] = r
else:
k = n - bisect_left(s, heights[l])
ans[i] = tree.query(k)
return ans
|
2,940
|
Find Building Where Alice and Bob Can Meet
|
Hard
|
<p>You are given a <strong>0-indexed</strong> array <code>heights</code> of positive integers, where <code>heights[i]</code> represents the height of the <code>i<sup>th</sup></code> building.</p>
<p>If a person is in building <code>i</code>, they can move to any other building <code>j</code> if and only if <code>i < j</code> and <code>heights[i] < heights[j]</code>.</p>
<p>You are also given another array <code>queries</code> where <code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>. On the <code>i<sup>th</sup></code> query, Alice is in building <code>a<sub>i</sub></code> while Bob is in building <code>b<sub>i</sub></code>.</p>
<p>Return <em>an array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is <strong>the index of the leftmost building</strong> where Alice and Bob can meet on the</em> <code>i<sup>th</sup></code> <em>query</em>. <em>If Alice and Bob cannot move to a common building on query</em> <code>i</code>, <em>set</em> <code>ans[i]</code> <em>to</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
<strong>Output:</strong> [2,5,-1,5,2]
<strong>Explanation:</strong> In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2].
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5].
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
<strong>Output:</strong> [7,6,-1,4,6]
<strong>Explanation:</strong> In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= heights.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= heights[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 5 * 10<sup>4</sup></code></li>
<li><code>queries[i] = [a<sub>i</sub>, b<sub>i</sub>]</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= heights.length - 1</code></li>
</ul>
|
Stack; Binary Indexed Tree; Segment Tree; Array; Binary Search; Monotonic Stack; Heap (Priority Queue)
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
private inf: number = 1 << 30;
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(this.inf);
}
update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] = Math.min(this.c[x], v);
x += x & -x;
}
}
query(x: number): number {
let mi = this.inf;
while (x > 0) {
mi = Math.min(mi, this.c[x]);
x -= x & -x;
}
return mi === this.inf ? -1 : mi;
}
}
function leftmostBuildingQueries(heights: number[], queries: number[][]): number[] {
const n = heights.length;
const m = queries.length;
for (const q of queries) {
if (q[0] > q[1]) {
[q[0], q[1]] = [q[1], q[0]];
}
}
const idx: number[] = Array(m)
.fill(0)
.map((_, i) => i);
idx.sort((i, j) => queries[j][1] - queries[i][1]);
const tree = new BinaryIndexedTree(n);
const ans: number[] = Array(m).fill(-1);
const s = [...heights];
s.sort((a, b) => a - b);
const search = (x: number) => {
let [l, r] = [0, n];
while (l < r) {
const mid = (l + r) >> 1;
if (s[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
let j = n - 1;
for (const i of idx) {
const [l, r] = queries[i];
while (j > r) {
const k = n - search(heights[j]) + 1;
tree.update(k, j);
--j;
}
if (l === r || heights[l] < heights[r]) {
ans[i] = r;
} else {
const k = n - search(heights[l]);
ans[i] = tree.query(k);
}
}
return ans;
}
|
2,941
|
Maximum GCD-Sum of a Subarray
|
Hard
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>
<ul>
<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>
<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Math; Binary Search; Number Theory
|
C++
|
class Solution {
public:
long long maxGcdSum(vector<int>& nums, int k) {
int n = nums.size();
long long s[n + 1];
s[0] = 0;
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums[i - 1];
}
vector<pair<int, int>> f;
long long ans = 0;
for (int i = 0; i < n; ++i) {
vector<pair<int, int>> g;
for (auto [j, x] : f) {
int y = gcd(x, nums[i]);
if (g.empt() || g.back().second != y) {
g.emplace_back(j, y);
}
}
f = move(g);
f.emplace_back(i, nums[i]);
for (auto [j, x] : f) {
if (i - j + 1 >= k) {
ans = max(ans, (s[i + 1] - s[j]) * x);
}
}
}
return ans;
}
};
|
2,941
|
Maximum GCD-Sum of a Subarray
|
Hard
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>
<ul>
<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>
<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Math; Binary Search; Number Theory
|
Go
|
func maxGcdSum(nums []int, k int) int64 {
n := len(nums)
s := make([]int64, n+1)
s[0] = 0
for i, x := range nums {
s[i+1] = s[i] + int64(x)
}
type pair [2]int
var f []pair
var ans int64
for i := 0; i < n; i++ {
var g []pair
for _, p := range f {
j, x := p[0], p[1]
y := int(gcd(int(x), nums[i]))
if len(g) == 0 || g[len(g)-1][1] != y {
g = append(g, pair{j, y})
}
}
f = g
f = append(f, pair{i, nums[i]})
for _, p := range f {
j, x := p[0], p[1]
if i-j+1 >= k {
ans = max(ans, (s[i+1]-s[j])*int64(x))
}
}
}
return ans
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
2,941
|
Maximum GCD-Sum of a Subarray
|
Hard
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>
<ul>
<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>
<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Math; Binary Search; Number Theory
|
Java
|
class Solution {
public long maxGcdSum(int[] nums, int k) {
int n = nums.length;
long[] s = new long[n + 1];
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums[i - 1];
}
List<int[]> f = new ArrayList<>();
long ans = 0;
for (int i = 0; i < n; ++i) {
List<int[]> g = new ArrayList<>();
for (var e : f) {
int j = e[0], x = e[1];
int y = gcd(x, nums[i]);
if (g.isEmpty() || g.get(g.size() - 1)[1] != y) {
g.add(new int[] {j, y});
}
}
f = g;
f.add(new int[] {i, nums[i]});
for (var e : f) {
int j = e[0], x = e[1];
if (i - j + 1 >= k) {
ans = Math.max(ans, (s[i + 1] - s[j]) * x);
}
}
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
2,941
|
Maximum GCD-Sum of a Subarray
|
Hard
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>
<ul>
<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>
<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Math; Binary Search; Number Theory
|
Python
|
class Solution:
def maxGcdSum(self, nums: List[int], k: int) -> int:
s = list(accumulate(nums, initial=0))
f = []
ans = 0
for i, v in enumerate(nums):
g = []
for j, x in f:
y = gcd(x, v)
if not g or g[-1][1] != y:
g.append((j, y))
f = g
f.append((i, v))
for j, x in f:
if i - j + 1 >= k:
ans = max(ans, (s[i + 1] - s[j]) * x)
return ans
|
2,941
|
Maximum GCD-Sum of a Subarray
|
Hard
|
<p>You are given an array of integers <code>nums</code> and an integer <code>k</code>.</p>
<p>The <strong>gcd-sum</strong> of an array <code>a</code> is calculated as follows:</p>
<ul>
<li>Let <code>s</code> be the sum of all the elements of <code>a</code>.</li>
<li>Let <code>g</code> be the <strong>greatest common divisor</strong> of all the elements of <code>a</code>.</li>
<li>The gcd-sum of <code>a</code> is equal to <code>s * g</code>.</li>
</ul>
<p>Return <em>the <strong>maximum gcd-sum</strong> of a subarray of</em> <code>nums</code> <em>with at least</em> <code>k</code> <em>elements.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,4,4,4,2], k = 2
<strong>Output:</strong> 48
<strong>Explanation:</strong> We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,9,4], k = 1
<strong>Output:</strong> 81
<strong>Explanation:</strong> We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Math; Binary Search; Number Theory
|
TypeScript
|
function maxGcdSum(nums: number[], k: number): number {
const n: number = nums.length;
const s: number[] = Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
s[i] = s[i - 1] + nums[i - 1];
}
let f: [number, number][] = [];
let ans: number = 0;
for (let i = 0; i < n; ++i) {
const g: [number, number][] = [];
for (const [j, x] of f) {
const y: number = gcd(x, nums[i]);
if (g.length === 0 || g.at(-1)[1] !== y) {
g.push([j, y]);
}
}
f = g;
f.push([i, nums[i]]);
for (const [j, x] of f) {
if (i - j + 1 >= k) {
ans = Math.max(ans, (s[i + 1] - s[j]) * x);
}
}
}
return ans;
}
function gcd(a: number, b: number): number {
return b === 0 ? a : gcd(b, a % b);
}
|
2,942
|
Find Words Containing Character
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p>
<p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p>
<p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["leet","code"], x = "e"
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> "e" occurs in both words: "l<strong><u>ee</u></strong>t", and "cod<u><strong>e</strong></u>". Hence, we return indices 0 and 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "a"
<strong>Output:</strong> [0,2]
<strong>Explanation:</strong> "a" occurs in "<strong><u>a</u></strong>bc", and "<u><strong>aaaa</strong></u>". Hence, we return indices 0 and 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "z"
<strong>Output:</strong> []
<strong>Explanation:</strong> "z" does not occur in any of the words. Hence, we return an empty array.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li><code>x</code> is a lowercase English letter.</li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Array; String
|
C++
|
class Solution {
public:
vector<int> findWordsContaining(vector<string>& words, char x) {
vector<int> ans;
for (int i = 0; i < words.size(); ++i) {
if (words[i].find(x) != string::npos) {
ans.push_back(i);
}
}
return ans;
}
};
|
2,942
|
Find Words Containing Character
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p>
<p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p>
<p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["leet","code"], x = "e"
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> "e" occurs in both words: "l<strong><u>ee</u></strong>t", and "cod<u><strong>e</strong></u>". Hence, we return indices 0 and 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "a"
<strong>Output:</strong> [0,2]
<strong>Explanation:</strong> "a" occurs in "<strong><u>a</u></strong>bc", and "<u><strong>aaaa</strong></u>". Hence, we return indices 0 and 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "z"
<strong>Output:</strong> []
<strong>Explanation:</strong> "z" does not occur in any of the words. Hence, we return an empty array.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li><code>x</code> is a lowercase English letter.</li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Array; String
|
Go
|
func findWordsContaining(words []string, x byte) (ans []int) {
for i, w := range words {
for _, c := range w {
if byte(c) == x {
ans = append(ans, i)
break
}
}
}
return
}
|
2,942
|
Find Words Containing Character
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p>
<p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p>
<p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["leet","code"], x = "e"
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> "e" occurs in both words: "l<strong><u>ee</u></strong>t", and "cod<u><strong>e</strong></u>". Hence, we return indices 0 and 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "a"
<strong>Output:</strong> [0,2]
<strong>Explanation:</strong> "a" occurs in "<strong><u>a</u></strong>bc", and "<u><strong>aaaa</strong></u>". Hence, we return indices 0 and 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "z"
<strong>Output:</strong> []
<strong>Explanation:</strong> "z" does not occur in any of the words. Hence, we return an empty array.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li><code>x</code> is a lowercase English letter.</li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Array; String
|
Java
|
class Solution {
public List<Integer> findWordsContaining(String[] words, char x) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < words.length; ++i) {
if (words[i].indexOf(x) != -1) {
ans.add(i);
}
}
return ans;
}
}
|
2,942
|
Find Words Containing Character
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p>
<p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p>
<p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["leet","code"], x = "e"
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> "e" occurs in both words: "l<strong><u>ee</u></strong>t", and "cod<u><strong>e</strong></u>". Hence, we return indices 0 and 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "a"
<strong>Output:</strong> [0,2]
<strong>Explanation:</strong> "a" occurs in "<strong><u>a</u></strong>bc", and "<u><strong>aaaa</strong></u>". Hence, we return indices 0 and 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "z"
<strong>Output:</strong> []
<strong>Explanation:</strong> "z" does not occur in any of the words. Hence, we return an empty array.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li><code>x</code> is a lowercase English letter.</li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Array; String
|
Python
|
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
return [i for i, w in enumerate(words) if x in w]
|
2,942
|
Find Words Containing Character
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p>
<p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p>
<p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["leet","code"], x = "e"
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> "e" occurs in both words: "l<strong><u>ee</u></strong>t", and "cod<u><strong>e</strong></u>". Hence, we return indices 0 and 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "a"
<strong>Output:</strong> [0,2]
<strong>Explanation:</strong> "a" occurs in "<strong><u>a</u></strong>bc", and "<u><strong>aaaa</strong></u>". Hence, we return indices 0 and 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","bcd","aaaa","cbc"], x = "z"
<strong>Output:</strong> []
<strong>Explanation:</strong> "z" does not occur in any of the words. Hence, we return an empty array.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 50</code></li>
<li><code>1 <= words[i].length <= 50</code></li>
<li><code>x</code> is a lowercase English letter.</li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Array; String
|
Rust
|
impl Solution {
pub fn find_words_containing(words: Vec<String>, x: char) -> Vec<i32> {
words
.into_iter()
.enumerate()
.filter_map(|(i, w)| w.contains(x).then(|| i as i32))
.collect()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.