id
int64 1
3.63k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,492 |
Maximum Containers on a Ship
|
Easy
|
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p>
<p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship's maximum weight capacity, <code>maxWeight</code>.</p>
<p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation: </strong></p>
<p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation: </strong></p>
<p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>1 <= w <= 1000</code></li>
<li><code>1 <= maxWeight <= 10<sup>9</sup></code></li>
</ul>
|
Math
|
Go
|
func maxContainers(n int, w int, maxWeight int) int {
return min(n*n*w, maxWeight) / w
}
|
3,492 |
Maximum Containers on a Ship
|
Easy
|
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p>
<p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship's maximum weight capacity, <code>maxWeight</code>.</p>
<p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation: </strong></p>
<p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation: </strong></p>
<p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>1 <= w <= 1000</code></li>
<li><code>1 <= maxWeight <= 10<sup>9</sup></code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int maxContainers(int n, int w, int maxWeight) {
return Math.min(n * n * w, maxWeight) / w;
}
}
|
3,492 |
Maximum Containers on a Ship
|
Easy
|
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p>
<p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship's maximum weight capacity, <code>maxWeight</code>.</p>
<p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation: </strong></p>
<p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation: </strong></p>
<p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>1 <= w <= 1000</code></li>
<li><code>1 <= maxWeight <= 10<sup>9</sup></code></li>
</ul>
|
Math
|
Python
|
class Solution:
def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
return min(n * n * w, maxWeight) // w
|
3,492 |
Maximum Containers on a Ship
|
Easy
|
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p>
<p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship's maximum weight capacity, <code>maxWeight</code>.</p>
<p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation: </strong></p>
<p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation: </strong></p>
<p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
<li><code>1 <= w <= 1000</code></li>
<li><code>1 <= maxWeight <= 10<sup>9</sup></code></li>
</ul>
|
Math
|
TypeScript
|
function maxContainers(n: number, w: number, maxWeight: number): number {
return (Math.min(n * n * w, maxWeight) / w) | 0;
}
|
3,493 |
Properties Graph
|
Medium
|
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p>
<p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p>
<p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) >= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p>
<p>Return the number of <strong>connected components</strong> in the resulting graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 3 connected components:</p>
<p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 1 connected component:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == properties.length <= 100</code></li>
<li><code>1 <= m == properties[i].length <= 100</code></li>
<li><code>1 <= properties[i][j] <= 100</code></li>
<li><code>1 <= k <= m</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
|
C++
|
class Solution {
public:
int numberOfComponents(vector<vector<int>>& properties, int k) {
int n = properties.size();
unordered_set<int> ss[n];
vector<int> g[n];
for (int i = 0; i < n; ++i) {
for (int x : properties[i]) {
ss[i].insert(x);
}
}
for (int i = 0; i < n; ++i) {
auto& s1 = ss[i];
for (int j = 0; j < i; ++j) {
auto& s2 = ss[j];
int cnt = 0;
for (int x : s1) {
if (s2.contains(x)) {
++cnt;
}
}
if (cnt >= k) {
g[i].push_back(j);
g[j].push_back(i);
}
}
}
int ans = 0;
vector<bool> vis(n);
auto dfs = [&](this auto&& dfs, int i) -> void {
vis[i] = true;
for (int j : g[i]) {
if (!vis[j]) {
dfs(j);
}
}
};
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
dfs(i);
++ans;
}
}
return ans;
}
};
|
3,493 |
Properties Graph
|
Medium
|
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p>
<p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p>
<p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) >= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p>
<p>Return the number of <strong>connected components</strong> in the resulting graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 3 connected components:</p>
<p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 1 connected component:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == properties.length <= 100</code></li>
<li><code>1 <= m == properties[i].length <= 100</code></li>
<li><code>1 <= properties[i][j] <= 100</code></li>
<li><code>1 <= k <= m</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
|
Go
|
func numberOfComponents(properties [][]int, k int) (ans int) {
n := len(properties)
ss := make([]map[int]struct{}, n)
g := make([][]int, n)
for i := 0; i < n; i++ {
ss[i] = make(map[int]struct{})
for _, x := range properties[i] {
ss[i][x] = struct{}{}
}
}
for i := 0; i < n; i++ {
for j := 0; j < i; j++ {
cnt := 0
for x := range ss[i] {
if _, ok := ss[j][x]; ok {
cnt++
}
}
if cnt >= k {
g[i] = append(g[i], j)
g[j] = append(g[j], i)
}
}
}
vis := make([]bool, n)
var dfs func(int)
dfs = func(i int) {
vis[i] = true
for _, j := range g[i] {
if !vis[j] {
dfs(j)
}
}
}
for i := 0; i < n; i++ {
if !vis[i] {
dfs(i)
ans++
}
}
return
}
|
3,493 |
Properties Graph
|
Medium
|
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p>
<p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p>
<p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) >= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p>
<p>Return the number of <strong>connected components</strong> in the resulting graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 3 connected components:</p>
<p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 1 connected component:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == properties.length <= 100</code></li>
<li><code>1 <= m == properties[i].length <= 100</code></li>
<li><code>1 <= properties[i][j] <= 100</code></li>
<li><code>1 <= k <= m</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
|
Java
|
class Solution {
private List<Integer>[] g;
private boolean[] vis;
public int numberOfComponents(int[][] properties, int k) {
int n = properties.length;
g = new List[n];
Set<Integer>[] ss = new Set[n];
Arrays.setAll(g, i -> new ArrayList<>());
Arrays.setAll(ss, i -> new HashSet<>());
for (int i = 0; i < n; ++i) {
for (int x : properties[i]) {
ss[i].add(x);
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
int cnt = 0;
for (int x : ss[i]) {
if (ss[j].contains(x)) {
++cnt;
}
}
if (cnt >= k) {
g[i].add(j);
g[j].add(i);
}
}
}
int ans = 0;
vis = new boolean[n];
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
dfs(i);
++ans;
}
}
return ans;
}
private void dfs(int i) {
vis[i] = true;
for (int j : g[i]) {
if (!vis[j]) {
dfs(j);
}
}
}
}
|
3,493 |
Properties Graph
|
Medium
|
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p>
<p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p>
<p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) >= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p>
<p>Return the number of <strong>connected components</strong> in the resulting graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 3 connected components:</p>
<p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 1 connected component:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == properties.length <= 100</code></li>
<li><code>1 <= m == properties[i].length <= 100</code></li>
<li><code>1 <= properties[i][j] <= 100</code></li>
<li><code>1 <= k <= m</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
|
Python
|
class Solution:
def numberOfComponents(self, properties: List[List[int]], k: int) -> int:
def dfs(i: int) -> None:
vis[i] = True
for j in g[i]:
if not vis[j]:
dfs(j)
n = len(properties)
ss = list(map(set, properties))
g = [[] for _ in range(n)]
for i, s1 in enumerate(ss):
for j in range(i):
s2 = ss[j]
if len(s1 & s2) >= k:
g[i].append(j)
g[j].append(i)
ans = 0
vis = [False] * n
for i in range(n):
if not vis[i]:
dfs(i)
ans += 1
return ans
|
3,493 |
Properties Graph
|
Medium
|
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p>
<p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p>
<p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) >= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p>
<p>Return the number of <strong>connected components</strong> in the resulting graph.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 3 connected components:</p>
<p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The graph formed has 1 connected component:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == properties.length <= 100</code></li>
<li><code>1 <= m == properties[i].length <= 100</code></li>
<li><code>1 <= properties[i][j] <= 100</code></li>
<li><code>1 <= k <= m</code></li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
|
TypeScript
|
function numberOfComponents(properties: number[][], k: number): number {
const n = properties.length;
const ss: Set<number>[] = Array.from({ length: n }, () => new Set());
const g: number[][] = Array.from({ length: n }, () => []);
for (let i = 0; i < n; i++) {
for (const x of properties[i]) {
ss[i].add(x);
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
let cnt = 0;
for (const x of ss[i]) {
if (ss[j].has(x)) {
cnt++;
}
}
if (cnt >= k) {
g[i].push(j);
g[j].push(i);
}
}
}
let ans = 0;
const vis: boolean[] = Array(n).fill(false);
const dfs = (i: number) => {
vis[i] = true;
for (const j of g[i]) {
if (!vis[j]) {
dfs(j);
}
}
};
for (let i = 0; i < n; i++) {
if (!vis[i]) {
dfs(i);
ans++;
}
}
return ans;
}
|
3,496 |
Maximize Score After Pair Deletions
|
Medium
|
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p>
<ul>
<li>Remove the first two elements.</li>
<li>Remove the last two elements.</li>
<li>Remove the first and last element.</li>
</ul>
<p>For each operation, add the sum of the removed elements to your total score.</p>
<p>Return the <strong>maximum</strong> possible score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li>
<li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li>
<li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li>
<li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li>
<li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
int maxScore(vector<int>& nums) {
const int inf = 1 << 30;
int n = nums.size();
int s = 0, mi = inf;
int t = inf;
for (int i = 0; i < n; ++i) {
s += nums[i];
mi = min(mi, nums[i]);
if (i + 1 < n) {
t = min(t, nums[i] + nums[i + 1]);
}
}
if (n % 2 == 1) {
return s - mi;
}
return s - t;
}
};
|
3,496 |
Maximize Score After Pair Deletions
|
Medium
|
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p>
<ul>
<li>Remove the first two elements.</li>
<li>Remove the last two elements.</li>
<li>Remove the first and last element.</li>
</ul>
<p>For each operation, add the sum of the removed elements to your total score.</p>
<p>Return the <strong>maximum</strong> possible score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li>
<li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li>
<li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li>
<li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li>
<li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Go
|
func maxScore(nums []int) int {
const inf = 1 << 30
n := len(nums)
s, mi, t := 0, inf, inf
for i, x := range nums {
s += x
mi = min(mi, x)
if i+1 < n {
t = min(t, x+nums[i+1])
}
}
if n%2 == 1 {
return s - mi
}
return s - t
}
|
3,496 |
Maximize Score After Pair Deletions
|
Medium
|
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p>
<ul>
<li>Remove the first two elements.</li>
<li>Remove the last two elements.</li>
<li>Remove the first and last element.</li>
</ul>
<p>For each operation, add the sum of the removed elements to your total score.</p>
<p>Return the <strong>maximum</strong> possible score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li>
<li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li>
<li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li>
<li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li>
<li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public int maxScore(int[] nums) {
final int inf = 1 << 30;
int n = nums.length;
int s = 0, mi = inf;
int t = inf;
for (int i = 0; i < n; ++i) {
s += nums[i];
mi = Math.min(mi, nums[i]);
if (i + 1 < n) {
t = Math.min(t, nums[i] + nums[i + 1]);
}
}
if (n % 2 == 1) {
return s - mi;
}
return s - t;
}
}
|
3,496 |
Maximize Score After Pair Deletions
|
Medium
|
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p>
<ul>
<li>Remove the first two elements.</li>
<li>Remove the last two elements.</li>
<li>Remove the first and last element.</li>
</ul>
<p>For each operation, add the sum of the removed elements to your total score.</p>
<p>Return the <strong>maximum</strong> possible score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li>
<li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li>
<li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li>
<li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li>
<li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def maxScore(self, nums: List[int]) -> int:
s = sum(nums)
if len(nums) & 1:
return s - min(nums)
return s - min(a + b for a, b in pairwise(nums))
|
3,496 |
Maximize Score After Pair Deletions
|
Medium
|
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p>
<ul>
<li>Remove the first two elements.</li>
<li>Remove the last two elements.</li>
<li>Remove the first and last element.</li>
</ul>
<p>For each operation, add the sum of the removed elements to your total score.</p>
<p>Return the <strong>maximum</strong> possible score you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li>
<li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li>
<li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The possible operations are:</p>
<ul>
<li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li>
<li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li>
<li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li>
</ul>
<p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Greedy; Array
|
TypeScript
|
function maxScore(nums: number[]): number {
const inf = Infinity;
const n = nums.length;
let [s, mi, t] = [0, inf, inf];
for (let i = 0; i < n; ++i) {
s += nums[i];
mi = Math.min(mi, nums[i]);
if (i + 1 < n) {
t = Math.min(t, nums[i] + nums[i + 1]);
}
}
return n % 2 ? s - mi : s - t;
}
|
3,497 |
Analyze Subscription Conversion
|
Medium
|
<p>Table: <code>UserActivity</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| user_id | int |
| activity_date | date |
| activity_type | varchar |
| activity_duration| int |
+------------------+---------+
(user_id, activity_date, activity_type) is the unique key for this table.
activity_type is one of ('free_trial', 'paid', 'cancelled').
activity_duration is the number of minutes the user spent on the platform that day.
Each row represents a user's activity on a specific date.
</pre>
<p>A subscription service wants to analyze user behavior patterns. The company offers a <code>7</code>-day <strong>free trial</strong>, after which users can subscribe to a <strong>paid plan</strong> or <strong>cancel</strong>. Write a solution to:</p>
<ol>
<li>Find users who converted from free trial to paid subscription</li>
<li>Calculate each user's <strong>average daily activity duration</strong> during their <strong>free trial</strong> period (rounded to <code>2</code> decimal places)</li>
<li>Calculate each user's <strong>average daily activity duration</strong> during their <strong>paid</strong> subscription period (rounded to <code>2</code> decimal places)</li>
</ol>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>UserActivity table:</p>
<pre class="example-io">
+---------+---------------+---------------+-------------------+
| user_id | activity_date | activity_type | activity_duration |
+---------+---------------+---------------+-------------------+
| 1 | 2023-01-01 | free_trial | 45 |
| 1 | 2023-01-02 | free_trial | 30 |
| 1 | 2023-01-05 | free_trial | 60 |
| 1 | 2023-01-10 | paid | 75 |
| 1 | 2023-01-12 | paid | 90 |
| 1 | 2023-01-15 | paid | 65 |
| 2 | 2023-02-01 | free_trial | 55 |
| 2 | 2023-02-03 | free_trial | 25 |
| 2 | 2023-02-07 | free_trial | 50 |
| 2 | 2023-02-10 | cancelled | 0 |
| 3 | 2023-03-05 | free_trial | 70 |
| 3 | 2023-03-06 | free_trial | 60 |
| 3 | 2023-03-08 | free_trial | 80 |
| 3 | 2023-03-12 | paid | 50 |
| 3 | 2023-03-15 | paid | 55 |
| 3 | 2023-03-20 | paid | 85 |
| 4 | 2023-04-01 | free_trial | 40 |
| 4 | 2023-04-03 | free_trial | 35 |
| 4 | 2023-04-05 | paid | 45 |
| 4 | 2023-04-07 | cancelled | 0 |
+---------+---------------+---------------+-------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------+--------------------+-------------------+
| user_id | trial_avg_duration | paid_avg_duration |
+---------+--------------------+-------------------+
| 1 | 45.00 | 76.67 |
| 3 | 70.00 | 63.33 |
| 4 | 37.50 | 45.00 |
+---------+--------------------+-------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>User 1:</strong>
<ul>
<li>Had 3 days of free trial with durations of 45, 30, and 60 minutes.</li>
<li>Average trial duration: (45 + 30 + 60) / 3 = 45.00 minutes.</li>
<li>Had 3 days of paid subscription with durations of 75, 90, and 65 minutes.</li>
<li>Average paid duration: (75 + 90 + 65) / 3 = 76.67 minutes.</li>
</ul>
</li>
<li><strong>User 2:</strong>
<ul>
<li>Had 3 days of free trial with durations of 55, 25, and 50 minutes.</li>
<li>Average trial duration: (55 + 25 + 50) / 3 = 43.33 minutes.</li>
<li>Did not convert to a paid subscription (only had free_trial and cancelled activities).</li>
<li>Not included in the output because they didn't convert to paid.</li>
</ul>
</li>
<li><strong>User 3:</strong>
<ul>
<li>Had 3 days of free trial with durations of 70, 60, and 80 minutes.</li>
<li>Average trial duration: (70 + 60 + 80) / 3 = 70.00 minutes.</li>
<li>Had 3 days of paid subscription with durations of 50, 55, and 85 minutes.</li>
<li>Average paid duration: (50 + 55 + 85) / 3 = 63.33 minutes.</li>
</ul>
</li>
<li><strong>User 4:</strong>
<ul>
<li>Had 2 days of free trial with durations of 40 and 35 minutes.</li>
<li>Average trial duration: (40 + 35) / 2 = 37.50 minutes.</li>
<li>Had 1 day of paid subscription with duration of 45 minutes before cancelling.</li>
<li>Average paid duration: 45.00 minutes.</li>
</ul>
</li>
</ul>
<p>The result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def analyze_subscription_conversion(user_activity: pd.DataFrame) -> pd.DataFrame:
df = user_activity[user_activity["activity_type"] != "cancelled"]
df_grouped = (
df.groupby(["user_id", "activity_type"])["activity_duration"]
.mean()
.add(0.0001)
.round(2)
.reset_index()
)
df_free_trial = (
df_grouped[df_grouped["activity_type"] == "free_trial"]
.rename(columns={"activity_duration": "trial_avg_duration"})
.drop(columns=["activity_type"])
)
df_paid = (
df_grouped[df_grouped["activity_type"] == "paid"]
.rename(columns={"activity_duration": "paid_avg_duration"})
.drop(columns=["activity_type"])
)
result = df_free_trial.merge(df_paid, on="user_id", how="inner").sort_values(
"user_id"
)
return result
|
3,497 |
Analyze Subscription Conversion
|
Medium
|
<p>Table: <code>UserActivity</code></p>
<pre>
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| user_id | int |
| activity_date | date |
| activity_type | varchar |
| activity_duration| int |
+------------------+---------+
(user_id, activity_date, activity_type) is the unique key for this table.
activity_type is one of ('free_trial', 'paid', 'cancelled').
activity_duration is the number of minutes the user spent on the platform that day.
Each row represents a user's activity on a specific date.
</pre>
<p>A subscription service wants to analyze user behavior patterns. The company offers a <code>7</code>-day <strong>free trial</strong>, after which users can subscribe to a <strong>paid plan</strong> or <strong>cancel</strong>. Write a solution to:</p>
<ol>
<li>Find users who converted from free trial to paid subscription</li>
<li>Calculate each user's <strong>average daily activity duration</strong> during their <strong>free trial</strong> period (rounded to <code>2</code> decimal places)</li>
<li>Calculate each user's <strong>average daily activity duration</strong> during their <strong>paid</strong> subscription period (rounded to <code>2</code> decimal places)</li>
</ol>
<p>Return <em>the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>UserActivity table:</p>
<pre class="example-io">
+---------+---------------+---------------+-------------------+
| user_id | activity_date | activity_type | activity_duration |
+---------+---------------+---------------+-------------------+
| 1 | 2023-01-01 | free_trial | 45 |
| 1 | 2023-01-02 | free_trial | 30 |
| 1 | 2023-01-05 | free_trial | 60 |
| 1 | 2023-01-10 | paid | 75 |
| 1 | 2023-01-12 | paid | 90 |
| 1 | 2023-01-15 | paid | 65 |
| 2 | 2023-02-01 | free_trial | 55 |
| 2 | 2023-02-03 | free_trial | 25 |
| 2 | 2023-02-07 | free_trial | 50 |
| 2 | 2023-02-10 | cancelled | 0 |
| 3 | 2023-03-05 | free_trial | 70 |
| 3 | 2023-03-06 | free_trial | 60 |
| 3 | 2023-03-08 | free_trial | 80 |
| 3 | 2023-03-12 | paid | 50 |
| 3 | 2023-03-15 | paid | 55 |
| 3 | 2023-03-20 | paid | 85 |
| 4 | 2023-04-01 | free_trial | 40 |
| 4 | 2023-04-03 | free_trial | 35 |
| 4 | 2023-04-05 | paid | 45 |
| 4 | 2023-04-07 | cancelled | 0 |
+---------+---------------+---------------+-------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------+--------------------+-------------------+
| user_id | trial_avg_duration | paid_avg_duration |
+---------+--------------------+-------------------+
| 1 | 45.00 | 76.67 |
| 3 | 70.00 | 63.33 |
| 4 | 37.50 | 45.00 |
+---------+--------------------+-------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>User 1:</strong>
<ul>
<li>Had 3 days of free trial with durations of 45, 30, and 60 minutes.</li>
<li>Average trial duration: (45 + 30 + 60) / 3 = 45.00 minutes.</li>
<li>Had 3 days of paid subscription with durations of 75, 90, and 65 minutes.</li>
<li>Average paid duration: (75 + 90 + 65) / 3 = 76.67 minutes.</li>
</ul>
</li>
<li><strong>User 2:</strong>
<ul>
<li>Had 3 days of free trial with durations of 55, 25, and 50 minutes.</li>
<li>Average trial duration: (55 + 25 + 50) / 3 = 43.33 minutes.</li>
<li>Did not convert to a paid subscription (only had free_trial and cancelled activities).</li>
<li>Not included in the output because they didn't convert to paid.</li>
</ul>
</li>
<li><strong>User 3:</strong>
<ul>
<li>Had 3 days of free trial with durations of 70, 60, and 80 minutes.</li>
<li>Average trial duration: (70 + 60 + 80) / 3 = 70.00 minutes.</li>
<li>Had 3 days of paid subscription with durations of 50, 55, and 85 minutes.</li>
<li>Average paid duration: (50 + 55 + 85) / 3 = 63.33 minutes.</li>
</ul>
</li>
<li><strong>User 4:</strong>
<ul>
<li>Had 2 days of free trial with durations of 40 and 35 minutes.</li>
<li>Average trial duration: (40 + 35) / 2 = 37.50 minutes.</li>
<li>Had 1 day of paid subscription with duration of 45 minutes before cancelling.</li>
<li>Average paid duration: 45.00 minutes.</li>
</ul>
</li>
</ul>
<p>The result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT user_id, activity_type, ROUND(SUM(activity_duration) / COUNT(1), 2) duration
FROM UserActivity
WHERE activity_type != 'cancelled'
GROUP BY user_id, activity_type
),
F AS (
SELECT user_id, duration trial_avg_duration
FROM T
WHERE activity_type = 'free_trial'
),
P AS (
SELECT user_id, duration paid_avg_duration
FROM T
WHERE activity_type = 'paid'
)
SELECT user_id, trial_avg_duration, paid_avg_duration
FROM
F
JOIN P USING (user_id)
ORDER BY 1;
|
3,498 |
Reverse Degree of a String
|
Easy
|
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p>
<p>The <strong>reverse degree</strong> is calculated as follows:</p>
<ol>
<li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>'a'</code> = 26, <code>'b'</code> = 25, ..., <code>'z'</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li>
<li>Sum these products for all characters in the string.</li>
</ol>
<p>Return the <strong>reverse degree</strong> of <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">148</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">26</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">25</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">50</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'c'</code></td>
<td style="border: 1px solid black;">24</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">72</td>
</tr>
</tbody>
</table>
<p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaza"</span></p>
<p><strong>Output:</strong> <span class="example-io">160</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">52</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">104</td>
</tr>
</tbody>
</table>
<p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Simulation
|
C++
|
class Solution {
public:
int reverseDegree(string s) {
int n = s.length();
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = 26 - (s[i - 1] - 'a');
ans += i * x;
}
return ans;
}
};
|
3,498 |
Reverse Degree of a String
|
Easy
|
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p>
<p>The <strong>reverse degree</strong> is calculated as follows:</p>
<ol>
<li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>'a'</code> = 26, <code>'b'</code> = 25, ..., <code>'z'</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li>
<li>Sum these products for all characters in the string.</li>
</ol>
<p>Return the <strong>reverse degree</strong> of <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">148</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">26</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">25</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">50</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'c'</code></td>
<td style="border: 1px solid black;">24</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">72</td>
</tr>
</tbody>
</table>
<p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaza"</span></p>
<p><strong>Output:</strong> <span class="example-io">160</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">52</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">104</td>
</tr>
</tbody>
</table>
<p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Simulation
|
Go
|
func reverseDegree(s string) (ans int) {
for i, c := range s {
x := 26 - int(c-'a')
ans += (i + 1) * x
}
return
}
|
3,498 |
Reverse Degree of a String
|
Easy
|
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p>
<p>The <strong>reverse degree</strong> is calculated as follows:</p>
<ol>
<li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>'a'</code> = 26, <code>'b'</code> = 25, ..., <code>'z'</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li>
<li>Sum these products for all characters in the string.</li>
</ol>
<p>Return the <strong>reverse degree</strong> of <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">148</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">26</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">25</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">50</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'c'</code></td>
<td style="border: 1px solid black;">24</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">72</td>
</tr>
</tbody>
</table>
<p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaza"</span></p>
<p><strong>Output:</strong> <span class="example-io">160</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">52</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">104</td>
</tr>
</tbody>
</table>
<p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Simulation
|
Java
|
class Solution {
public int reverseDegree(String s) {
int n = s.length();
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = 26 - (s.charAt(i - 1) - 'a');
ans += i * x;
}
return ans;
}
}
|
3,498 |
Reverse Degree of a String
|
Easy
|
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p>
<p>The <strong>reverse degree</strong> is calculated as follows:</p>
<ol>
<li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>'a'</code> = 26, <code>'b'</code> = 25, ..., <code>'z'</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li>
<li>Sum these products for all characters in the string.</li>
</ol>
<p>Return the <strong>reverse degree</strong> of <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">148</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">26</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">25</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">50</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'c'</code></td>
<td style="border: 1px solid black;">24</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">72</td>
</tr>
</tbody>
</table>
<p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaza"</span></p>
<p><strong>Output:</strong> <span class="example-io">160</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">52</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">104</td>
</tr>
</tbody>
</table>
<p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def reverseDegree(self, s: str) -> int:
ans = 0
for i, c in enumerate(s, 1):
x = 26 - (ord(c) - ord("a"))
ans += i * x
return ans
|
3,498 |
Reverse Degree of a String
|
Easy
|
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p>
<p>The <strong>reverse degree</strong> is calculated as follows:</p>
<ol>
<li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>'a'</code> = 26, <code>'b'</code> = 25, ..., <code>'z'</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li>
<li>Sum these products for all characters in the string.</li>
</ol>
<p>Return the <strong>reverse degree</strong> of <code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc"</span></p>
<p><strong>Output:</strong> <span class="example-io">148</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">26</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'b'</code></td>
<td style="border: 1px solid black;">25</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">50</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'c'</code></td>
<td style="border: 1px solid black;">24</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">72</td>
</tr>
</tbody>
</table>
<p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaza"</span></p>
<p><strong>Output:</strong> <span class="example-io">160</span></p>
<p><strong>Explanation:</strong></p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Letter</th>
<th style="border: 1px solid black;">Index in Reversed Alphabet</th>
<th style="border: 1px solid black;">Index in String</th>
<th style="border: 1px solid black;">Product</th>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">1</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">2</td>
<td style="border: 1px solid black;">52</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'z'</code></td>
<td style="border: 1px solid black;">1</td>
<td style="border: 1px solid black;">3</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;"><code>'a'</code></td>
<td style="border: 1px solid black;">26</td>
<td style="border: 1px solid black;">4</td>
<td style="border: 1px solid black;">104</td>
</tr>
</tbody>
</table>
<p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
String; Simulation
|
TypeScript
|
function reverseDegree(s: string): number {
let ans = 0;
for (let i = 1; i <= s.length; ++i) {
const x = 26 - (s.charCodeAt(i - 1) - 'a'.charCodeAt(0));
ans += i * x;
}
return ans;
}
|
3,499 |
Maximize Active Section with Trade I
|
Medium
|
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p>
<ul>
<li><code>'1'</code> represents an <strong>active</strong> section.</li>
<li><code>'0'</code> represents an <strong>inactive</strong> section.</li>
</ul>
<p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p>
<ul>
<li>Convert a contiguous block of <code>'1'</code>s that is surrounded by <code>'0'</code>s to all <code>'0'</code>s.</li>
<li>Afterward, convert a contiguous block of <code>'0'</code>s that is surrounded by <code>'1'</code>s to all <code>'1'</code>s.</li>
</ul>
<p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p>
<p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>'1'</code> at both ends, forming <code>t = '1' + s + '1'</code>. The augmented <code>'1'</code>s <strong>do not</strong> contribute to the final count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Because there is no block of <code>'1'</code>s surrounded by <code>'0'</code>s, no valid trade is possible. The maximum number of active sections is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0100"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"0100"</code> → Augmented to <code>"101001"</code>.</li>
<li>Choose <code>"0100"</code>, convert <code>"10<u><strong>1</strong></u>001"</code> → <code>"1<u><strong>0000</strong></u>1"</code> → <code>"1<u><strong>1111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1000100"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"1000100"</code> → Augmented to <code>"110001001"</code>.</li>
<li>Choose <code>"000100"</code>, convert <code>"11000<u><strong>1</strong></u>001"</code> → <code>"11<u><strong>000000</strong></u>1"</code> → <code>"11<u><strong>111111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111111"</code>. The maximum number of active sections is 7.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01010"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"01010"</code> → Augmented to <code>"1010101"</code>.</li>
<li>Choose <code>"010"</code>, convert <code>"10<u><strong>1</strong></u>0101"</code> → <code>"1<u><strong>000</strong></u>101"</code> → <code>"1<u><strong>111</strong></u>101"</code>.</li>
<li>The final string without augmentation is <code>"11110"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<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>
|
String; Enumeration
|
C++
|
class Solution {
public:
int maxActiveSectionsAfterTrade(std::string s) {
int n = s.length();
int ans = 0, i = 0;
int pre = INT_MIN, mx = 0;
while (i < n) {
int j = i + 1;
while (j < n && s[j] == s[i]) {
j++;
}
int cur = j - i;
if (s[i] == '1') {
ans += cur;
} else {
mx = std::max(mx, pre + cur);
pre = cur;
}
i = j;
}
ans += mx;
return ans;
}
};
|
3,499 |
Maximize Active Section with Trade I
|
Medium
|
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p>
<ul>
<li><code>'1'</code> represents an <strong>active</strong> section.</li>
<li><code>'0'</code> represents an <strong>inactive</strong> section.</li>
</ul>
<p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p>
<ul>
<li>Convert a contiguous block of <code>'1'</code>s that is surrounded by <code>'0'</code>s to all <code>'0'</code>s.</li>
<li>Afterward, convert a contiguous block of <code>'0'</code>s that is surrounded by <code>'1'</code>s to all <code>'1'</code>s.</li>
</ul>
<p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p>
<p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>'1'</code> at both ends, forming <code>t = '1' + s + '1'</code>. The augmented <code>'1'</code>s <strong>do not</strong> contribute to the final count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Because there is no block of <code>'1'</code>s surrounded by <code>'0'</code>s, no valid trade is possible. The maximum number of active sections is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0100"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"0100"</code> → Augmented to <code>"101001"</code>.</li>
<li>Choose <code>"0100"</code>, convert <code>"10<u><strong>1</strong></u>001"</code> → <code>"1<u><strong>0000</strong></u>1"</code> → <code>"1<u><strong>1111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1000100"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"1000100"</code> → Augmented to <code>"110001001"</code>.</li>
<li>Choose <code>"000100"</code>, convert <code>"11000<u><strong>1</strong></u>001"</code> → <code>"11<u><strong>000000</strong></u>1"</code> → <code>"11<u><strong>111111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111111"</code>. The maximum number of active sections is 7.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01010"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"01010"</code> → Augmented to <code>"1010101"</code>.</li>
<li>Choose <code>"010"</code>, convert <code>"10<u><strong>1</strong></u>0101"</code> → <code>"1<u><strong>000</strong></u>101"</code> → <code>"1<u><strong>111</strong></u>101"</code>.</li>
<li>The final string without augmentation is <code>"11110"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<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>
|
String; Enumeration
|
Go
|
func maxActiveSectionsAfterTrade(s string) (ans int) {
n := len(s)
pre, mx := math.MinInt, 0
for i := 0; i < n; {
j := i + 1
for j < n && s[j] == s[i] {
j++
}
cur := j - i
if s[i] == '1' {
ans += cur
} else {
mx = max(mx, pre+cur)
pre = cur
}
i = j
}
ans += mx
return
}
|
3,499 |
Maximize Active Section with Trade I
|
Medium
|
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p>
<ul>
<li><code>'1'</code> represents an <strong>active</strong> section.</li>
<li><code>'0'</code> represents an <strong>inactive</strong> section.</li>
</ul>
<p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p>
<ul>
<li>Convert a contiguous block of <code>'1'</code>s that is surrounded by <code>'0'</code>s to all <code>'0'</code>s.</li>
<li>Afterward, convert a contiguous block of <code>'0'</code>s that is surrounded by <code>'1'</code>s to all <code>'1'</code>s.</li>
</ul>
<p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p>
<p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>'1'</code> at both ends, forming <code>t = '1' + s + '1'</code>. The augmented <code>'1'</code>s <strong>do not</strong> contribute to the final count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Because there is no block of <code>'1'</code>s surrounded by <code>'0'</code>s, no valid trade is possible. The maximum number of active sections is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0100"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"0100"</code> → Augmented to <code>"101001"</code>.</li>
<li>Choose <code>"0100"</code>, convert <code>"10<u><strong>1</strong></u>001"</code> → <code>"1<u><strong>0000</strong></u>1"</code> → <code>"1<u><strong>1111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1000100"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"1000100"</code> → Augmented to <code>"110001001"</code>.</li>
<li>Choose <code>"000100"</code>, convert <code>"11000<u><strong>1</strong></u>001"</code> → <code>"11<u><strong>000000</strong></u>1"</code> → <code>"11<u><strong>111111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111111"</code>. The maximum number of active sections is 7.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01010"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"01010"</code> → Augmented to <code>"1010101"</code>.</li>
<li>Choose <code>"010"</code>, convert <code>"10<u><strong>1</strong></u>0101"</code> → <code>"1<u><strong>000</strong></u>101"</code> → <code>"1<u><strong>111</strong></u>101"</code>.</li>
<li>The final string without augmentation is <code>"11110"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<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>
|
String; Enumeration
|
Java
|
class Solution {
public int maxActiveSectionsAfterTrade(String s) {
int n = s.length();
int ans = 0, i = 0;
int pre = Integer.MIN_VALUE, mx = 0;
while (i < n) {
int j = i + 1;
while (j < n && s.charAt(j) == s.charAt(i)) {
j++;
}
int cur = j - i;
if (s.charAt(i) == '1') {
ans += cur;
} else {
mx = Math.max(mx, pre + cur);
pre = cur;
}
i = j;
}
ans += mx;
return ans;
}
}
|
3,499 |
Maximize Active Section with Trade I
|
Medium
|
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p>
<ul>
<li><code>'1'</code> represents an <strong>active</strong> section.</li>
<li><code>'0'</code> represents an <strong>inactive</strong> section.</li>
</ul>
<p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p>
<ul>
<li>Convert a contiguous block of <code>'1'</code>s that is surrounded by <code>'0'</code>s to all <code>'0'</code>s.</li>
<li>Afterward, convert a contiguous block of <code>'0'</code>s that is surrounded by <code>'1'</code>s to all <code>'1'</code>s.</li>
</ul>
<p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p>
<p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>'1'</code> at both ends, forming <code>t = '1' + s + '1'</code>. The augmented <code>'1'</code>s <strong>do not</strong> contribute to the final count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Because there is no block of <code>'1'</code>s surrounded by <code>'0'</code>s, no valid trade is possible. The maximum number of active sections is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0100"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"0100"</code> → Augmented to <code>"101001"</code>.</li>
<li>Choose <code>"0100"</code>, convert <code>"10<u><strong>1</strong></u>001"</code> → <code>"1<u><strong>0000</strong></u>1"</code> → <code>"1<u><strong>1111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1000100"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"1000100"</code> → Augmented to <code>"110001001"</code>.</li>
<li>Choose <code>"000100"</code>, convert <code>"11000<u><strong>1</strong></u>001"</code> → <code>"11<u><strong>000000</strong></u>1"</code> → <code>"11<u><strong>111111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111111"</code>. The maximum number of active sections is 7.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01010"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"01010"</code> → Augmented to <code>"1010101"</code>.</li>
<li>Choose <code>"010"</code>, convert <code>"10<u><strong>1</strong></u>0101"</code> → <code>"1<u><strong>000</strong></u>101"</code> → <code>"1<u><strong>111</strong></u>101"</code>.</li>
<li>The final string without augmentation is <code>"11110"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<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>
|
String; Enumeration
|
Python
|
class Solution:
def maxActiveSectionsAfterTrade(self, s: str) -> int:
n = len(s)
ans = i = 0
pre, mx = -inf, 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cur = j - i
if s[i] == "1":
ans += cur
else:
mx = max(mx, pre + cur)
pre = cur
i = j
ans += mx
return ans
|
3,499 |
Maximize Active Section with Trade I
|
Medium
|
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p>
<ul>
<li><code>'1'</code> represents an <strong>active</strong> section.</li>
<li><code>'0'</code> represents an <strong>inactive</strong> section.</li>
</ul>
<p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p>
<ul>
<li>Convert a contiguous block of <code>'1'</code>s that is surrounded by <code>'0'</code>s to all <code>'0'</code>s.</li>
<li>Afterward, convert a contiguous block of <code>'0'</code>s that is surrounded by <code>'1'</code>s to all <code>'1'</code>s.</li>
</ul>
<p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p>
<p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>'1'</code> at both ends, forming <code>t = '1' + s + '1'</code>. The augmented <code>'1'</code>s <strong>do not</strong> contribute to the final count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Because there is no block of <code>'1'</code>s surrounded by <code>'0'</code>s, no valid trade is possible. The maximum number of active sections is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0100"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"0100"</code> → Augmented to <code>"101001"</code>.</li>
<li>Choose <code>"0100"</code>, convert <code>"10<u><strong>1</strong></u>001"</code> → <code>"1<u><strong>0000</strong></u>1"</code> → <code>"1<u><strong>1111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1000100"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"1000100"</code> → Augmented to <code>"110001001"</code>.</li>
<li>Choose <code>"000100"</code>, convert <code>"11000<u><strong>1</strong></u>001"</code> → <code>"11<u><strong>000000</strong></u>1"</code> → <code>"11<u><strong>111111</strong></u>1"</code>.</li>
<li>The final string without augmentation is <code>"1111111"</code>. The maximum number of active sections is 7.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "01010"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>String <code>"01010"</code> → Augmented to <code>"1010101"</code>.</li>
<li>Choose <code>"010"</code>, convert <code>"10<u><strong>1</strong></u>0101"</code> → <code>"1<u><strong>000</strong></u>101"</code> → <code>"1<u><strong>111</strong></u>101"</code>.</li>
<li>The final string without augmentation is <code>"11110"</code>. The maximum number of active sections is 4.</li>
</ul>
</div>
<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>
|
String; Enumeration
|
TypeScript
|
function maxActiveSectionsAfterTrade(s: string): number {
let n = s.length;
let [ans, mx] = [0, 0];
let pre = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && s[j] === s[i]) {
j++;
}
let cur = j - i;
if (s[i] === '1') {
ans += cur;
} else {
mx = Math.max(mx, pre + cur);
pre = cur;
}
i = j;
}
ans += mx;
return ans;
}
|
3,502 |
Minimum Cost to Reach Every Position
|
Easy
|
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p>
<p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p>
<p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p>
<ul data-end="632" data-start="488">
<li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li>
<li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li>
</ul>
<p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can get to each position in the following way:</p>
<ul>
<li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li>
<li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li>
<li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li>
<li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li>
<li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li>
<li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == cost.length <= 100</code></li>
<li><code>1 <= cost[i] <= 100</code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
vector<int> minCosts(vector<int>& cost) {
int n = cost.size();
vector<int> ans(n);
int mi = cost[0];
for (int i = 0; i < n; ++i) {
mi = min(mi, cost[i]);
ans[i] = mi;
}
return ans;
}
};
|
3,502 |
Minimum Cost to Reach Every Position
|
Easy
|
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p>
<p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p>
<p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p>
<ul data-end="632" data-start="488">
<li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li>
<li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li>
</ul>
<p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can get to each position in the following way:</p>
<ul>
<li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li>
<li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li>
<li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li>
<li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li>
<li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li>
<li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == cost.length <= 100</code></li>
<li><code>1 <= cost[i] <= 100</code></li>
</ul>
|
Array
|
Go
|
func minCosts(cost []int) []int {
n := len(cost)
ans := make([]int, n)
mi := cost[0]
for i, c := range cost {
mi = min(mi, c)
ans[i] = mi
}
return ans
}
|
3,502 |
Minimum Cost to Reach Every Position
|
Easy
|
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p>
<p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p>
<p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p>
<ul data-end="632" data-start="488">
<li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li>
<li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li>
</ul>
<p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can get to each position in the following way:</p>
<ul>
<li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li>
<li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li>
<li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li>
<li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li>
<li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li>
<li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == cost.length <= 100</code></li>
<li><code>1 <= cost[i] <= 100</code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int[] minCosts(int[] cost) {
int n = cost.length;
int[] ans = new int[n];
int mi = cost[0];
for (int i = 0; i < n; ++i) {
mi = Math.min(mi, cost[i]);
ans[i] = mi;
}
return ans;
}
}
|
3,502 |
Minimum Cost to Reach Every Position
|
Easy
|
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p>
<p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p>
<p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p>
<ul data-end="632" data-start="488">
<li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li>
<li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li>
</ul>
<p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can get to each position in the following way:</p>
<ul>
<li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li>
<li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li>
<li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li>
<li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li>
<li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li>
<li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == cost.length <= 100</code></li>
<li><code>1 <= cost[i] <= 100</code></li>
</ul>
|
Array
|
Python
|
class Solution:
def minCosts(self, cost: List[int]) -> List[int]:
n = len(cost)
ans = [0] * n
mi = cost[0]
for i, c in enumerate(cost):
mi = min(mi, c)
ans[i] = mi
return ans
|
3,502 |
Minimum Cost to Reach Every Position
|
Easy
|
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p>
<p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p>
<p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p>
<ul data-end="632" data-start="488">
<li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li>
<li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li>
</ul>
<p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can get to each position in the following way:</p>
<ul>
<li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li>
<li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li>
<li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li>
<li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li>
<li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li>
<li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == cost.length <= 100</code></li>
<li><code>1 <= cost[i] <= 100</code></li>
</ul>
|
Array
|
TypeScript
|
function minCosts(cost: number[]): number[] {
const n = cost.length;
const ans: number[] = Array(n).fill(0);
let mi = cost[0];
for (let i = 0; i < n; ++i) {
mi = Math.min(mi, cost[i]);
ans[i] = mi;
}
return ans;
}
|
3,503 |
Longest Palindrome After Substring Concatenation I
|
Medium
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> 5</p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 30</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming; Enumeration
|
C++
|
class Solution {
public:
int longestPalindrome(string s, string t) {
int m = s.size(), n = t.size();
ranges::reverse(t);
vector<int> g1 = calc(s), g2 = calc(t);
int ans = max(ranges::max(g1), ranges::max(g2));
vector<vector<int>> f(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0));
ans = max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0));
}
}
}
return ans;
}
private:
void expand(const string& s, vector<int>& g, int l, int r) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
g[l] = max(g[l], r - l + 1);
--l;
++r;
}
}
vector<int> calc(const string& s) {
int n = s.size();
vector<int> g(n, 0);
for (int i = 0; i < n; ++i) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
};
|
3,503 |
Longest Palindrome After Substring Concatenation I
|
Medium
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> 5</p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 30</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming; Enumeration
|
Go
|
func longestPalindrome(s, t string) int {
m, n := len(s), len(t)
t = reverse(t)
g1, g2 := calc(s), calc(t)
ans := max(slices.Max(g1), slices.Max(g2))
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if s[i-1] == t[j-1] {
f[i][j] = f[i-1][j-1] + 1
a, b := 0, 0
if i < m {
a = g1[i]
}
if j < n {
b = g2[j]
}
ans = max(ans, f[i][j]*2+a)
ans = max(ans, f[i][j]*2+b)
}
}
}
return ans
}
func calc(s string) []int {
n, g := len(s), make([]int, len(s))
for i := 0; i < n; i++ {
expand(s, g, i, i)
expand(s, g, i, i+1)
}
return g
}
func expand(s string, g []int, l, r int) {
for l >= 0 && r < len(s) && s[l] == s[r] {
g[l] = max(g[l], r-l+1)
l, r = l-1, r+1
}
}
func reverse(s string) string {
r := []rune(s)
slices.Reverse(r)
return string(r)
}
|
3,503 |
Longest Palindrome After Substring Concatenation I
|
Medium
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> 5</p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 30</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming; Enumeration
|
Java
|
class Solution {
public int longestPalindrome(String S, String T) {
char[] s = S.toCharArray();
char[] t = new StringBuilder(T).reverse().toString().toCharArray();
int m = s.length, n = t.length;
int[] g1 = calc(s), g2 = calc(t);
int ans = Math.max(Arrays.stream(g1).max().getAsInt(), Arrays.stream(g2).max().getAsInt());
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = Math.max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0));
ans = Math.max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0));
}
}
}
return ans;
}
private void expand(char[] s, int[] g, int l, int r) {
while (l >= 0 && r < s.length && s[l] == s[r]) {
g[l] = Math.max(g[l], r - l + 1);
--l;
++r;
}
}
private int[] calc(char[] s) {
int n = s.length;
int[] g = new int[n];
for (int i = 0; i < n; ++i) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
}
|
3,503 |
Longest Palindrome After Substring Concatenation I
|
Medium
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> 5</p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 30</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming; Enumeration
|
Python
|
class Solution:
def longestPalindrome(self, s: str, t: str) -> int:
def expand(s: str, g: List[int], l: int, r: int):
while l >= 0 and r < len(s) and s[l] == s[r]:
g[l] = max(g[l], r - l + 1)
l, r = l - 1, r + 1
def calc(s: str) -> List[int]:
n = len(s)
g = [0] * n
for i in range(n):
expand(s, g, i, i)
expand(s, g, i, i + 1)
return g
m, n = len(s), len(t)
t = t[::-1]
g1, g2 = calc(s), calc(t)
ans = max(*g1, *g2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i, a in enumerate(s, 1):
for j, b in enumerate(t, 1):
if a == b:
f[i][j] = f[i - 1][j - 1] + 1
ans = max(ans, f[i][j] * 2 + (0 if i >= m else g1[i]))
ans = max(ans, f[i][j] * 2 + (0 if j >= n else g2[j]))
return ans
|
3,503 |
Longest Palindrome After Substring Concatenation I
|
Medium
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> 4</p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> 5</p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 30</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming; Enumeration
|
TypeScript
|
function longestPalindrome(s: string, t: string): number {
function expand(s: string, g: number[], l: number, r: number): void {
while (l >= 0 && r < s.length && s[l] === s[r]) {
g[l] = Math.max(g[l], r - l + 1);
l--;
r++;
}
}
function calc(s: string): number[] {
const n = s.length;
const g: number[] = Array(n).fill(0);
for (let i = 0; i < n; i++) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
const m = s.length,
n = t.length;
t = t.split('').reverse().join('');
const g1 = calc(s);
const g2 = calc(t);
let ans = Math.max(...g1, ...g2);
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (s[i - 1] === t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = Math.max(ans, f[i][j] * 2 + (i >= m ? 0 : g1[i]));
ans = Math.max(ans, f[i][j] * 2 + (j >= n ? 0 : g2[j]));
}
}
}
return ans;
}
|
3,504 |
Longest Palindrome After Substring Concatenation II
|
Hard
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 1000</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
C++
|
class Solution {
public:
int longestPalindrome(string s, string t) {
int m = s.size(), n = t.size();
ranges::reverse(t);
vector<int> g1 = calc(s), g2 = calc(t);
int ans = max(ranges::max(g1), ranges::max(g2));
vector<vector<int>> f(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0));
ans = max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0));
}
}
}
return ans;
}
private:
void expand(const string& s, vector<int>& g, int l, int r) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
g[l] = max(g[l], r - l + 1);
--l;
++r;
}
}
vector<int> calc(const string& s) {
int n = s.size();
vector<int> g(n, 0);
for (int i = 0; i < n; ++i) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
};
|
3,504 |
Longest Palindrome After Substring Concatenation II
|
Hard
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 1000</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Go
|
func longestPalindrome(s, t string) int {
m, n := len(s), len(t)
t = reverse(t)
g1, g2 := calc(s), calc(t)
ans := max(slices.Max(g1), slices.Max(g2))
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if s[i-1] == t[j-1] {
f[i][j] = f[i-1][j-1] + 1
a, b := 0, 0
if i < m {
a = g1[i]
}
if j < n {
b = g2[j]
}
ans = max(ans, f[i][j]*2+a)
ans = max(ans, f[i][j]*2+b)
}
}
}
return ans
}
func calc(s string) []int {
n, g := len(s), make([]int, len(s))
for i := 0; i < n; i++ {
expand(s, g, i, i)
expand(s, g, i, i+1)
}
return g
}
func expand(s string, g []int, l, r int) {
for l >= 0 && r < len(s) && s[l] == s[r] {
g[l] = max(g[l], r-l+1)
l, r = l-1, r+1
}
}
func reverse(s string) string {
r := []rune(s)
slices.Reverse(r)
return string(r)
}
|
3,504 |
Longest Palindrome After Substring Concatenation II
|
Hard
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 1000</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Java
|
class Solution {
public int longestPalindrome(String S, String T) {
char[] s = S.toCharArray();
char[] t = new StringBuilder(T).reverse().toString().toCharArray();
int m = s.length, n = t.length;
int[] g1 = calc(s), g2 = calc(t);
int ans = Math.max(Arrays.stream(g1).max().getAsInt(), Arrays.stream(g2).max().getAsInt());
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = Math.max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0));
ans = Math.max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0));
}
}
}
return ans;
}
private void expand(char[] s, int[] g, int l, int r) {
while (l >= 0 && r < s.length && s[l] == s[r]) {
g[l] = Math.max(g[l], r - l + 1);
--l;
++r;
}
}
private int[] calc(char[] s) {
int n = s.length;
int[] g = new int[n];
for (int i = 0; i < n; ++i) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
}
|
3,504 |
Longest Palindrome After Substring Concatenation II
|
Hard
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 1000</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Python
|
class Solution:
def longestPalindrome(self, s: str, t: str) -> int:
def expand(s: str, g: List[int], l: int, r: int):
while l >= 0 and r < len(s) and s[l] == s[r]:
g[l] = max(g[l], r - l + 1)
l, r = l - 1, r + 1
def calc(s: str) -> List[int]:
n = len(s)
g = [0] * n
for i in range(n):
expand(s, g, i, i)
expand(s, g, i, i + 1)
return g
m, n = len(s), len(t)
t = t[::-1]
g1, g2 = calc(s), calc(t)
ans = max(*g1, *g2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i, a in enumerate(s, 1):
for j, b in enumerate(t, 1):
if a == b:
f[i][j] = f[i - 1][j - 1] + 1
ans = max(ans, f[i][j] * 2 + (0 if i >= m else g1[i]))
ans = max(ans, f[i][j] * 2 + (0 if j >= n else g2[j]))
return ans
|
3,504 |
Longest Palindrome After Substring Concatenation II
|
Hard
|
<p>You are given two strings, <code>s</code> and <code>t</code>.</p>
<p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p>
<p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "a"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"a"</code> from <code>s</code> and <code>"a"</code> from <code>t</code> results in <code>"aa"</code>, which is a palindrome of length 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abc", t = "def"</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "b", t = "aaaa"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Selecting "<code>aaaa</code>" from <code>t</code> is the longest palindrome, so the answer is 4.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abcde", t = "ecdba"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>Concatenating <code>"abc"</code> from <code>s</code> and <code>"ba"</code> from <code>t</code> results in <code>"abcba"</code>, which is a palindrome of length 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length, t.length <= 1000</code></li>
<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
TypeScript
|
function longestPalindrome(s: string, t: string): number {
function expand(s: string, g: number[], l: number, r: number): void {
while (l >= 0 && r < s.length && s[l] === s[r]) {
g[l] = Math.max(g[l], r - l + 1);
l--;
r++;
}
}
function calc(s: string): number[] {
const n = s.length;
const g: number[] = Array(n).fill(0);
for (let i = 0; i < n; i++) {
expand(s, g, i, i);
expand(s, g, i, i + 1);
}
return g;
}
const m = s.length,
n = t.length;
t = t.split('').reverse().join('');
const g1 = calc(s);
const g2 = calc(t);
let ans = Math.max(...g1, ...g2);
const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (s[i - 1] === t[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
ans = Math.max(ans, f[i][j] * 2 + (i >= m ? 0 : g1[i]));
ans = Math.max(ans, f[i][j] * 2 + (j >= n ? 0 : g2[j]));
}
}
}
return ans;
}
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long minEliminationTime(vector<int>& timeReq, int splitTime) {
using ll = long long;
priority_queue<ll, vector<ll>, greater<ll>> pq;
for (int v : timeReq) {
pq.push(v);
}
while (pq.size() > 1) {
pq.pop();
ll x = pq.top();
pq.pop();
pq.push(x + splitTime);
}
return pq.top();
}
};
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
Go
|
func minEliminationTime(timeReq []int, splitTime int) int64 {
pq := hp{}
for _, v := range timeReq {
heap.Push(&pq, v)
}
for pq.Len() > 1 {
heap.Pop(&pq)
heap.Push(&pq, heap.Pop(&pq).(int)+splitTime)
}
return int64(pq.IntSlice[0])
}
type hp struct{ sort.IntSlice }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
Java
|
class Solution {
public long minEliminationTime(int[] timeReq, int splitTime) {
PriorityQueue<Long> q = new PriorityQueue<>();
for (int x : timeReq) {
q.offer((long) x);
}
while (q.size() > 1) {
q.poll();
q.offer(q.poll() + splitTime);
}
return q.poll();
}
}
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
Python
|
class Solution:
def minEliminationTime(self, timeReq: List[int], splitTime: int) -> int:
heapify(timeReq)
while len(timeReq) > 1:
heappop(timeReq)
heappush(timeReq, heappop(timeReq) + splitTime)
return timeReq[0]
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
Rust
|
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn min_elimination_time(time_req: Vec<i32>, split_time: i32) -> i64 {
let mut pq = BinaryHeap::new();
for x in time_req {
pq.push(Reverse(x as i64));
}
while pq.len() > 1 {
pq.pop();
let merged = pq.pop().unwrap().0 + split_time as i64;
pq.push(Reverse(merged));
}
pq.pop().unwrap().0
}
}
|
3,506 |
Find Time Required to Eliminate Bacterial Strains
|
Hard
|
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p>
<p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body's survival.</p>
<p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p>
<p>The WBC devises a clever strategy to fight the bacteria:</p>
<ul>
<li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li>
<li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li>
<li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li>
<li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li>
</ul>
<p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p>
<p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li>
<li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p>
<p><strong>Output:</strong>15</p>
<p><strong>Explanation:</strong></p>
<p>The elimination process goes as follows:</p>
<ul>
<li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li>
<li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= timeReq.length <= 10<sup>5</sup></code></li>
<li><code>1 <= timeReq[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= splitTime <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Math; Heap (Priority Queue)
|
TypeScript
|
function minEliminationTime(timeReq: number[], splitTime: number): number {
const pq = new MinPriorityQueue();
for (const b of timeReq) {
pq.enqueue(b);
}
while (pq.size() > 1) {
pq.dequeue()!;
pq.enqueue(pq.dequeue()! + splitTime);
}
return pq.dequeue()!;
}
|
3,511 |
Make a Positive Array
|
Medium
|
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p>
<p>You can perform the following operation any number of times:</p>
<ul>
<li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li>
</ul>
<p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarrays with more than 2 elements and a non-positive sum are:</p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Subarray Indices</th>
<th style="border: 1px solid black;">Subarray</th>
<th style="border: 1px solid black;">Sum</th>
<th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th>
<th style="border: 1px solid black;">New Sum</th>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...2]</td>
<td style="border: 1px solid black;">[-1, -2, 3]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[-1, 1, 3]</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...3]</td>
<td style="border: 1px solid black;">[-1, -2, 3, -1]</td>
<td style="border: 1px solid black;">-1</td>
<td style="border: 1px solid black;">[-1, 1, 3, -1]</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[1...3]</td>
<td style="border: 1px solid black;">[-2, 3, -1]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[1, 3, -1]</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>Thus, <code>nums</code> is positive after one operation.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array is already positive, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum
|
C++
|
class Solution {
public:
int makeArrayPositive(vector<int>& nums) {
int ans = 0;
long long preMx = 0, s = 0;
for (int l = -1, r = 0; r < nums.size(); r++) {
int x = nums[r];
s += x;
if (r - l > 2 && s <= preMx) {
ans++;
l = r;
preMx = s = 0;
} else if (r - l >= 2) {
preMx = max(preMx, s - x - nums[r - 1]);
}
}
return ans;
}
};
|
3,511 |
Make a Positive Array
|
Medium
|
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p>
<p>You can perform the following operation any number of times:</p>
<ul>
<li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li>
</ul>
<p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarrays with more than 2 elements and a non-positive sum are:</p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Subarray Indices</th>
<th style="border: 1px solid black;">Subarray</th>
<th style="border: 1px solid black;">Sum</th>
<th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th>
<th style="border: 1px solid black;">New Sum</th>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...2]</td>
<td style="border: 1px solid black;">[-1, -2, 3]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[-1, 1, 3]</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...3]</td>
<td style="border: 1px solid black;">[-1, -2, 3, -1]</td>
<td style="border: 1px solid black;">-1</td>
<td style="border: 1px solid black;">[-1, 1, 3, -1]</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[1...3]</td>
<td style="border: 1px solid black;">[-2, 3, -1]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[1, 3, -1]</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>Thus, <code>nums</code> is positive after one operation.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array is already positive, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum
|
Go
|
func makeArrayPositive(nums []int) (ans int) {
l := -1
preMx := 0
s := 0
for r, x := range nums {
s += x
if r-l > 2 && s <= preMx {
ans++
l = r
preMx = 0
s = 0
} else if r-l >= 2 {
preMx = max(preMx, s-x-nums[r-1])
}
}
return
}
|
3,511 |
Make a Positive Array
|
Medium
|
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p>
<p>You can perform the following operation any number of times:</p>
<ul>
<li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li>
</ul>
<p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarrays with more than 2 elements and a non-positive sum are:</p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Subarray Indices</th>
<th style="border: 1px solid black;">Subarray</th>
<th style="border: 1px solid black;">Sum</th>
<th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th>
<th style="border: 1px solid black;">New Sum</th>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...2]</td>
<td style="border: 1px solid black;">[-1, -2, 3]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[-1, 1, 3]</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...3]</td>
<td style="border: 1px solid black;">[-1, -2, 3, -1]</td>
<td style="border: 1px solid black;">-1</td>
<td style="border: 1px solid black;">[-1, 1, 3, -1]</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[1...3]</td>
<td style="border: 1px solid black;">[-2, 3, -1]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[1, 3, -1]</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>Thus, <code>nums</code> is positive after one operation.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array is already positive, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum
|
Java
|
class Solution {
public int makeArrayPositive(int[] nums) {
int ans = 0;
long preMx = 0, s = 0;
for (int l = -1, r = 0; r < nums.length; r++) {
int x = nums[r];
s += x;
if (r - l > 2 && s <= preMx) {
ans++;
l = r;
preMx = s = 0;
} else if (r - l >= 2) {
preMx = Math.max(preMx, s - x - nums[r - 1]);
}
}
return ans;
}
}
|
3,511 |
Make a Positive Array
|
Medium
|
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p>
<p>You can perform the following operation any number of times:</p>
<ul>
<li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li>
</ul>
<p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarrays with more than 2 elements and a non-positive sum are:</p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Subarray Indices</th>
<th style="border: 1px solid black;">Subarray</th>
<th style="border: 1px solid black;">Sum</th>
<th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th>
<th style="border: 1px solid black;">New Sum</th>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...2]</td>
<td style="border: 1px solid black;">[-1, -2, 3]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[-1, 1, 3]</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...3]</td>
<td style="border: 1px solid black;">[-1, -2, 3, -1]</td>
<td style="border: 1px solid black;">-1</td>
<td style="border: 1px solid black;">[-1, 1, 3, -1]</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[1...3]</td>
<td style="border: 1px solid black;">[-2, 3, -1]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[1, 3, -1]</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>Thus, <code>nums</code> is positive after one operation.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array is already positive, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum
|
Python
|
class Solution:
def makeArrayPositive(self, nums: List[int]) -> int:
l = -1
ans = pre_mx = s = 0
for r, x in enumerate(nums):
s += x
if r - l > 2 and s <= pre_mx:
ans += 1
l = r
pre_mx = s = 0
elif r - l >= 2:
pre_mx = max(pre_mx, s - x - nums[r - 1])
return ans
|
3,511 |
Make a Positive Array
|
Medium
|
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p>
<p>You can perform the following operation any number of times:</p>
<ul>
<li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li>
</ul>
<p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only subarrays with more than 2 elements and a non-positive sum are:</p>
<table style="border: 1px solid black;">
<tbody>
<tr>
<th style="border: 1px solid black;">Subarray Indices</th>
<th style="border: 1px solid black;">Subarray</th>
<th style="border: 1px solid black;">Sum</th>
<th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th>
<th style="border: 1px solid black;">New Sum</th>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...2]</td>
<td style="border: 1px solid black;">[-1, -2, 3]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[-1, 1, 3]</td>
<td style="border: 1px solid black;">3</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[0...3]</td>
<td style="border: 1px solid black;">[-1, -2, 3, -1]</td>
<td style="border: 1px solid black;">-1</td>
<td style="border: 1px solid black;">[-1, 1, 3, -1]</td>
<td style="border: 1px solid black;">2</td>
</tr>
<tr>
<td style="border: 1px solid black;">nums[1...3]</td>
<td style="border: 1px solid black;">[-2, 3, -1]</td>
<td style="border: 1px solid black;">0</td>
<td style="border: 1px solid black;">[1, 3, -1]</td>
<td style="border: 1px solid black;">3</td>
</tr>
</tbody>
</table>
<p>Thus, <code>nums</code> is positive after one operation.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array is already positive, so no operations are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum
|
TypeScript
|
function makeArrayPositive(nums: number[]): number {
let l = -1;
let [ans, preMx, s] = [0, 0, 0];
for (let r = 0; r < nums.length; r++) {
const x = nums[r];
s += x;
if (r - l > 2 && s <= preMx) {
ans++;
l = r;
preMx = 0;
s = 0;
} else if (r - l >= 2) {
preMx = Math.max(preMx, s - x - nums[r - 1]);
}
}
return ans;
}
|
3,512 |
Minimum Operations to Make Array Sum Divisible by K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p>
<ul>
<li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li>
<li>The sum is 15, which is divisible by 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li>
<li>The sum is 0, which is divisible by 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
return reduce(nums.begin(), nums.end(), 0) % k;
}
};
|
3,512 |
Minimum Operations to Make Array Sum Divisible by K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p>
<ul>
<li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li>
<li>The sum is 15, which is divisible by 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li>
<li>The sum is 0, which is divisible by 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Math
|
Go
|
func minOperations(nums []int, k int) (ans int) {
for _, x := range nums {
ans = (ans + x) % k
}
return
}
|
3,512 |
Minimum Operations to Make Array Sum Divisible by K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p>
<ul>
<li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li>
<li>The sum is 15, which is divisible by 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li>
<li>The sum is 0, which is divisible by 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int minOperations(int[] nums, int k) {
return Arrays.stream(nums).sum() % k;
}
}
|
3,512 |
Minimum Operations to Make Array Sum Divisible by K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p>
<ul>
<li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li>
<li>The sum is 15, which is divisible by 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li>
<li>The sum is 0, which is divisible by 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(nums) % k
|
3,512 |
Minimum Operations to Make Array Sum Divisible by K
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p>
<ul>
<li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li>
<li>The sum is 15, which is divisible by 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li>
<li>The sum is 0, which is divisible by 6.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= 100</code></li>
</ul>
|
Array; Math
|
TypeScript
|
function minOperations(nums: number[], k: number): number {
return nums.reduce((acc, x) => acc + x, 0) % k;
}
|
3,516 |
Find Closest Person
|
Easy
|
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p>
<ul data-end="252" data-start="118">
<li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li>
<li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li>
<li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li>
</ul>
<p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p>
<p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p>
<ul data-end="505" data-start="374">
<li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li>
<li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li>
<li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li>
</ul>
<p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="258" data-start="113">
<li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li>
<li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li>
</ul>
<p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 100</code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
int findClosest(int x, int y, int z) {
int a = abs(x - z);
int b = abs(y - z);
return a == b ? 0 : (a < b ? 1 : 2);
}
};
|
3,516 |
Find Closest Person
|
Easy
|
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p>
<ul data-end="252" data-start="118">
<li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li>
<li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li>
<li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li>
</ul>
<p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p>
<p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p>
<ul data-end="505" data-start="374">
<li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li>
<li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li>
<li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li>
</ul>
<p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="258" data-start="113">
<li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li>
<li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li>
</ul>
<p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 100</code></li>
</ul>
|
Math
|
Go
|
func findClosest(x int, y int, z int) int {
a, b := abs(x-z), abs(y-z)
if a == b {
return 0
}
if a < b {
return 1
}
return 2
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,516 |
Find Closest Person
|
Easy
|
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p>
<ul data-end="252" data-start="118">
<li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li>
<li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li>
<li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li>
</ul>
<p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p>
<p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p>
<ul data-end="505" data-start="374">
<li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li>
<li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li>
<li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li>
</ul>
<p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="258" data-start="113">
<li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li>
<li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li>
</ul>
<p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 100</code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int findClosest(int x, int y, int z) {
int a = Math.abs(x - z);
int b = Math.abs(y - z);
return a == b ? 0 : (a < b ? 1 : 2);
}
}
|
3,516 |
Find Closest Person
|
Easy
|
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p>
<ul data-end="252" data-start="118">
<li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li>
<li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li>
<li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li>
</ul>
<p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p>
<p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p>
<ul data-end="505" data-start="374">
<li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li>
<li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li>
<li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li>
</ul>
<p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="258" data-start="113">
<li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li>
<li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li>
</ul>
<p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 100</code></li>
</ul>
|
Math
|
Python
|
class Solution:
def findClosest(self, x: int, y: int, z: int) -> int:
a = abs(x - z)
b = abs(y - z)
return 0 if a == b else (1 if a < b else 2)
|
3,516 |
Find Closest Person
|
Easy
|
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p>
<ul data-end="252" data-start="118">
<li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li>
<li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li>
<li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li>
</ul>
<p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p>
<p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p>
<ul data-end="505" data-start="374">
<li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li>
<li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li>
<li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li>
</ul>
<p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="258" data-start="113">
<li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li>
<li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li>
</ul>
<p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul data-end="245" data-start="92">
<li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li>
<li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li>
</ul>
<p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y, z <= 100</code></li>
</ul>
|
Math
|
TypeScript
|
function findClosest(x: number, y: number, z: number): number {
const a = Math.abs(x - z);
const b = Math.abs(y - z);
return a === b ? 0 : a < b ? 1 : 2;
}
|
3,522 |
Calculate Score After Performing Instructions
|
Medium
|
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p>
<p>You need to simulate a process based on the following rules:</p>
<ul>
<li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li>
<li>If <code>instructions[i]</code> is <code>"add"</code>:
<ul>
<li>Add <code>values[i]</code> to your score.</li>
<li>Move to the next instruction <code>(i + 1)</code>.</li>
</ul>
</li>
<li>If <code>instructions[i]</code> is <code>"jump"</code>:
<ul>
<li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li>
</ul>
</li>
</ul>
<p>The process ends when you either:</p>
<ul>
<li>Go out of bounds (i.e., <code>i < 0 or i >= n</code>), or</li>
<li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li>
</ul>
<p>Return your score at the end of the process.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 2 = 2</code>.</li>
<li>At index 2: Instruction is <code>"add"</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li>
<li>At index 3: Instruction is <code>"jump"</code>, move to index <code>3 + 1 = 4</code>.</li>
<li>At index 4: Instruction is <code>"add"</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li>
<li>At index 5: Instruction is <code>"jump"</code>, move to index <code>5 + (-3) = 2</code>.</li>
<li>At index 2: Already visited. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add"], values = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 3 = 3</code>.</li>
<li>At index 3: Out of bounds. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump"], values = [0]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 0 = 0</code>.</li>
<li>At index 0: Already visited. The process ends.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == instructions.length == values.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>instructions[i]</code> is either <code>"add"</code> or <code>"jump"</code>.</li>
<li><code>-10<sup>5</sup> <= values[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; String; Simulation
|
C++
|
class Solution {
public:
long long calculateScore(vector<string>& instructions, vector<int>& values) {
int n = values.size();
vector<bool> vis(n, false);
long long ans = 0;
int i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i][0] == 'a') {
ans += values[i];
i += 1;
} else {
i += values[i];
}
}
return ans;
}
};
|
3,522 |
Calculate Score After Performing Instructions
|
Medium
|
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p>
<p>You need to simulate a process based on the following rules:</p>
<ul>
<li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li>
<li>If <code>instructions[i]</code> is <code>"add"</code>:
<ul>
<li>Add <code>values[i]</code> to your score.</li>
<li>Move to the next instruction <code>(i + 1)</code>.</li>
</ul>
</li>
<li>If <code>instructions[i]</code> is <code>"jump"</code>:
<ul>
<li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li>
</ul>
</li>
</ul>
<p>The process ends when you either:</p>
<ul>
<li>Go out of bounds (i.e., <code>i < 0 or i >= n</code>), or</li>
<li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li>
</ul>
<p>Return your score at the end of the process.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 2 = 2</code>.</li>
<li>At index 2: Instruction is <code>"add"</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li>
<li>At index 3: Instruction is <code>"jump"</code>, move to index <code>3 + 1 = 4</code>.</li>
<li>At index 4: Instruction is <code>"add"</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li>
<li>At index 5: Instruction is <code>"jump"</code>, move to index <code>5 + (-3) = 2</code>.</li>
<li>At index 2: Already visited. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add"], values = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 3 = 3</code>.</li>
<li>At index 3: Out of bounds. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump"], values = [0]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 0 = 0</code>.</li>
<li>At index 0: Already visited. The process ends.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == instructions.length == values.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>instructions[i]</code> is either <code>"add"</code> or <code>"jump"</code>.</li>
<li><code>-10<sup>5</sup> <= values[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; String; Simulation
|
Go
|
func calculateScore(instructions []string, values []int) (ans int64) {
n := len(values)
vis := make([]bool, n)
i := 0
for i >= 0 && i < n && !vis[i] {
vis[i] = true
if instructions[i][0] == 'a' {
ans += int64(values[i])
i += 1
} else {
i += values[i]
}
}
return
}
|
3,522 |
Calculate Score After Performing Instructions
|
Medium
|
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p>
<p>You need to simulate a process based on the following rules:</p>
<ul>
<li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li>
<li>If <code>instructions[i]</code> is <code>"add"</code>:
<ul>
<li>Add <code>values[i]</code> to your score.</li>
<li>Move to the next instruction <code>(i + 1)</code>.</li>
</ul>
</li>
<li>If <code>instructions[i]</code> is <code>"jump"</code>:
<ul>
<li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li>
</ul>
</li>
</ul>
<p>The process ends when you either:</p>
<ul>
<li>Go out of bounds (i.e., <code>i < 0 or i >= n</code>), or</li>
<li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li>
</ul>
<p>Return your score at the end of the process.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 2 = 2</code>.</li>
<li>At index 2: Instruction is <code>"add"</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li>
<li>At index 3: Instruction is <code>"jump"</code>, move to index <code>3 + 1 = 4</code>.</li>
<li>At index 4: Instruction is <code>"add"</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li>
<li>At index 5: Instruction is <code>"jump"</code>, move to index <code>5 + (-3) = 2</code>.</li>
<li>At index 2: Already visited. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add"], values = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 3 = 3</code>.</li>
<li>At index 3: Out of bounds. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump"], values = [0]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 0 = 0</code>.</li>
<li>At index 0: Already visited. The process ends.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == instructions.length == values.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>instructions[i]</code> is either <code>"add"</code> or <code>"jump"</code>.</li>
<li><code>-10<sup>5</sup> <= values[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; String; Simulation
|
Java
|
class Solution {
public long calculateScore(String[] instructions, int[] values) {
int n = values.length;
boolean[] vis = new boolean[n];
long ans = 0;
int i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i].charAt(0) == 'a') {
ans += values[i];
i += 1;
} else {
i = i + values[i];
}
}
return ans;
}
}
|
3,522 |
Calculate Score After Performing Instructions
|
Medium
|
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p>
<p>You need to simulate a process based on the following rules:</p>
<ul>
<li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li>
<li>If <code>instructions[i]</code> is <code>"add"</code>:
<ul>
<li>Add <code>values[i]</code> to your score.</li>
<li>Move to the next instruction <code>(i + 1)</code>.</li>
</ul>
</li>
<li>If <code>instructions[i]</code> is <code>"jump"</code>:
<ul>
<li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li>
</ul>
</li>
</ul>
<p>The process ends when you either:</p>
<ul>
<li>Go out of bounds (i.e., <code>i < 0 or i >= n</code>), or</li>
<li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li>
</ul>
<p>Return your score at the end of the process.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 2 = 2</code>.</li>
<li>At index 2: Instruction is <code>"add"</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li>
<li>At index 3: Instruction is <code>"jump"</code>, move to index <code>3 + 1 = 4</code>.</li>
<li>At index 4: Instruction is <code>"add"</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li>
<li>At index 5: Instruction is <code>"jump"</code>, move to index <code>5 + (-3) = 2</code>.</li>
<li>At index 2: Already visited. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add"], values = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 3 = 3</code>.</li>
<li>At index 3: Out of bounds. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump"], values = [0]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 0 = 0</code>.</li>
<li>At index 0: Already visited. The process ends.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == instructions.length == values.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>instructions[i]</code> is either <code>"add"</code> or <code>"jump"</code>.</li>
<li><code>-10<sup>5</sup> <= values[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; String; Simulation
|
Python
|
class Solution:
def calculateScore(self, instructions: List[str], values: List[int]) -> int:
n = len(values)
vis = [False] * n
ans = i = 0
while 0 <= i < n and not vis[i]:
vis[i] = True
if instructions[i][0] == "a":
ans += values[i]
i += 1
else:
i = i + values[i]
return ans
|
3,522 |
Calculate Score After Performing Instructions
|
Medium
|
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p>
<p>You need to simulate a process based on the following rules:</p>
<ul>
<li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li>
<li>If <code>instructions[i]</code> is <code>"add"</code>:
<ul>
<li>Add <code>values[i]</code> to your score.</li>
<li>Move to the next instruction <code>(i + 1)</code>.</li>
</ul>
</li>
<li>If <code>instructions[i]</code> is <code>"jump"</code>:
<ul>
<li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li>
</ul>
</li>
</ul>
<p>The process ends when you either:</p>
<ul>
<li>Go out of bounds (i.e., <code>i < 0 or i >= n</code>), or</li>
<li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li>
</ul>
<p>Return your score at the end of the process.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 2 = 2</code>.</li>
<li>At index 2: Instruction is <code>"add"</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li>
<li>At index 3: Instruction is <code>"jump"</code>, move to index <code>3 + 1 = 4</code>.</li>
<li>At index 4: Instruction is <code>"add"</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li>
<li>At index 5: Instruction is <code>"jump"</code>, move to index <code>5 + (-3) = 2</code>.</li>
<li>At index 2: Already visited. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump","add","add"], values = [3,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 3 = 3</code>.</li>
<li>At index 3: Out of bounds. The process ends.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">instructions = ["jump"], values = [0]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Simulate the process starting at instruction 0:</p>
<ul>
<li>At index 0: Instruction is <code>"jump"</code>, move to index <code>0 + 0 = 0</code>.</li>
<li>At index 0: Already visited. The process ends.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == instructions.length == values.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>instructions[i]</code> is either <code>"add"</code> or <code>"jump"</code>.</li>
<li><code>-10<sup>5</sup> <= values[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; String; Simulation
|
TypeScript
|
function calculateScore(instructions: string[], values: number[]): number {
const n = values.length;
const vis: boolean[] = Array(n).fill(false);
let ans = 0;
let i = 0;
while (i >= 0 && i < n && !vis[i]) {
vis[i] = true;
if (instructions[i][0] === 'a') {
ans += values[i];
i += 1;
} else {
i += values[i];
}
}
return ans;
}
|
3,523 |
Make Array Non-decreasing
|
Medium
|
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p>
<p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to achieve the maximum size is:</p>
<ol>
<li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> → <code>[4, 5, 3, 5]</code>.</li>
<li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> → <code>[4, 5, 5]</code>.</li>
</ol>
<p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
C++
|
class Solution {
public:
int maximumPossibleSize(vector<int>& nums) {
int ans = 0, mx = 0;
for (int x : nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}
};
|
3,523 |
Make Array Non-decreasing
|
Medium
|
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p>
<p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to achieve the maximum size is:</p>
<ol>
<li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> → <code>[4, 5, 3, 5]</code>.</li>
<li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> → <code>[4, 5, 5]</code>.</li>
</ol>
<p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Go
|
func maximumPossibleSize(nums []int) int {
ans, mx := 0, 0
for _, x := range nums {
if mx <= x {
ans++
mx = x
}
}
return ans
}
|
3,523 |
Make Array Non-decreasing
|
Medium
|
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p>
<p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to achieve the maximum size is:</p>
<ol>
<li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> → <code>[4, 5, 3, 5]</code>.</li>
<li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> → <code>[4, 5, 5]</code>.</li>
</ol>
<p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Java
|
class Solution {
public int maximumPossibleSize(int[] nums) {
int ans = 0, mx = 0;
for (int x : nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}
}
|
3,523 |
Make Array Non-decreasing
|
Medium
|
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p>
<p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to achieve the maximum size is:</p>
<ol>
<li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> → <code>[4, 5, 3, 5]</code>.</li>
<li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> → <code>[4, 5, 5]</code>.</li>
</ol>
<p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Python
|
class Solution:
def maximumPossibleSize(self, nums: List[int]) -> int:
ans = mx = 0
for x in nums:
if mx <= x:
ans += 1
mx = x
return ans
|
3,523 |
Make Array Non-decreasing
|
Medium
|
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p>
<p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One way to achieve the maximum size is:</p>
<ol>
<li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> → <code>[4, 5, 3, 5]</code>.</li>
<li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> → <code>[4, 5, 5]</code>.</li>
</ol>
<p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 2 * 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
TypeScript
|
function maximumPossibleSize(nums: number[]): number {
let [ans, mx] = [0, 0];
for (const x of nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}
|
3,527 |
Find the Most Common Response
|
Medium
|
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p>
<p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"good"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list, <code>responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]</code>.</li>
<li><code>"good"</code> appears 3 times, <code>"ok"</code> appears 2 times, and <code>"bad"</code> appears 2 times.</li>
<li>Return <code>"good"</code> because it has the highest frequency.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"bad"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list we have <code>responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]</code>.</li>
<li><code>"bad"</code>, <code>"good"</code>, and <code>"ok"</code> each occur 2 times.</li>
<li>The output is <code>"bad"</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= responses.length <= 1000</code></li>
<li><code>1 <= responses[i].length <= 1000</code></li>
<li><code>1 <= responses[i][j].length <= 10</code></li>
<li><code>responses[i][j]</code> consists of only lowercase English letters</li>
</ul>
|
Array; Hash Table; String; Counting
|
C++
|
class Solution {
public:
string findCommonResponse(vector<vector<string>>& responses) {
unordered_map<string, int> cnt;
for (const auto& ws : responses) {
unordered_set<string> s;
for (const auto& w : ws) {
if (s.insert(w).second) {
++cnt[w];
}
}
}
string ans = responses[0][0];
for (const auto& e : cnt) {
const string& w = e.first;
int v = e.second;
if (cnt[ans] < v || (cnt[ans] == v && w < ans)) {
ans = w;
}
}
return ans;
}
};
|
3,527 |
Find the Most Common Response
|
Medium
|
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p>
<p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"good"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list, <code>responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]</code>.</li>
<li><code>"good"</code> appears 3 times, <code>"ok"</code> appears 2 times, and <code>"bad"</code> appears 2 times.</li>
<li>Return <code>"good"</code> because it has the highest frequency.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"bad"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list we have <code>responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]</code>.</li>
<li><code>"bad"</code>, <code>"good"</code>, and <code>"ok"</code> each occur 2 times.</li>
<li>The output is <code>"bad"</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= responses.length <= 1000</code></li>
<li><code>1 <= responses[i].length <= 1000</code></li>
<li><code>1 <= responses[i][j].length <= 10</code></li>
<li><code>responses[i][j]</code> consists of only lowercase English letters</li>
</ul>
|
Array; Hash Table; String; Counting
|
Go
|
func findCommonResponse(responses [][]string) string {
cnt := map[string]int{}
for _, ws := range responses {
s := map[string]struct{}{}
for _, w := range ws {
if _, ok := s[w]; !ok {
s[w] = struct{}{}
cnt[w]++
}
}
}
ans := responses[0][0]
for w, v := range cnt {
if cnt[ans] < v || (cnt[ans] == v && w < ans) {
ans = w
}
}
return ans
}
|
3,527 |
Find the Most Common Response
|
Medium
|
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p>
<p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"good"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list, <code>responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]</code>.</li>
<li><code>"good"</code> appears 3 times, <code>"ok"</code> appears 2 times, and <code>"bad"</code> appears 2 times.</li>
<li>Return <code>"good"</code> because it has the highest frequency.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"bad"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list we have <code>responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]</code>.</li>
<li><code>"bad"</code>, <code>"good"</code>, and <code>"ok"</code> each occur 2 times.</li>
<li>The output is <code>"bad"</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= responses.length <= 1000</code></li>
<li><code>1 <= responses[i].length <= 1000</code></li>
<li><code>1 <= responses[i][j].length <= 10</code></li>
<li><code>responses[i][j]</code> consists of only lowercase English letters</li>
</ul>
|
Array; Hash Table; String; Counting
|
Java
|
class Solution {
public String findCommonResponse(List<List<String>> responses) {
Map<String, Integer> cnt = new HashMap<>();
for (var ws : responses) {
Set<String> s = new HashSet<>();
for (var w : ws) {
if (s.add(w)) {
cnt.merge(w, 1, Integer::sum);
}
}
}
String ans = responses.get(0).get(0);
for (var e : cnt.entrySet()) {
String w = e.getKey();
int v = e.getValue();
if (cnt.get(ans) < v || (cnt.get(ans) == v && w.compareTo(ans) < 0)) {
ans = w;
}
}
return ans;
}
}
|
3,527 |
Find the Most Common Response
|
Medium
|
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p>
<p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"good"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list, <code>responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]</code>.</li>
<li><code>"good"</code> appears 3 times, <code>"ok"</code> appears 2 times, and <code>"bad"</code> appears 2 times.</li>
<li>Return <code>"good"</code> because it has the highest frequency.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"bad"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list we have <code>responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]</code>.</li>
<li><code>"bad"</code>, <code>"good"</code>, and <code>"ok"</code> each occur 2 times.</li>
<li>The output is <code>"bad"</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= responses.length <= 1000</code></li>
<li><code>1 <= responses[i].length <= 1000</code></li>
<li><code>1 <= responses[i][j].length <= 10</code></li>
<li><code>responses[i][j]</code> consists of only lowercase English letters</li>
</ul>
|
Array; Hash Table; String; Counting
|
Python
|
class Solution:
def findCommonResponse(self, responses: List[List[str]]) -> str:
cnt = Counter()
for ws in responses:
for w in set(ws):
cnt[w] += 1
ans = responses[0][0]
for w, x in cnt.items():
if cnt[ans] < x or (cnt[ans] == x and w < ans):
ans = w
return ans
|
3,527 |
Find the Most Common Response
|
Medium
|
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p>
<p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"good"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list, <code>responses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]</code>.</li>
<li><code>"good"</code> appears 3 times, <code>"ok"</code> appears 2 times, and <code>"bad"</code> appears 2 times.</li>
<li>Return <code>"good"</code> because it has the highest frequency.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">"bad"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>After removing duplicates within each list we have <code>responses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]</code>.</li>
<li><code>"bad"</code>, <code>"good"</code>, and <code>"ok"</code> each occur 2 times.</li>
<li>The output is <code>"bad"</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= responses.length <= 1000</code></li>
<li><code>1 <= responses[i].length <= 1000</code></li>
<li><code>1 <= responses[i][j].length <= 10</code></li>
<li><code>responses[i][j]</code> consists of only lowercase English letters</li>
</ul>
|
Array; Hash Table; String; Counting
|
TypeScript
|
function findCommonResponse(responses: string[][]): string {
const cnt = new Map<string, number>();
for (const ws of responses) {
const s = new Set<string>();
for (const w of ws) {
if (!s.has(w)) {
s.add(w);
cnt.set(w, (cnt.get(w) ?? 0) + 1);
}
}
}
let ans = responses[0][0];
for (const [w, v] of cnt) {
const best = cnt.get(ans)!;
if (best < v || (best === v && w < ans)) {
ans = w;
}
}
return ans;
}
|
3,528 |
Unit Conversion I
|
Medium
|
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p>
<p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li>
<li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li>
<li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li>
<li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li>
<li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>conversions.length == n - 1</code></li>
<li><code>0 <= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> < n</code></li>
<li><code>1 <= conversionFactor<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
C++
|
class Solution {
public:
vector<int> baseUnitConversions(vector<vector<int>>& conversions) {
const int mod = 1e9 + 7;
int n = conversions.size() + 1;
vector<vector<pair<int, int>>> g(n);
vector<int> ans(n);
for (const auto& e : conversions) {
g[e[0]].push_back({e[1], e[2]});
}
auto dfs = [&](this auto&& dfs, int s, long long mul) -> void {
ans[s] = mul;
for (auto [t, w] : g[s]) {
dfs(t, mul * w % mod);
}
};
dfs(0, 1);
return ans;
}
};
|
3,528 |
Unit Conversion I
|
Medium
|
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p>
<p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li>
<li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li>
<li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li>
<li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li>
<li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>conversions.length == n - 1</code></li>
<li><code>0 <= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> < n</code></li>
<li><code>1 <= conversionFactor<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Go
|
func baseUnitConversions(conversions [][]int) []int {
const mod = int(1e9 + 7)
n := len(conversions) + 1
g := make([][]struct{ t, w int }, n)
for _, e := range conversions {
s, t, w := e[0], e[1], e[2]
g[s] = append(g[s], struct{ t, w int }{t, w})
}
ans := make([]int, n)
var dfs func(s int, mul int)
dfs = func(s int, mul int) {
ans[s] = mul
for _, e := range g[s] {
dfs(e.t, mul*e.w%mod)
}
}
dfs(0, 1)
return ans
}
|
3,528 |
Unit Conversion I
|
Medium
|
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p>
<p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li>
<li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li>
<li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li>
<li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li>
<li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>conversions.length == n - 1</code></li>
<li><code>0 <= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> < n</code></li>
<li><code>1 <= conversionFactor<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Java
|
class Solution {
private final int mod = (int) 1e9 + 7;
private List<int[]>[] g;
private int[] ans;
private int n;
public int[] baseUnitConversions(int[][] conversions) {
n = conversions.length + 1;
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
ans = new int[n];
for (var e : conversions) {
g[e[0]].add(new int[] {e[1], e[2]});
}
dfs(0, 1);
return ans;
}
private void dfs(int s, long mul) {
ans[s] = (int) mul;
for (var e : g[s]) {
dfs(e[0], mul * e[1] % mod);
}
}
}
|
3,528 |
Unit Conversion I
|
Medium
|
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p>
<p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li>
<li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li>
<li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li>
<li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li>
<li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>conversions.length == n - 1</code></li>
<li><code>0 <= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> < n</code></li>
<li><code>1 <= conversionFactor<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
Python
|
class Solution:
def baseUnitConversions(self, conversions: List[List[int]]) -> List[int]:
def dfs(s: int, mul: int) -> None:
ans[s] = mul
for t, w in g[s]:
dfs(t, mul * w % mod)
mod = 10**9 + 7
n = len(conversions) + 1
g = [[] for _ in range(n)]
for s, t, w in conversions:
g[s].append((t, w))
ans = [0] * n
dfs(0, 1)
return ans
|
3,528 |
Unit Conversion I
|
Medium
|
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p>
<p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li>
<li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li>
<li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li>
<li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li>
<li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li>
<li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li>
<li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>conversions.length == n - 1</code></li>
<li><code>0 <= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> < n</code></li>
<li><code>1 <= conversionFactor<sub>i</sub> <= 10<sup>9</sup></code></li>
<li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph
|
TypeScript
|
function baseUnitConversions(conversions: number[][]): number[] {
const mod = BigInt(1e9 + 7);
const n = conversions.length + 1;
const g: { t: number; w: number }[][] = Array.from({ length: n }, () => []);
for (const [s, t, w] of conversions) {
g[s].push({ t, w });
}
const ans: number[] = Array(n).fill(0);
const dfs = (s: number, mul: number) => {
ans[s] = mul;
for (const { t, w } of g[s]) {
dfs(t, Number((BigInt(mul) * BigInt(w)) % mod));
}
};
dfs(0, 1);
return ans;
}
|
3,531 |
Count Covered Buildings
|
Medium
|
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p>
<p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p>
<p>Return the number of <strong>covered</strong> buildings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[2,2]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,2]</code>)</li>
<li>below (<code>[3,2]</code>)</li>
<li>left (<code>[2,1]</code>)</li>
<li>right (<code>[2,3]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>No building has at least one building in all four directions.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[3,3]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,3]</code>)</li>
<li>below (<code>[5,3]</code>)</li>
<li>left (<code>[3,2]</code>)</li>
<li>right (<code>[3,5]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= buildings.length <= 10<sup>5</sup> </code></li>
<li><code>buildings[i] = [x, y]</code></li>
<li><code>1 <= x, y <= n</code></li>
<li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li>
</ul>
|
Array; Hash Table; Sorting
|
C++
|
class Solution {
public:
int countCoveredBuildings(int n, vector<vector<int>>& buildings) {
unordered_map<int, vector<int>> g1;
unordered_map<int, vector<int>> g2;
for (const auto& building : buildings) {
int x = building[0], y = building[1];
g1[x].push_back(y);
g2[y].push_back(x);
}
for (auto& e : g1) {
sort(e.second.begin(), e.second.end());
}
for (auto& e : g2) {
sort(e.second.begin(), e.second.end());
}
int ans = 0;
for (const auto& building : buildings) {
int x = building[0], y = building[1];
const vector<int>& l1 = g1[x];
const vector<int>& l2 = g2[y];
if (l2[0] < x && x < l2[l2.size() - 1] && l1[0] < y && y < l1[l1.size() - 1]) {
ans++;
}
}
return ans;
}
};
|
3,531 |
Count Covered Buildings
|
Medium
|
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p>
<p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p>
<p>Return the number of <strong>covered</strong> buildings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[2,2]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,2]</code>)</li>
<li>below (<code>[3,2]</code>)</li>
<li>left (<code>[2,1]</code>)</li>
<li>right (<code>[2,3]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>No building has at least one building in all four directions.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[3,3]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,3]</code>)</li>
<li>below (<code>[5,3]</code>)</li>
<li>left (<code>[3,2]</code>)</li>
<li>right (<code>[3,5]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= buildings.length <= 10<sup>5</sup> </code></li>
<li><code>buildings[i] = [x, y]</code></li>
<li><code>1 <= x, y <= n</code></li>
<li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li>
</ul>
|
Array; Hash Table; Sorting
|
Go
|
func countCoveredBuildings(n int, buildings [][]int) (ans int) {
g1 := make(map[int][]int)
g2 := make(map[int][]int)
for _, building := range buildings {
x, y := building[0], building[1]
g1[x] = append(g1[x], y)
g2[y] = append(g2[y], x)
}
for _, list := range g1 {
sort.Ints(list)
}
for _, list := range g2 {
sort.Ints(list)
}
for _, building := range buildings {
x, y := building[0], building[1]
l1 := g1[x]
l2 := g2[y]
if l2[0] < x && x < l2[len(l2)-1] && l1[0] < y && y < l1[len(l1)-1] {
ans++
}
}
return
}
|
3,531 |
Count Covered Buildings
|
Medium
|
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p>
<p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p>
<p>Return the number of <strong>covered</strong> buildings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[2,2]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,2]</code>)</li>
<li>below (<code>[3,2]</code>)</li>
<li>left (<code>[2,1]</code>)</li>
<li>right (<code>[2,3]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>No building has at least one building in all four directions.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[3,3]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,3]</code>)</li>
<li>below (<code>[5,3]</code>)</li>
<li>left (<code>[3,2]</code>)</li>
<li>right (<code>[3,5]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= buildings.length <= 10<sup>5</sup> </code></li>
<li><code>buildings[i] = [x, y]</code></li>
<li><code>1 <= x, y <= n</code></li>
<li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li>
</ul>
|
Array; Hash Table; Sorting
|
Java
|
class Solution {
public int countCoveredBuildings(int n, int[][] buildings) {
Map<Integer, List<Integer>> g1 = new HashMap<>();
Map<Integer, List<Integer>> g2 = new HashMap<>();
for (int[] building : buildings) {
int x = building[0], y = building[1];
g1.computeIfAbsent(x, k -> new ArrayList<>()).add(y);
g2.computeIfAbsent(y, k -> new ArrayList<>()).add(x);
}
for (var e : g1.entrySet()) {
Collections.sort(e.getValue());
}
for (var e : g2.entrySet()) {
Collections.sort(e.getValue());
}
int ans = 0;
for (int[] building : buildings) {
int x = building[0], y = building[1];
List<Integer> l1 = g1.get(x);
List<Integer> l2 = g2.get(y);
if (l2.get(0) < x && x < l2.get(l2.size() - 1) && l1.get(0) < y
&& y < l1.get(l1.size() - 1)) {
ans++;
}
}
return ans;
}
}
|
3,531 |
Count Covered Buildings
|
Medium
|
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p>
<p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p>
<p>Return the number of <strong>covered</strong> buildings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[2,2]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,2]</code>)</li>
<li>below (<code>[3,2]</code>)</li>
<li>left (<code>[2,1]</code>)</li>
<li>right (<code>[2,3]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>No building has at least one building in all four directions.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[3,3]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,3]</code>)</li>
<li>below (<code>[5,3]</code>)</li>
<li>left (<code>[3,2]</code>)</li>
<li>right (<code>[3,5]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= buildings.length <= 10<sup>5</sup> </code></li>
<li><code>buildings[i] = [x, y]</code></li>
<li><code>1 <= x, y <= n</code></li>
<li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li>
</ul>
|
Array; Hash Table; Sorting
|
Python
|
class Solution:
def countCoveredBuildings(self, n: int, buildings: List[List[int]]) -> int:
g1 = defaultdict(list)
g2 = defaultdict(list)
for x, y in buildings:
g1[x].append(y)
g2[y].append(x)
for x in g1:
g1[x].sort()
for y in g2:
g2[y].sort()
ans = 0
for x, y in buildings:
l1 = g1[x]
l2 = g2[y]
if l2[0] < x < l2[-1] and l1[0] < y < l1[-1]:
ans += 1
return ans
|
3,531 |
Count Covered Buildings
|
Medium
|
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p>
<p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p>
<p>Return the number of <strong>covered</strong> buildings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[2,2]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,2]</code>)</li>
<li>below (<code>[3,2]</code>)</li>
<li>left (<code>[2,1]</code>)</li>
<li>right (<code>[2,3]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>No building has at least one building in all four directions.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Only building <code>[3,3]</code> is covered as it has at least one building:
<ul>
<li>above (<code>[1,3]</code>)</li>
<li>below (<code>[5,3]</code>)</li>
<li>left (<code>[3,2]</code>)</li>
<li>right (<code>[3,5]</code>)</li>
</ul>
</li>
<li>Thus, the count of covered buildings is 1.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= buildings.length <= 10<sup>5</sup> </code></li>
<li><code>buildings[i] = [x, y]</code></li>
<li><code>1 <= x, y <= n</code></li>
<li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li>
</ul>
|
Array; Hash Table; Sorting
|
TypeScript
|
function countCoveredBuildings(n: number, buildings: number[][]): number {
const g1: Map<number, number[]> = new Map();
const g2: Map<number, number[]> = new Map();
for (const [x, y] of buildings) {
if (!g1.has(x)) g1.set(x, []);
g1.get(x)?.push(y);
if (!g2.has(y)) g2.set(y, []);
g2.get(y)?.push(x);
}
for (const list of g1.values()) {
list.sort((a, b) => a - b);
}
for (const list of g2.values()) {
list.sort((a, b) => a - b);
}
let ans = 0;
for (const [x, y] of buildings) {
const l1 = g1.get(x)!;
const l2 = g2.get(y)!;
if (l2[0] < x && x < l2[l2.length - 1] && l1[0] < y && y < l1[l1.length - 1]) {
ans++;
}
}
return ans;
}
|
3,532 |
Path Existence Queries in a Graph I
|
Medium
|
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p>
<p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p>
<p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| <= maxDiff</code>).</p>
<p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[true,false]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p>
<p><strong>Explanation:</strong></p>
<p>The resulting graph is:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p>
<ul>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li>
<li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>0 <= maxDiff <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
</ul>
|
Union Find; Graph; Array; Hash Table; Binary Search
|
C++
|
class Solution {
public:
vector<bool> pathExistenceQueries(int n, vector<int>& nums, int maxDiff, vector<vector<int>>& queries) {
vector<int> g(n);
int cnt = 0;
for (int i = 1; i < n; ++i) {
if (nums[i] - nums[i - 1] > maxDiff) {
++cnt;
}
g[i] = cnt;
}
vector<bool> ans;
for (const auto& q : queries) {
int u = q[0], v = q[1];
ans.push_back(g[u] == g[v]);
}
return ans;
}
};
|
3,532 |
Path Existence Queries in a Graph I
|
Medium
|
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p>
<p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p>
<p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| <= maxDiff</code>).</p>
<p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[true,false]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p>
<p><strong>Explanation:</strong></p>
<p>The resulting graph is:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p>
<ul>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li>
<li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>0 <= maxDiff <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
</ul>
|
Union Find; Graph; Array; Hash Table; Binary Search
|
Go
|
func pathExistenceQueries(n int, nums []int, maxDiff int, queries [][]int) (ans []bool) {
g := make([]int, n)
cnt := 0
for i := 1; i < n; i++ {
if nums[i]-nums[i-1] > maxDiff {
cnt++
}
g[i] = cnt
}
for _, q := range queries {
u, v := q[0], q[1]
ans = append(ans, g[u] == g[v])
}
return
}
|
3,532 |
Path Existence Queries in a Graph I
|
Medium
|
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p>
<p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p>
<p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| <= maxDiff</code>).</p>
<p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[true,false]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p>
<p><strong>Explanation:</strong></p>
<p>The resulting graph is:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p>
<ul>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li>
<li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>0 <= maxDiff <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
</ul>
|
Union Find; Graph; Array; Hash Table; Binary Search
|
Java
|
class Solution {
public boolean[] pathExistenceQueries(int n, int[] nums, int maxDiff, int[][] queries) {
int[] g = new int[n];
int cnt = 0;
for (int i = 1; i < n; ++i) {
if (nums[i] - nums[i - 1] > maxDiff) {
cnt++;
}
g[i] = cnt;
}
int m = queries.length;
boolean[] ans = new boolean[m];
for (int i = 0; i < m; ++i) {
int u = queries[i][0];
int v = queries[i][1];
ans[i] = g[u] == g[v];
}
return ans;
}
}
|
3,532 |
Path Existence Queries in a Graph I
|
Medium
|
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p>
<p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p>
<p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| <= maxDiff</code>).</p>
<p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[true,false]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p>
<p><strong>Explanation:</strong></p>
<p>The resulting graph is:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p>
<ul>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li>
<li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>0 <= maxDiff <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
</ul>
|
Union Find; Graph; Array; Hash Table; Binary Search
|
Python
|
class Solution:
def pathExistenceQueries(
self, n: int, nums: List[int], maxDiff: int, queries: List[List[int]]
) -> List[bool]:
g = [0] * n
cnt = 0
for i in range(1, n):
if nums[i] - nums[i - 1] > maxDiff:
cnt += 1
g[i] = cnt
return [g[u] == g[v] for u, v in queries]
|
3,532 |
Path Existence Queries in a Graph I
|
Medium
|
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p>
<p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p>
<p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| <= maxDiff</code>).</p>
<p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p>
<p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[true,false]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p>
<p><strong>Explanation:</strong></p>
<p>The resulting graph is:</p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p>
<ul>
<li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li>
<li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li>
<li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li>
<li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>0 <= maxDiff <= 10<sup>5</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> < n</code></li>
</ul>
|
Union Find; Graph; Array; Hash Table; Binary Search
|
TypeScript
|
function pathExistenceQueries(
n: number,
nums: number[],
maxDiff: number,
queries: number[][],
): boolean[] {
const g: number[] = Array(n).fill(0);
let cnt = 0;
for (let i = 1; i < n; ++i) {
if (nums[i] - nums[i - 1] > maxDiff) {
++cnt;
}
g[i] = cnt;
}
return queries.map(([u, v]) => g[u] === g[v]);
}
|
3,536 |
Maximum Product of Two Digits
|
Easy
|
<p>You are given a positive integer <code>n</code>.</p>
<p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p>
<p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 31</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[3, 1]</code>.</li>
<li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li>
<li>The maximum product is 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 22</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[2, 2]</code>.</li>
<li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li>
<li>The maximum product is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 124</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li>
<li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li>
<li>The maximum product is 8.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>10 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Math; Sorting
|
C++
|
class Solution {
public:
int maxProduct(int n) {
int a = 0, b = 0;
for (; n; n /= 10) {
int x = n % 10;
if (a < x) {
b = a;
a = x;
} else if (b < x) {
b = x;
}
}
return a * b;
}
};
|
3,536 |
Maximum Product of Two Digits
|
Easy
|
<p>You are given a positive integer <code>n</code>.</p>
<p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p>
<p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 31</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[3, 1]</code>.</li>
<li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li>
<li>The maximum product is 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 22</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[2, 2]</code>.</li>
<li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li>
<li>The maximum product is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 124</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li>
<li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li>
<li>The maximum product is 8.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>10 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Math; Sorting
|
Go
|
func maxProduct(n int) int {
a, b := 0, 0
for ; n > 0; n /= 10 {
x := n % 10
if a < x {
b, a = a, x
} else if b < x {
b = x
}
}
return a * b
}
|
3,536 |
Maximum Product of Two Digits
|
Easy
|
<p>You are given a positive integer <code>n</code>.</p>
<p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p>
<p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 31</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[3, 1]</code>.</li>
<li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li>
<li>The maximum product is 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 22</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[2, 2]</code>.</li>
<li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li>
<li>The maximum product is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 124</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li>
<li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li>
<li>The maximum product is 8.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>10 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Math; Sorting
|
Java
|
class Solution {
public int maxProduct(int n) {
int a = 0, b = 0;
for (; n > 0; n /= 10) {
int x = n % 10;
if (a < x) {
b = a;
a = x;
} else if (b < x) {
b = x;
}
}
return a * b;
}
}
|
3,536 |
Maximum Product of Two Digits
|
Easy
|
<p>You are given a positive integer <code>n</code>.</p>
<p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p>
<p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 31</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[3, 1]</code>.</li>
<li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li>
<li>The maximum product is 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 22</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[2, 2]</code>.</li>
<li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li>
<li>The maximum product is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 124</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li>
<li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li>
<li>The maximum product is 8.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>10 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Math; Sorting
|
Python
|
class Solution:
def maxProduct(self, n: int) -> int:
a = b = 0
while n:
n, x = divmod(n, 10)
if a < x:
a, b = x, a
elif b < x:
b = x
return a * b
|
3,536 |
Maximum Product of Two Digits
|
Easy
|
<p>You are given a positive integer <code>n</code>.</p>
<p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p>
<p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 31</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[3, 1]</code>.</li>
<li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li>
<li>The maximum product is 3.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 22</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[2, 2]</code>.</li>
<li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li>
<li>The maximum product is 4.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 124</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li>
<li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li>
<li>The maximum product is 8.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>10 <= n <= 10<sup>9</sup></code></li>
</ul>
|
Math; Sorting
|
TypeScript
|
function maxProduct(n: number): number {
let [a, b] = [0, 0];
for (; n; n = Math.floor(n / 10)) {
const x = n % 10;
if (a < x) {
[a, b] = [x, a];
} else if (b < x) {
b = x;
}
}
return a * b;
}
|
3,541 |
Find Most Frequent Vowel and Consonant
|
Easy
|
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>'a'</code> to <code>'z'</code>). </p>
<p>Your task is to:</p>
<ul>
<li>Find the vowel (one of <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, or <code>'u'</code>) with the <strong>maximum</strong> frequency.</li>
<li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li>
</ul>
<p>Return the sum of the two frequencies.</p>
<p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p>
The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "successes"</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'u'</code> (frequency 1), <code>'e'</code> (frequency 2). The maximum frequency is 2.</li>
<li>The consonants are: <code>'s'</code> (frequency 4), <code>'c'</code> (frequency 2). The maximum frequency is 4.</li>
<li>The output is <code>2 + 4 = 6</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aeiaeia"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'a'</code> (frequency 3), <code>'e'</code> ( frequency 2), <code>'i'</code> (frequency 2). The maximum frequency is 3.</li>
<li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li>
<li>The output is <code>3 + 0 = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
Hash Table; String; Counting
|
C++
|
class Solution {
public:
int maxFreqSum(string s) {
int cnt[26]{};
for (char c : s) {
++cnt[c - 'a'];
}
int a = 0, b = 0;
for (int i = 0; i < 26; ++i) {
char c = 'a' + i;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
a = max(a, cnt[i]);
} else {
b = max(b, cnt[i]);
}
}
return a + b;
}
};
|
3,541 |
Find Most Frequent Vowel and Consonant
|
Easy
|
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>'a'</code> to <code>'z'</code>). </p>
<p>Your task is to:</p>
<ul>
<li>Find the vowel (one of <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, or <code>'u'</code>) with the <strong>maximum</strong> frequency.</li>
<li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li>
</ul>
<p>Return the sum of the two frequencies.</p>
<p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p>
The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "successes"</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'u'</code> (frequency 1), <code>'e'</code> (frequency 2). The maximum frequency is 2.</li>
<li>The consonants are: <code>'s'</code> (frequency 4), <code>'c'</code> (frequency 2). The maximum frequency is 4.</li>
<li>The output is <code>2 + 4 = 6</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aeiaeia"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'a'</code> (frequency 3), <code>'e'</code> ( frequency 2), <code>'i'</code> (frequency 2). The maximum frequency is 3.</li>
<li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li>
<li>The output is <code>3 + 0 = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
Hash Table; String; Counting
|
Go
|
func maxFreqSum(s string) int {
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
a, b := 0, 0
for i := range cnt {
c := byte(i + 'a')
if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' {
a = max(a, cnt[i])
} else {
b = max(b, cnt[i])
}
}
return a + b
}
|
3,541 |
Find Most Frequent Vowel and Consonant
|
Easy
|
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>'a'</code> to <code>'z'</code>). </p>
<p>Your task is to:</p>
<ul>
<li>Find the vowel (one of <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, or <code>'u'</code>) with the <strong>maximum</strong> frequency.</li>
<li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li>
</ul>
<p>Return the sum of the two frequencies.</p>
<p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p>
The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "successes"</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'u'</code> (frequency 1), <code>'e'</code> (frequency 2). The maximum frequency is 2.</li>
<li>The consonants are: <code>'s'</code> (frequency 4), <code>'c'</code> (frequency 2). The maximum frequency is 4.</li>
<li>The output is <code>2 + 4 = 6</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aeiaeia"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The vowels are: <code>'a'</code> (frequency 3), <code>'e'</code> ( frequency 2), <code>'i'</code> (frequency 2). The maximum frequency is 3.</li>
<li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li>
<li>The output is <code>3 + 0 = 3</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
Hash Table; String; Counting
|
Java
|
class Solution {
public int maxFreqSum(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
int a = 0, b = 0;
for (int i = 0; i < cnt.length; ++i) {
char c = (char) (i + 'a');
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
a = Math.max(a, cnt[i]);
} else {
b = Math.max(b, cnt[i]);
}
}
return a + b;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.