id
int64 1
3.65k
| 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,445 |
Maximum Difference Between Even and Odd Frequency II
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p>
<ul>
<li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li>
<li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li>
<li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li>
</ul>
<p>Return the <strong>maximum</strong> difference.</p>
<p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "12233", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>For the substring <code>"12233"</code>, the frequency of <code>'1'</code> is 1 and the frequency of <code>'3'</code> is 2. The difference is <code>1 - 2 = -1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1122211", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>For the substring <code>"11222"</code>, the frequency of <code>'2'</code> is 3 and the frequency of <code>'1'</code> is 2. The difference is <code>3 - 2 = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "110", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 3 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of digits <code>'0'</code> to <code>'4'</code>.</li>
<li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Enumeration; Prefix Sum; Sliding Window
|
Rust
|
use std::cmp::{max, min};
use std::i32::{MAX, MIN};
impl Solution {
pub fn max_difference(S: String, k: i32) -> i32 {
let s: Vec<usize> = S
.chars()
.map(|c| c.to_digit(10).unwrap() as usize)
.collect();
let k = k as usize;
let mut ans = MIN;
for a in 0..5 {
for b in 0..5 {
if a == b {
continue;
}
let mut curA = 0;
let mut curB = 0;
let mut preA = 0;
let mut preB = 0;
let mut t = [[MAX; 2]; 2];
let mut l: isize = -1;
for (r, &x) in s.iter().enumerate() {
curA += (x == a) as i32;
curB += (x == b) as i32;
while (r as isize - l) as usize >= k && curB - preB >= 2 {
let i = (preA & 1) as usize;
let j = (preB & 1) as usize;
t[i][j] = min(t[i][j], preA - preB);
l += 1;
if l >= 0 {
preA += (s[l as usize] == a) as i32;
preB += (s[l as usize] == b) as i32;
}
}
let i = (curA & 1 ^ 1) as usize;
let j = (curB & 1) as usize;
if t[i][j] != MAX {
ans = max(ans, curA - curB - t[i][j]);
}
}
}
}
ans
}
}
|
3,445 |
Maximum Difference Between Even and Odd Frequency II
|
Hard
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Your task is to find the <strong>maximum</strong> difference between the frequency of <strong>two</strong> characters, <code>freq[a] - freq[b]</code>, in a <span data-keyword="substring">substring</span> <code>subs</code> of <code>s</code>, such that:</p>
<ul>
<li><code>subs</code> has a size of <strong>at least</strong> <code>k</code>.</li>
<li>Character <code>a</code> has an <em>odd frequency</em> in <code>subs</code>.</li>
<li>Character <code>b</code> has a <strong>non-zero</strong> <em>even frequency</em> in <code>subs</code>.</li>
</ul>
<p>Return the <strong>maximum</strong> difference.</p>
<p><strong>Note</strong> that <code>subs</code> can contain more than 2 <strong>distinct</strong> characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "12233", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>For the substring <code>"12233"</code>, the frequency of <code>'1'</code> is 1 and the frequency of <code>'3'</code> is 2. The difference is <code>1 - 2 = -1</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1122211", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>For the substring <code>"11222"</code>, the frequency of <code>'2'</code> is 3 and the frequency of <code>'1'</code> is 2. The difference is <code>3 - 2 = 1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "110", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 3 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of digits <code>'0'</code> to <code>'4'</code>.</li>
<li>The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.</li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Enumeration; Prefix Sum; Sliding Window
|
TypeScript
|
function maxDifference(S: string, k: number): number {
const s = S.split('').map(Number);
let ans = -Infinity;
for (let a = 0; a < 5; a++) {
for (let b = 0; b < 5; b++) {
if (a === b) {
continue;
}
let [curA, curB, preA, preB] = [0, 0, 0, 0];
const t: number[][] = [
[Infinity, Infinity],
[Infinity, Infinity],
];
let l = -1;
for (let r = 0; r < s.length; r++) {
const x = s[r];
curA += x === a ? 1 : 0;
curB += x === b ? 1 : 0;
while (r - l >= k && curB - preB >= 2) {
t[preA & 1][preB & 1] = Math.min(t[preA & 1][preB & 1], preA - preB);
l++;
preA += s[l] === a ? 1 : 0;
preB += s[l] === b ? 1 : 0;
}
ans = Math.max(ans, curA - curB - t[(curA & 1) ^ 1][curB & 1]);
}
}
}
return ans;
}
|
3,446 |
Sort Matrix by Diagonals
|
Medium
|
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p>
<ul>
<li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li>
<li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p>
<p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p>
<ul>
<li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li>
<li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li>
</ul>
<p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p>
<ul>
<li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li>
<li><code>[3]</code> remains unchanged.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p>
<p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[1]]</span></p>
<p><strong>Explanation:</strong></p>
<p>Diagonals with exactly one element are already in order, so no changes are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>grid.length == grid[i].length == n</code></li>
<li><code>1 <= n <= 10</code></li>
<li><code>-10<sup>5</sup> <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Sorting
|
C++
|
class Solution {
public:
vector<vector<int>> sortMatrix(vector<vector<int>>& grid) {
int n = grid.size();
for (int k = n - 2; k >= 0; --k) {
int i = k, j = 0;
vector<int> t;
while (i < n && j < n) {
t.push_back(grid[i++][j++]);
}
ranges::sort(t);
for (int x : t) {
grid[--i][--j] = x;
}
}
for (int k = n - 2; k > 0; --k) {
int i = k, j = n - 1;
vector<int> t;
while (i >= 0 && j >= 0) {
t.push_back(grid[i--][j--]);
}
ranges::sort(t);
for (int x : t) {
grid[++i][++j] = x;
}
}
return grid;
}
};
|
3,446 |
Sort Matrix by Diagonals
|
Medium
|
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p>
<ul>
<li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li>
<li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p>
<p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p>
<ul>
<li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li>
<li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li>
</ul>
<p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p>
<ul>
<li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li>
<li><code>[3]</code> remains unchanged.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p>
<p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[1]]</span></p>
<p><strong>Explanation:</strong></p>
<p>Diagonals with exactly one element are already in order, so no changes are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>grid.length == grid[i].length == n</code></li>
<li><code>1 <= n <= 10</code></li>
<li><code>-10<sup>5</sup> <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Sorting
|
Go
|
func sortMatrix(grid [][]int) [][]int {
n := len(grid)
for k := n - 2; k >= 0; k-- {
i, j := k, 0
t := []int{}
for ; i < n && j < n; i, j = i+1, j+1 {
t = append(t, grid[i][j])
}
sort.Ints(t)
for _, x := range t {
i, j = i-1, j-1
grid[i][j] = x
}
}
for k := n - 2; k > 0; k-- {
i, j := k, n-1
t := []int{}
for ; i >= 0 && j >= 0; i, j = i-1, j-1 {
t = append(t, grid[i][j])
}
sort.Ints(t)
for _, x := range t {
i, j = i+1, j+1
grid[i][j] = x
}
}
return grid
}
|
3,446 |
Sort Matrix by Diagonals
|
Medium
|
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p>
<ul>
<li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li>
<li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p>
<p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p>
<ul>
<li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li>
<li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li>
</ul>
<p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p>
<ul>
<li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li>
<li><code>[3]</code> remains unchanged.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p>
<p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[1]]</span></p>
<p><strong>Explanation:</strong></p>
<p>Diagonals with exactly one element are already in order, so no changes are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>grid.length == grid[i].length == n</code></li>
<li><code>1 <= n <= 10</code></li>
<li><code>-10<sup>5</sup> <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Sorting
|
Java
|
class Solution {
public int[][] sortMatrix(int[][] grid) {
int n = grid.length;
for (int k = n - 2; k >= 0; --k) {
int i = k, j = 0;
List<Integer> t = new ArrayList<>();
while (i < n && j < n) {
t.add(grid[i++][j++]);
}
Collections.sort(t);
for (int x : t) {
grid[--i][--j] = x;
}
}
for (int k = n - 2; k > 0; --k) {
int i = k, j = n - 1;
List<Integer> t = new ArrayList<>();
while (i >= 0 && j >= 0) {
t.add(grid[i--][j--]);
}
Collections.sort(t);
for (int x : t) {
grid[++i][++j] = x;
}
}
return grid;
}
}
|
3,446 |
Sort Matrix by Diagonals
|
Medium
|
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p>
<ul>
<li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li>
<li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p>
<p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p>
<ul>
<li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li>
<li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li>
</ul>
<p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p>
<ul>
<li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li>
<li><code>[3]</code> remains unchanged.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p>
<p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[1]]</span></p>
<p><strong>Explanation:</strong></p>
<p>Diagonals with exactly one element are already in order, so no changes are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>grid.length == grid[i].length == n</code></li>
<li><code>1 <= n <= 10</code></li>
<li><code>-10<sup>5</sup> <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Sorting
|
Python
|
class Solution:
def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
for k in range(n - 2, -1, -1):
i, j = k, 0
t = []
while i < n and j < n:
t.append(grid[i][j])
i += 1
j += 1
t.sort()
i, j = k, 0
while i < n and j < n:
grid[i][j] = t.pop()
i += 1
j += 1
for k in range(n - 2, 0, -1):
i, j = k, n - 1
t = []
while i >= 0 and j >= 0:
t.append(grid[i][j])
i -= 1
j -= 1
t.sort()
i, j = k, n - 1
while i >= 0 and j >= 0:
grid[i][j] = t.pop()
i -= 1
j -= 1
return grid
|
3,446 |
Sort Matrix by Diagonals
|
Medium
|
<p>You are given an <code>n x n</code> square matrix of integers <code>grid</code>. Return the matrix such that:</p>
<ul>
<li>The diagonals in the <strong>bottom-left triangle</strong> (including the middle diagonal) are sorted in <strong>non-increasing order</strong>.</li>
<li>The diagonals in the <strong>top-right triangle</strong> are sorted in <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,7,3],[9,8,2],[4,5,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[8,2,3],[9,6,7],[4,5,1]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example1drawio.png" style="width: 461px; height: 181px;" /></p>
<p>The diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:</p>
<ul>
<li><code>[1, 8, 6]</code> becomes <code>[8, 6, 1]</code>.</li>
<li><code>[9, 5]</code> and <code>[4]</code> remain unchanged.</li>
</ul>
<p>The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:</p>
<ul>
<li><code>[7, 2]</code> becomes <code>[2, 7]</code>.</li>
<li><code>[3]</code> remains unchanged.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[0,1],[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[2,1],[1,0]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3446.Sort%20Matrix%20by%20Diagonals/images/4052example2adrawio.png" style="width: 383px; height: 141px;" /></p>
<p>The diagonals with a black arrow must be non-increasing, so <code>[0, 2]</code> is changed to <code>[2, 0]</code>. The other diagonals are already in the correct order.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[[1]]</span></p>
<p><strong>Explanation:</strong></p>
<p>Diagonals with exactly one element are already in order, so no changes are needed.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>grid.length == grid[i].length == n</code></li>
<li><code>1 <= n <= 10</code></li>
<li><code>-10<sup>5</sup> <= grid[i][j] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Matrix; Sorting
|
TypeScript
|
function sortMatrix(grid: number[][]): number[][] {
const n = grid.length;
for (let k = n - 2; k >= 0; --k) {
let [i, j] = [k, 0];
const t: number[] = [];
while (i < n && j < n) {
t.push(grid[i++][j++]);
}
t.sort((a, b) => a - b);
for (const x of t) {
grid[--i][--j] = x;
}
}
for (let k = n - 2; k > 0; --k) {
let [i, j] = [k, n - 1];
const t: number[] = [];
while (i >= 0 && j >= 0) {
t.push(grid[i--][j--]);
}
t.sort((a, b) => a - b);
for (const x of t) {
grid[++i][++j] = x;
}
}
return grid;
}
|
3,447 |
Assign Elements to Groups with Constraints
|
Medium
|
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p>
<p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p>
<ul>
<li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li>
<li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li>
<li>If no element satisfies the condition for a group, assign -1 to that group.</li>
</ul>
<p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p>
<p><strong>Note</strong>: An element may be assigned to more than one group.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li>
<li><code>elements[1] = 2</code> is assigned to group 3.</li>
<li>Group 2 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[1] = 3</code> is assigned to group 1.</li>
<li><code>elements[0] = 5</code> is assigned to group 2.</li>
<li>Groups 0 and 3 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= groups.length <= 10<sup>5</sup></code></li>
<li><code>1 <= elements.length <= 10<sup>5</sup></code></li>
<li><code>1 <= groups[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= elements[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
vector<int> assignElements(vector<int>& groups, vector<int>& elements) {
int mx = ranges::max(groups);
vector<int> d(mx + 1, -1);
for (int j = 0; j < elements.size(); ++j) {
int x = elements[j];
if (x > mx || d[x] != -1) {
continue;
}
for (int y = x; y <= mx; y += x) {
if (d[y] == -1) {
d[y] = j;
}
}
}
vector<int> ans(groups.size());
for (int i = 0; i < groups.size(); ++i) {
ans[i] = d[groups[i]];
}
return ans;
}
};
|
3,447 |
Assign Elements to Groups with Constraints
|
Medium
|
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p>
<p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p>
<ul>
<li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li>
<li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li>
<li>If no element satisfies the condition for a group, assign -1 to that group.</li>
</ul>
<p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p>
<p><strong>Note</strong>: An element may be assigned to more than one group.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li>
<li><code>elements[1] = 2</code> is assigned to group 3.</li>
<li>Group 2 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[1] = 3</code> is assigned to group 1.</li>
<li><code>elements[0] = 5</code> is assigned to group 2.</li>
<li>Groups 0 and 3 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= groups.length <= 10<sup>5</sup></code></li>
<li><code>1 <= elements.length <= 10<sup>5</sup></code></li>
<li><code>1 <= groups[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= elements[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func assignElements(groups []int, elements []int) (ans []int) {
mx := slices.Max(groups)
d := make([]int, mx+1)
for i := range d {
d[i] = -1
}
for j, x := range elements {
if x > mx || d[x] != -1 {
continue
}
for y := x; y <= mx; y += x {
if d[y] == -1 {
d[y] = j
}
}
}
for _, x := range groups {
ans = append(ans, d[x])
}
return
}
|
3,447 |
Assign Elements to Groups with Constraints
|
Medium
|
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p>
<p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p>
<ul>
<li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li>
<li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li>
<li>If no element satisfies the condition for a group, assign -1 to that group.</li>
</ul>
<p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p>
<p><strong>Note</strong>: An element may be assigned to more than one group.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li>
<li><code>elements[1] = 2</code> is assigned to group 3.</li>
<li>Group 2 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[1] = 3</code> is assigned to group 1.</li>
<li><code>elements[0] = 5</code> is assigned to group 2.</li>
<li>Groups 0 and 3 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= groups.length <= 10<sup>5</sup></code></li>
<li><code>1 <= elements.length <= 10<sup>5</sup></code></li>
<li><code>1 <= groups[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= elements[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int[] assignElements(int[] groups, int[] elements) {
int mx = Arrays.stream(groups).max().getAsInt();
int[] d = new int[mx + 1];
Arrays.fill(d, -1);
for (int j = 0; j < elements.length; ++j) {
int x = elements[j];
if (x > mx || d[x] != -1) {
continue;
}
for (int y = x; y <= mx; y += x) {
if (d[y] == -1) {
d[y] = j;
}
}
}
int n = groups.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = d[groups[i]];
}
return ans;
}
}
|
3,447 |
Assign Elements to Groups with Constraints
|
Medium
|
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p>
<p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p>
<ul>
<li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li>
<li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li>
<li>If no element satisfies the condition for a group, assign -1 to that group.</li>
</ul>
<p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p>
<p><strong>Note</strong>: An element may be assigned to more than one group.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li>
<li><code>elements[1] = 2</code> is assigned to group 3.</li>
<li>Group 2 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[1] = 3</code> is assigned to group 1.</li>
<li><code>elements[0] = 5</code> is assigned to group 2.</li>
<li>Groups 0 and 3 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= groups.length <= 10<sup>5</sup></code></li>
<li><code>1 <= elements.length <= 10<sup>5</sup></code></li>
<li><code>1 <= groups[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= elements[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def assignElements(self, groups: List[int], elements: List[int]) -> List[int]:
mx = max(groups)
d = [-1] * (mx + 1)
for j, x in enumerate(elements):
if x > mx or d[x] != -1:
continue
for y in range(x, mx + 1, x):
if d[y] == -1:
d[y] = j
return [d[x] for x in groups]
|
3,447 |
Assign Elements to Groups with Constraints
|
Medium
|
<p>You are given an integer array <code>groups</code>, where <code>groups[i]</code> represents the size of the <code>i<sup>th</sup></code> group. You are also given an integer array <code>elements</code>.</p>
<p>Your task is to assign <strong>one</strong> element to each group based on the following rules:</p>
<ul>
<li>An element at index <code>j</code> can be assigned to a group <code>i</code> if <code>groups[i]</code> is <strong>divisible</strong> by <code>elements[j]</code>.</li>
<li>If there are multiple elements that can be assigned, assign the element with the <strong>smallest index</strong> <code>j</code>.</li>
<li>If no element satisfies the condition for a group, assign -1 to that group.</li>
</ul>
<p>Return an integer array <code>assigned</code>, where <code>assigned[i]</code> is the index of the element chosen for group <code>i</code>, or -1 if no suitable element exists.</p>
<p><strong>Note</strong>: An element may be assigned to more than one group.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [8,4,3,2,4], elements = [4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,-1,1,0]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[0] = 4</code> is assigned to groups 0, 1, and 4.</li>
<li><code>elements[1] = 2</code> is assigned to group 3.</li>
<li>Group 2 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [2,3,5,7], elements = [5,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">[-1,1,0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>elements[1] = 3</code> is assigned to group 1.</li>
<li><code>elements[0] = 5</code> is assigned to group 2.</li>
<li>Groups 0 and 3 cannot be assigned any element.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">groups = [10,21,30,41], elements = [2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1,0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p><code>elements[0] = 2</code> is assigned to the groups with even values, and <code>elements[1] = 1</code> is assigned to the groups with odd values.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= groups.length <= 10<sup>5</sup></code></li>
<li><code>1 <= elements.length <= 10<sup>5</sup></code></li>
<li><code>1 <= groups[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= elements[i] <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function assignElements(groups: number[], elements: number[]): number[] {
const mx = Math.max(...groups);
const d: number[] = Array(mx + 1).fill(-1);
for (let j = 0; j < elements.length; ++j) {
const x = elements[j];
if (x > mx || d[x] !== -1) {
continue;
}
for (let y = x; y <= mx; y += x) {
if (d[y] === -1) {
d[y] = j;
}
}
}
return groups.map(x => d[x]);
}
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int maxStudentsOnBench(vector<vector<int>>& students) {
unordered_map<int, unordered_set<int>> d;
for (const auto& e : students) {
int studentId = e[0], benchId = e[1];
d[benchId].insert(studentId);
}
int ans = 0;
for (const auto& s : d) {
ans = max(ans, (int) s.second.size());
}
return ans;
}
};
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func maxStudentsOnBench(students [][]int) (ans int) {
d := make(map[int]map[int]struct{})
for _, e := range students {
studentId, benchId := e[0], e[1]
if _, exists := d[benchId]; !exists {
d[benchId] = make(map[int]struct{})
}
d[benchId][studentId] = struct{}{}
}
for _, s := range d {
ans = max(ans, len(s))
}
return
}
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int maxStudentsOnBench(int[][] students) {
Map<Integer, Set<Integer>> d = new HashMap<>();
for (var e : students) {
int studentId = e[0], benchId = e[1];
d.computeIfAbsent(benchId, k -> new HashSet<>()).add(studentId);
}
int ans = 0;
for (var s : d.values()) {
ans = Math.max(ans, s.size());
}
return ans;
}
}
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def maxStudentsOnBench(self, students: List[List[int]]) -> int:
if not students:
return 0
d = defaultdict(set)
for student_id, bench_id in students:
d[bench_id].add(student_id)
return max(map(len, d.values()))
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
Rust
|
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn max_students_on_bench(students: Vec<Vec<i32>>) -> i32 {
let mut d: HashMap<i32, HashSet<i32>> = HashMap::new();
for e in students {
let student_id = e[0];
let bench_id = e[1];
d.entry(bench_id)
.or_insert_with(HashSet::new)
.insert(student_id);
}
let mut ans = 0;
for s in d.values() {
ans = ans.max(s.len() as i32);
}
ans
}
}
|
3,450 |
Maximum Students on a Single Bench
|
Easy
|
<p data-pm-slice="1 1 []">You are given a 2D integer array of student data <code>students</code>, where <code>students[i] = [student_id, bench_id]</code> represents that student <code>student_id</code> is sitting on the bench <code>bench_id</code>.</p>
<p>Return the <strong>maximum</strong> number of <em>unique</em> students sitting on any single bench. If no students are present, return 0.</p>
<p><strong>Note</strong>: A student can appear multiple times on the same bench in the input, but they should be counted only once per bench.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,2],[2,2],[3,3],[1,3],[2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 2 has two unique students: <code>[1, 2]</code>.</li>
<li>Bench 3 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>The maximum number of unique students on a single bench 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">students = [[1,1],[2,1],[3,1],[4,2],[5,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Bench 1 has three unique students: <code>[1, 2, 3]</code>.</li>
<li>Bench 2 has two unique students: <code>[4, 5]</code>.</li>
<li>The maximum number of unique students on a single bench is 3.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = [[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The maximum number of unique students on a single bench is 1.</li>
</ul>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">students = []</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since no students are present, the output is 0.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= students.length <= 100</code></li>
<li><code>students[i] = [student_id, bench_id]</code></li>
<li><code>1 <= student_id <= 100</code></li>
<li><code>1 <= bench_id <= 100</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function maxStudentsOnBench(students: number[][]): number {
const d: Map<number, Set<number>> = new Map();
for (const [studentId, benchId] of students) {
if (!d.has(benchId)) {
d.set(benchId, new Set());
}
d.get(benchId)?.add(studentId);
}
let ans = 0;
for (const s of d.values()) {
ans = Math.max(ans, s.size);
}
return ans;
}
|
3,451 |
Find Invalid IP Addresses
|
Hard
|
<p>Table: <code> logs</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| log_id | int |
| ip | varchar |
| status_code | int |
+-------------+---------+
log_id is the unique key for this table.
Each row contains server access log information including IP address and HTTP status code.
</pre>
<p>Write a solution to find <strong>invalid IP addresses</strong>. An IPv4 address is invalid if it meets any of these conditions:</p>
<ul>
<li>Contains numbers <strong>greater than</strong> <code>255</code> in any octet</li>
<li>Has <strong>leading zeros</strong> in any octet (like <code>01.02.03.04</code>)</li>
<li>Has <strong>less or more</strong> than <code>4</code> octets</li>
</ul>
<p>Return <em>the result table </em><em>ordered by</em> <code>invalid_count</code>, <code>ip</code> <em>in <strong>descending</strong> order respectively</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>logs table:</p>
<pre class="example-io">
+--------+---------------+-------------+
| log_id | ip | status_code |
+--------+---------------+-------------+
| 1 | 192.168.1.1 | 200 |
| 2 | 256.1.2.3 | 404 |
| 3 | 192.168.001.1 | 200 |
| 4 | 192.168.1.1 | 200 |
| 5 | 192.168.1 | 500 |
| 6 | 256.1.2.3 | 404 |
| 7 | 192.168.001.1 | 200 |
+--------+---------------+-------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------------+--------------+
| ip | invalid_count|
+---------------+--------------+
| 256.1.2.3 | 2 |
| 192.168.001.1 | 2 |
| 192.168.1 | 1 |
+---------------+--------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>256.1.2.3 is invalid because 256 > 255</li>
<li>192.168.001.1 is invalid because of leading zeros</li>
<li>192.168.1 is invalid because it has only 3 octets</li>
</ul>
<p>The output table is ordered by invalid_count, ip in descending order respectively.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_invalid_ips(logs: pd.DataFrame) -> pd.DataFrame:
def is_valid_ip(ip: str) -> bool:
octets = ip.split(".")
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
return False
value = int(octet)
if not 0 <= value <= 255 or octet != str(value):
return False
return True
logs["is_valid"] = logs["ip"].apply(is_valid_ip)
invalid_ips = logs[~logs["is_valid"]]
invalid_count = invalid_ips["ip"].value_counts().reset_index()
invalid_count.columns = ["ip", "invalid_count"]
result = invalid_count.sort_values(
by=["invalid_count", "ip"], ascending=[False, False]
)
return result
|
3,451 |
Find Invalid IP Addresses
|
Hard
|
<p>Table: <code> logs</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| log_id | int |
| ip | varchar |
| status_code | int |
+-------------+---------+
log_id is the unique key for this table.
Each row contains server access log information including IP address and HTTP status code.
</pre>
<p>Write a solution to find <strong>invalid IP addresses</strong>. An IPv4 address is invalid if it meets any of these conditions:</p>
<ul>
<li>Contains numbers <strong>greater than</strong> <code>255</code> in any octet</li>
<li>Has <strong>leading zeros</strong> in any octet (like <code>01.02.03.04</code>)</li>
<li>Has <strong>less or more</strong> than <code>4</code> octets</li>
</ul>
<p>Return <em>the result table </em><em>ordered by</em> <code>invalid_count</code>, <code>ip</code> <em>in <strong>descending</strong> order respectively</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>logs table:</p>
<pre class="example-io">
+--------+---------------+-------------+
| log_id | ip | status_code |
+--------+---------------+-------------+
| 1 | 192.168.1.1 | 200 |
| 2 | 256.1.2.3 | 404 |
| 3 | 192.168.001.1 | 200 |
| 4 | 192.168.1.1 | 200 |
| 5 | 192.168.1 | 500 |
| 6 | 256.1.2.3 | 404 |
| 7 | 192.168.001.1 | 200 |
+--------+---------------+-------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------------+--------------+
| ip | invalid_count|
+---------------+--------------+
| 256.1.2.3 | 2 |
| 192.168.001.1 | 2 |
| 192.168.1 | 1 |
+---------------+--------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>256.1.2.3 is invalid because 256 > 255</li>
<li>192.168.001.1 is invalid because of leading zeros</li>
<li>192.168.1 is invalid because it has only 3 octets</li>
</ul>
<p>The output table is ordered by invalid_count, ip in descending order respectively.</p>
</div>
|
Database
|
SQL
|
SELECT
ip,
COUNT(*) AS invalid_count
FROM logs
WHERE
LENGTH(ip) - LENGTH(REPLACE(ip, '.', '')) != 3
OR SUBSTRING_INDEX(ip, '.', 1) REGEXP '^0[0-9]'
OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 2), '.', -1) REGEXP '^0[0-9]'
OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 3), '.', -1) REGEXP '^0[0-9]'
OR SUBSTRING_INDEX(ip, '.', -1) REGEXP '^0[0-9]'
OR SUBSTRING_INDEX(ip, '.', 1) > 255
OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 2), '.', -1) > 255
OR SUBSTRING_INDEX(SUBSTRING_INDEX(ip, '.', 3), '.', -1) > 255
OR SUBSTRING_INDEX(ip, '.', -1) > 255
GROUP BY 1
ORDER BY 2 DESC, 1 DESC;
|
3,452 |
Sum of Good Numbers
|
Easy
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p>
<p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= floor(nums.length / 2)</code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int sumOfGoodNumbers(vector<int>& nums, int k) {
int ans = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (i >= k && nums[i] <= nums[i - k]) {
continue;
}
if (i + k < n && nums[i] <= nums[i + k]) {
continue;
}
ans += nums[i];
}
return ans;
}
};
|
3,452 |
Sum of Good Numbers
|
Easy
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p>
<p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= floor(nums.length / 2)</code></li>
</ul>
|
Array
|
Go
|
func sumOfGoodNumbers(nums []int, k int) (ans int) {
for i, x := range nums {
if i >= k && x <= nums[i-k] {
continue
}
if i+k < len(nums) && x <= nums[i+k] {
continue
}
ans += x
}
return
}
|
3,452 |
Sum of Good Numbers
|
Easy
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p>
<p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= floor(nums.length / 2)</code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int sumOfGoodNumbers(int[] nums, int k) {
int ans = 0;
int n = nums.length;
for (int i = 0; i < n; ++i) {
if (i >= k && nums[i] <= nums[i - k]) {
continue;
}
if (i + k < n && nums[i] <= nums[i + k]) {
continue;
}
ans += nums[i];
}
return ans;
}
}
|
3,452 |
Sum of Good Numbers
|
Easy
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p>
<p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= floor(nums.length / 2)</code></li>
</ul>
|
Array
|
Python
|
class Solution:
def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
ans = 0
for i, x in enumerate(nums):
if i >= k and x <= nums[i - k]:
continue
if i + k < len(nums) and x <= nums[i + k]:
continue
ans += x
return ans
|
3,452 |
Sum of Good Numbers
|
Easy
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, an element <code>nums[i]</code> is considered <strong>good</strong> if it is <strong>strictly</strong> greater than the elements at indices <code>i - k</code> and <code>i + k</code> (if those indices exist). If neither of these indices <em>exists</em>, <code>nums[i]</code> is still considered <strong>good</strong>.</p>
<p>Return the <strong>sum</strong> of all the <strong>good</strong> elements in the array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,5,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The good numbers are <code>nums[1] = 3</code>, <code>nums[4] = 5</code>, and <code>nums[5] = 4</code> because they are strictly greater than the numbers at indices <code>i - k</code> and <code>i + k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The only good number is <code>nums[0] = 2</code> because it is strictly greater than <code>nums[1]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= k <= floor(nums.length / 2)</code></li>
</ul>
|
Array
|
TypeScript
|
function sumOfGoodNumbers(nums: number[], k: number): number {
const n = nums.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
if (i >= k && nums[i] <= nums[i - k]) {
continue;
}
if (i + k < n && nums[i] <= nums[i + k]) {
continue;
}
ans += nums[i];
}
return ans;
}
|
3,456 |
Find Special Substring of Length K
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p>
<ol>
<li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>"aaa"</code> or <code>"bbb"</code>).</li>
<li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li>
<li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li>
</ol>
<p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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 = "aaabaaa", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substring <code>s[4..6] == "aaa"</code> satisfies the conditions.</p>
<ul>
<li>It has a length of 3.</li>
<li>All characters are the same.</li>
<li>The character before <code>"aaa"</code> is <code>'b'</code>, which is different from <code>'a'</code>.</li>
<li>There is no character after <code>"aaa"</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 = "abc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
bool hasSpecialSubstring(string s, int k) {
int n = s.length();
for (int l = 0, cnt = 0; l < n;) {
int r = l + 1;
while (r < n && s[r] == s[l]) {
++r;
}
if (r - l == k) {
return true;
}
l = r;
}
return false;
}
};
|
3,456 |
Find Special Substring of Length K
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p>
<ol>
<li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>"aaa"</code> or <code>"bbb"</code>).</li>
<li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li>
<li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li>
</ol>
<p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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 = "aaabaaa", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substring <code>s[4..6] == "aaa"</code> satisfies the conditions.</p>
<ul>
<li>It has a length of 3.</li>
<li>All characters are the same.</li>
<li>The character before <code>"aaa"</code> is <code>'b'</code>, which is different from <code>'a'</code>.</li>
<li>There is no character after <code>"aaa"</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 = "abc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String
|
Go
|
func hasSpecialSubstring(s string, k int) bool {
n := len(s)
for l := 0; l < n; {
r := l + 1
for r < n && s[r] == s[l] {
r++
}
if r-l == k {
return true
}
l = r
}
return false
}
|
3,456 |
Find Special Substring of Length K
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p>
<ol>
<li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>"aaa"</code> or <code>"bbb"</code>).</li>
<li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li>
<li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li>
</ol>
<p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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 = "aaabaaa", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substring <code>s[4..6] == "aaa"</code> satisfies the conditions.</p>
<ul>
<li>It has a length of 3.</li>
<li>All characters are the same.</li>
<li>The character before <code>"aaa"</code> is <code>'b'</code>, which is different from <code>'a'</code>.</li>
<li>There is no character after <code>"aaa"</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 = "abc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String
|
Java
|
class Solution {
public boolean hasSpecialSubstring(String s, int k) {
int n = s.length();
for (int l = 0, cnt = 0; l < n;) {
int r = l + 1;
while (r < n && s.charAt(r) == s.charAt(l)) {
++r;
}
if (r - l == k) {
return true;
}
l = r;
}
return false;
}
}
|
3,456 |
Find Special Substring of Length K
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p>
<ol>
<li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>"aaa"</code> or <code>"bbb"</code>).</li>
<li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li>
<li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li>
</ol>
<p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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 = "aaabaaa", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substring <code>s[4..6] == "aaa"</code> satisfies the conditions.</p>
<ul>
<li>It has a length of 3.</li>
<li>All characters are the same.</li>
<li>The character before <code>"aaa"</code> is <code>'b'</code>, which is different from <code>'a'</code>.</li>
<li>There is no character after <code>"aaa"</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 = "abc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String
|
Python
|
class Solution:
def hasSpecialSubstring(self, s: str, k: int) -> bool:
l, n = 0, len(s)
while l < n:
r = l
while r < n and s[r] == s[l]:
r += 1
if r - l == k:
return True
l = r
return False
|
3,456 |
Find Special Substring of Length K
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Determine if there exists a <span data-keyword="substring-nonempty">substring</span> of length <strong>exactly</strong> <code>k</code> in <code>s</code> that satisfies the following conditions:</p>
<ol>
<li>The substring consists of <strong>only one distinct character</strong> (e.g., <code>"aaa"</code> or <code>"bbb"</code>).</li>
<li>If there is a character <strong>immediately before</strong> the substring, it must be different from the character in the substring.</li>
<li>If there is a character <strong>immediately after</strong> the substring, it must also be different from the character in the substring.</li>
</ol>
<p>Return <code>true</code> if such a substring exists. Otherwise, return <code>false</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 = "aaabaaa", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substring <code>s[4..6] == "aaa"</code> satisfies the conditions.</p>
<ul>
<li>It has a length of 3.</li>
<li>All characters are the same.</li>
<li>The character before <code>"aaa"</code> is <code>'b'</code>, which is different from <code>'a'</code>.</li>
<li>There is no character after <code>"aaa"</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 = "abc", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring of length 2 that consists of one distinct character and satisfies the conditions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= k <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters only.</li>
</ul>
|
String
|
TypeScript
|
function hasSpecialSubstring(s: string, k: number): boolean {
const n = s.length;
for (let l = 0; l < n; ) {
let r = l + 1;
while (r < n && s[r] === s[l]) {
r++;
}
if (r - l === k) {
return true;
}
l = r;
}
return false;
}
|
3,457 |
Eat Pizzas!
|
Medium
|
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W <= X <= Y <= Z</code>, you gain the weight of only 1 pizza!</p>
<ul>
<li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li>
<li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li>
</ul>
<p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p>
<p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li>
<li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li>
<li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>4 <= n == pizzas.length <= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li>
<li><code>1 <= pizzas[i] <= 10<sup>5</sup></code></li>
<li><code>n</code> is a multiple of 4.</li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
long long maxWeight(vector<int>& pizzas) {
int n = pizzas.size();
int days = pizzas.size() / 4;
ranges::sort(pizzas);
int odd = (days + 1) / 2;
int even = days - odd;
long long ans = accumulate(pizzas.begin() + n - odd, pizzas.end(), 0LL);
for (int i = n - odd - 2; even; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
};
|
3,457 |
Eat Pizzas!
|
Medium
|
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W <= X <= Y <= Z</code>, you gain the weight of only 1 pizza!</p>
<ul>
<li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li>
<li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li>
</ul>
<p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p>
<p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li>
<li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li>
<li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>4 <= n == pizzas.length <= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li>
<li><code>1 <= pizzas[i] <= 10<sup>5</sup></code></li>
<li><code>n</code> is a multiple of 4.</li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func maxWeight(pizzas []int) (ans int64) {
n := len(pizzas)
days := n / 4
sort.Ints(pizzas)
odd := (days + 1) / 2
even := days - odd
for i := n - odd; i < n; i++ {
ans += int64(pizzas[i])
}
for i := n - odd - 2; even > 0; even-- {
ans += int64(pizzas[i])
i -= 2
}
return
}
|
3,457 |
Eat Pizzas!
|
Medium
|
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W <= X <= Y <= Z</code>, you gain the weight of only 1 pizza!</p>
<ul>
<li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li>
<li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li>
</ul>
<p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p>
<p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li>
<li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li>
<li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>4 <= n == pizzas.length <= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li>
<li><code>1 <= pizzas[i] <= 10<sup>5</sup></code></li>
<li><code>n</code> is a multiple of 4.</li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public long maxWeight(int[] pizzas) {
int n = pizzas.length;
int days = n / 4;
Arrays.sort(pizzas);
int odd = (days + 1) / 2;
int even = days / 2;
long ans = 0;
for (int i = n - odd; i < n; ++i) {
ans += pizzas[i];
}
for (int i = n - odd - 2; even > 0; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
}
|
3,457 |
Eat Pizzas!
|
Medium
|
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W <= X <= Y <= Z</code>, you gain the weight of only 1 pizza!</p>
<ul>
<li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li>
<li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li>
</ul>
<p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p>
<p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li>
<li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li>
<li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>4 <= n == pizzas.length <= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li>
<li><code>1 <= pizzas[i] <= 10<sup>5</sup></code></li>
<li><code>n</code> is a multiple of 4.</li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def maxWeight(self, pizzas: List[int]) -> int:
days = len(pizzas) // 4
pizzas.sort()
odd = (days + 1) // 2
even = days - odd
ans = sum(pizzas[-odd:])
i = len(pizzas) - odd - 2
for _ in range(even):
ans += pizzas[i]
i -= 2
return ans
|
3,457 |
Eat Pizzas!
|
Medium
|
<p>You are given an integer array <code>pizzas</code> of size <code>n</code>, where <code>pizzas[i]</code> represents the weight of the <code>i<sup>th</sup></code> pizza. Every day, you eat <strong>exactly</strong> 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights <code>W</code>, <code>X</code>, <code>Y</code>, and <code>Z</code>, where <code>W <= X <= Y <= Z</code>, you gain the weight of only 1 pizza!</p>
<ul>
<li>On <strong><span style="box-sizing: border-box; margin: 0px; padding: 0px;">odd-numbered</span></strong> days <strong>(1-indexed)</strong>, you gain a weight of <code>Z</code>.</li>
<li>On <strong>even-numbered</strong> days, you gain a weight of <code>Y</code>.</li>
</ul>
<p>Find the <strong>maximum</strong> total weight you can gain by eating <strong>all</strong> pizzas optimally.</p>
<p><strong>Note</strong>: It is guaranteed that <code>n</code> is a multiple of 4, and each pizza can be eaten only once.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [1,2,3,4,5,6,7,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[1, 2, 4, 7] = [2, 3, 5, 8]</code>. You gain a weight of 8.</li>
<li>On day 2, you eat pizzas at indices <code>[0, 3, 5, 6] = [1, 4, 6, 7]</code>. You gain a weight of 6.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>8 + 6 = 14</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">pizzas = [2,1,1,1,1,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>On day 1, you eat pizzas at indices <code>[4, 5, 6, 0] = [1, 1, 1, 2]</code>. You gain a weight of 2.</li>
<li>On day 2, you eat pizzas at indices <code>[1, 2, 3, 7] = [1, 1, 1, 1]</code>. You gain a weight of 1.</li>
</ul>
<p>The total weight gained after eating all the pizzas is <code>2 + 1 = 3.</code></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>4 <= n == pizzas.length <= 2 * 10<sup><span style="font-size: 10.8333px;">5</span></sup></code></li>
<li><code>1 <= pizzas[i] <= 10<sup>5</sup></code></li>
<li><code>n</code> is a multiple of 4.</li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function maxWeight(pizzas: number[]): number {
const n = pizzas.length;
const days = n >> 2;
pizzas.sort((a, b) => a - b);
const odd = (days + 1) >> 1;
let even = days - odd;
let ans = 0;
for (let i = n - odd; i < n; ++i) {
ans += pizzas[i];
}
for (let i = n - odd - 2; even; --even) {
ans += pizzas[i];
i -= 2;
}
return ans;
}
|
3,459 |
Length of Longest V-Shaped Diagonal Segment
|
Hard
|
<p>You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, where each element is either <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>A <strong>V-shaped diagonal segment</strong> is defined as:</p>
<ul>
<li>The segment starts with <code>1</code>.</li>
<li>The subsequent elements follow this infinite sequence: <code>2, 0, 2, 0, ...</code>.</li>
<li>The segment:
<ul>
<li>Starts <strong>along</strong> a diagonal direction (top-left to bottom-right, bottom-right to top-left, top-right to bottom-left, or bottom-left to top-right).</li>
<li>Continues the<strong> sequence</strong> in the same diagonal direction.</li>
<li>Makes<strong> at most one clockwise 90-degree</strong><strong> turn</strong> to another diagonal direction while <strong>maintaining</strong> the sequence.</li>
</ul>
</li>
</ul>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/length_of_longest3.jpg" style="width: 481px; height: 202px;" /></p>
<p>Return the <strong>length</strong> of the <strong>longest</strong> <strong>V-shaped diagonal segment</strong>. If no valid segment <em>exists</em>, return 0.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[2,2,1,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_1-2.jpg" style="width: 201px; height: 192px;" /></p>
<p>The longest V-shaped diagonal segment has a length of 5 and follows these coordinates: <code>(0,2) → (1,3) → (2,4)</code>, takes a <strong>90-degree clockwise turn</strong> at <code>(2,4)</code>, and continues as <code>(3,3) → (4,2)</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[2,2,2,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_2.jpg" style="width: 201px; height: 201px;" /></strong></p>
<p>The longest V-shaped diagonal segment has a length of 4 and follows these coordinates: <code>(2,3) → (3,2)</code>, takes a <strong>90-degree clockwise turn</strong> at <code>(3,2)</code>, and continues as <code>(2,1) → (1,0)</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2,2,2,2],[2,2,2,2,0],[2,0,0,0,0],[0,0,2,2,2],[2,0,0,2,0]]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3459.Length%20of%20Longest%20V-Shaped%20Diagonal%20Segment/images/matrix_3.jpg" style="width: 201px; height: 201px;" /></strong></p>
<p>The longest V-shaped diagonal segment has a length of 5 and follows these coordinates: <code>(0,0) → (1,1) → (2,2) → (3,3) → (4,4)</code>.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The longest V-shaped diagonal segment has a length of 1 and follows these coordinates: <code>(0,0)</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code> or <code>2</code>.</li>
</ul>
|
Memoization; Array; Dynamic Programming; Matrix
|
Python
|
class Solution:
def lenOfVDiagonal(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
next_digit = {1: 2, 2: 0, 0: 2}
def within_bounds(i, j):
return 0 <= i < m and 0 <= j < n
@cache
def f(i, j, di, dj, turned):
result = 1
successor = next_digit[grid[i][j]]
if within_bounds(i + di, j + dj) and grid[i + di][j + dj] == successor:
result = 1 + f(i + di, j + dj, di, dj, turned)
if not turned:
di, dj = dj, -di
if within_bounds(i + di, j + dj) and grid[i + di][j + dj] == successor:
result = max(result, 1 + f(i + di, j + dj, di, dj, True))
return result
directions = ((1, 1), (-1, 1), (1, -1), (-1, -1))
result = 0
for i in range(m):
for j in range(n):
if grid[i][j] != 1:
continue
for di, dj in directions:
result = max(result, f(i, j, di, dj, False))
return result
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
C++
|
class Solution {
public:
int longestCommonPrefix(string s, string t) {
int n = s.length(), m = t.length();
int i = 0, j = 0;
bool rem = false;
while (i < n && j < m) {
if (s[i] != t[j]) {
if (rem) {
break;
}
rem = true;
} else {
++j;
}
++i;
}
return j;
}
};
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Go
|
func longestCommonPrefix(s string, t string) int {
n, m := len(s), len(t)
i, j := 0, 0
rem := false
for i < n && j < m {
if s[i] != t[j] {
if rem {
break
}
rem = true
} else {
j++
}
i++
}
return j
}
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Java
|
class Solution {
public int longestCommonPrefix(String s, String t) {
int n = s.length(), m = t.length();
int i = 0, j = 0;
boolean rem = false;
while (i < n && j < m) {
if (s.charAt(i) != t.charAt(j)) {
if (rem) {
break;
}
rem = true;
} else {
++j;
}
++i;
}
return j;
}
}
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
JavaScript
|
/**
* @param {string} s
* @param {string} t
* @return {number}
*/
var longestCommonPrefix = function (s, t) {
const [n, m] = [s.length, t.length];
let [i, j] = [0, 0];
let rem = false;
while (i < n && j < m) {
if (s[i] !== t[j]) {
if (rem) {
break;
}
rem = true;
} else {
++j;
}
++i;
}
return j;
};
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Python
|
class Solution:
def longestCommonPrefix(self, s: str, t: str) -> int:
n, m = len(s), len(t)
i = j = 0
rem = False
while i < n and j < m:
if s[i] != t[j]:
if rem:
break
rem = True
else:
j += 1
i += 1
return j
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Rust
|
impl Solution {
pub fn longest_common_prefix(s: String, t: String) -> i32 {
let (n, m) = (s.len(), t.len());
let (mut i, mut j) = (0, 0);
let mut rem = false;
while i < n && j < m {
if s.as_bytes()[i] != t.as_bytes()[j] {
if rem {
break;
}
rem = true;
} else {
j += 1;
}
i += 1;
}
j as i32
}
}
|
3,460 |
Longest Common Prefix After at Most One Removal
|
Medium
|
<p>You are given two strings <code>s</code> and <code>t</code>.</p>
<p>Return the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> between <code>s</code> and <code>t</code> after removing <strong>at most</strong> one character from <code>s</code>.</p>
<p><strong>Note:</strong> <code>s</code> can be left without any removal.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "madxa", t = "madam"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[3]</code> from <code>s</code> results in <code>"mada"</code>, which has a longest common prefix of length 4 with <code>t</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", t = "eetcode"</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing <code>s[0]</code> from <code>s</code> results in <code>"eetcode"</code>, which matches <code>t</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "one", t = "one"</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>No removal is needed.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "a", t = "b"</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>s</code> and <code>t</code> cannot have a common prefix.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>1 <= t.length <= 10<sup>5</sup></code></li>
<li><code>s</code> and <code>t</code> contain only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
TypeScript
|
function longestCommonPrefix(s: string, t: string): number {
const [n, m] = [s.length, t.length];
let [i, j] = [0, 0];
let rem: boolean = false;
while (i < n && j < m) {
if (s[i] !== t[j]) {
if (rem) {
break;
}
rem = true;
} else {
++j;
}
++i;
}
return j;
}
|
3,461 |
Check If Digits Are Equal in String After Operations I
|
Easy
|
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p>
<ul>
<li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li>
<li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li>
</ul>
<p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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 = "3902"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "3902"</code></li>
<li>First operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li>
<li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li>
<li><code>s</code> becomes <code>"292"</code></li>
</ul>
</li>
<li>Second operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li>
<li><code>s</code> becomes <code>"11"</code></li>
</ul>
</li>
<li>Since the digits in <code>"11"</code> are the same, the output is <code>true</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 = "34789"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "34789"</code>.</li>
<li>After the first operation, <code>s = "7157"</code>.</li>
<li>After the second operation, <code>s = "862"</code>.</li>
<li>After the third operation, <code>s = "48"</code>.</li>
<li>Since <code>'4' != '8'</code>, the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 100</code></li>
<li><code>s</code> consists of only digits.</li>
</ul>
|
Math; String; Combinatorics; Number Theory; Simulation
|
C++
|
class Solution {
public:
bool hasSameDigits(string s) {
int n = s.size();
string t = s;
for (int k = n - 1; k > 1; --k) {
for (int i = 0; i < k; ++i) {
t[i] = (t[i] - '0' + t[i + 1] - '0') % 10 + '0';
}
}
return t[0] == t[1];
}
};
|
3,461 |
Check If Digits Are Equal in String After Operations I
|
Easy
|
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p>
<ul>
<li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li>
<li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li>
</ul>
<p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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 = "3902"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "3902"</code></li>
<li>First operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li>
<li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li>
<li><code>s</code> becomes <code>"292"</code></li>
</ul>
</li>
<li>Second operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li>
<li><code>s</code> becomes <code>"11"</code></li>
</ul>
</li>
<li>Since the digits in <code>"11"</code> are the same, the output is <code>true</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 = "34789"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "34789"</code>.</li>
<li>After the first operation, <code>s = "7157"</code>.</li>
<li>After the second operation, <code>s = "862"</code>.</li>
<li>After the third operation, <code>s = "48"</code>.</li>
<li>Since <code>'4' != '8'</code>, the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 100</code></li>
<li><code>s</code> consists of only digits.</li>
</ul>
|
Math; String; Combinatorics; Number Theory; Simulation
|
Go
|
func hasSameDigits(s string) bool {
t := []byte(s)
n := len(t)
for k := n - 1; k > 1; k-- {
for i := 0; i < k; i++ {
t[i] = (t[i]-'0'+t[i+1]-'0')%10 + '0'
}
}
return t[0] == t[1]
}
|
3,461 |
Check If Digits Are Equal in String After Operations I
|
Easy
|
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p>
<ul>
<li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li>
<li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li>
</ul>
<p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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 = "3902"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "3902"</code></li>
<li>First operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li>
<li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li>
<li><code>s</code> becomes <code>"292"</code></li>
</ul>
</li>
<li>Second operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li>
<li><code>s</code> becomes <code>"11"</code></li>
</ul>
</li>
<li>Since the digits in <code>"11"</code> are the same, the output is <code>true</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 = "34789"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "34789"</code>.</li>
<li>After the first operation, <code>s = "7157"</code>.</li>
<li>After the second operation, <code>s = "862"</code>.</li>
<li>After the third operation, <code>s = "48"</code>.</li>
<li>Since <code>'4' != '8'</code>, the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 100</code></li>
<li><code>s</code> consists of only digits.</li>
</ul>
|
Math; String; Combinatorics; Number Theory; Simulation
|
Java
|
class Solution {
public boolean hasSameDigits(String s) {
char[] t = s.toCharArray();
int n = t.length;
for (int k = n - 1; k > 1; --k) {
for (int i = 0; i < k; ++i) {
t[i] = (char) ((t[i] - '0' + t[i + 1] - '0') % 10 + '0');
}
}
return t[0] == t[1];
}
}
|
3,461 |
Check If Digits Are Equal in String After Operations I
|
Easy
|
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p>
<ul>
<li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li>
<li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li>
</ul>
<p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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 = "3902"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "3902"</code></li>
<li>First operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li>
<li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li>
<li><code>s</code> becomes <code>"292"</code></li>
</ul>
</li>
<li>Second operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li>
<li><code>s</code> becomes <code>"11"</code></li>
</ul>
</li>
<li>Since the digits in <code>"11"</code> are the same, the output is <code>true</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 = "34789"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "34789"</code>.</li>
<li>After the first operation, <code>s = "7157"</code>.</li>
<li>After the second operation, <code>s = "862"</code>.</li>
<li>After the third operation, <code>s = "48"</code>.</li>
<li>Since <code>'4' != '8'</code>, the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 100</code></li>
<li><code>s</code> consists of only digits.</li>
</ul>
|
Math; String; Combinatorics; Number Theory; Simulation
|
Python
|
class Solution:
def hasSameDigits(self, s: str) -> bool:
t = list(map(int, s))
n = len(t)
for k in range(n - 1, 1, -1):
for i in range(k):
t[i] = (t[i] + t[i + 1]) % 10
return t[0] == t[1]
|
3,461 |
Check If Digits Are Equal in String After Operations I
|
Easy
|
<p>You are given a string <code>s</code> consisting of digits. Perform the following operation repeatedly until the string has <strong>exactly</strong> two digits:</p>
<ul>
<li>For each pair of consecutive digits in <code>s</code>, starting from the first digit, calculate a new digit as the sum of the two digits <strong>modulo</strong> 10.</li>
<li>Replace <code>s</code> with the sequence of newly calculated digits, <em>maintaining the order</em> in which they are computed.</li>
</ul>
<p>Return <code>true</code> if the final two digits in <code>s</code> are the <strong>same</strong>; otherwise, return <code>false</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 = "3902"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "3902"</code></li>
<li>First operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9</code></li>
<li><code>(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2</code></li>
<li><code>s</code> becomes <code>"292"</code></li>
</ul>
</li>
<li>Second operation:
<ul>
<li><code>(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1</code></li>
<li><code>(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1</code></li>
<li><code>s</code> becomes <code>"11"</code></li>
</ul>
</li>
<li>Since the digits in <code>"11"</code> are the same, the output is <code>true</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 = "34789"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Initially, <code>s = "34789"</code>.</li>
<li>After the first operation, <code>s = "7157"</code>.</li>
<li>After the second operation, <code>s = "862"</code>.</li>
<li>After the third operation, <code>s = "48"</code>.</li>
<li>Since <code>'4' != '8'</code>, the output is <code>false</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= s.length <= 100</code></li>
<li><code>s</code> consists of only digits.</li>
</ul>
|
Math; String; Combinatorics; Number Theory; Simulation
|
TypeScript
|
function hasSameDigits(s: string): boolean {
const t = s.split('').map(Number);
const n = t.length;
for (let k = n - 1; k > 1; --k) {
for (let i = 0; i < k; ++i) {
t[i] = (t[i] + t[i + 1]) % 10;
}
}
return t[0] === t[1];
}
|
3,462 |
Maximum Sum With at Most K Elements
|
Medium
|
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p>
<ul data-spread="false">
<li>
<p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p>
</li>
</ul>
<p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li>
<li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the first row, we can take at most 2 elements. The element taken is 7.</li>
<li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li>
<li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == limits.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>0 <= grid[i][j] <= 10<sup>5</sup></code></li>
<li><code>0 <= limits[i] <= m</code></li>
<li><code>0 <= k <= min(n * m, sum(limits))</code></li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long maxSum(vector<vector<int>>& grid, vector<int>& limits, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
int n = grid.size();
for (int i = 0; i < n; ++i) {
vector<int> nums = grid[i];
int limit = limits[i];
ranges::sort(nums);
for (int j = 0; j < limit; ++j) {
pq.push(nums[nums.size() - j - 1]);
if (pq.size() > k) {
pq.pop();
}
}
}
long long ans = 0;
while (!pq.empty()) {
ans += pq.top();
pq.pop();
}
return ans;
}
};
|
3,462 |
Maximum Sum With at Most K Elements
|
Medium
|
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p>
<ul data-spread="false">
<li>
<p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p>
</li>
</ul>
<p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li>
<li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the first row, we can take at most 2 elements. The element taken is 7.</li>
<li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li>
<li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == limits.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>0 <= grid[i][j] <= 10<sup>5</sup></code></li>
<li><code>0 <= limits[i] <= m</code></li>
<li><code>0 <= k <= min(n * m, sum(limits))</code></li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Go
|
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func maxSum(grid [][]int, limits []int, k int) int64 {
pq := &MinHeap{}
heap.Init(pq)
n := len(grid)
for i := 0; i < n; i++ {
nums := make([]int, len(grid[i]))
copy(nums, grid[i])
limit := limits[i]
sort.Ints(nums)
for j := 0; j < limit; j++ {
heap.Push(pq, nums[len(nums)-j-1])
if pq.Len() > k {
heap.Pop(pq)
}
}
}
var ans int64 = 0
for pq.Len() > 0 {
ans += int64(heap.Pop(pq).(int))
}
return ans
}
|
3,462 |
Maximum Sum With at Most K Elements
|
Medium
|
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p>
<ul data-spread="false">
<li>
<p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p>
</li>
</ul>
<p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li>
<li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the first row, we can take at most 2 elements. The element taken is 7.</li>
<li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li>
<li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == limits.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>0 <= grid[i][j] <= 10<sup>5</sup></code></li>
<li><code>0 <= limits[i] <= m</code></li>
<li><code>0 <= k <= min(n * m, sum(limits))</code></li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long maxSum(int[][] grid, int[] limits, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
int n = grid.length;
for (int i = 0; i < n; ++i) {
int[] nums = grid[i];
int limit = limits[i];
Arrays.sort(nums);
for (int j = 0; j < limit; ++j) {
pq.offer(nums[nums.length - j - 1]);
if (pq.size() > k) {
pq.poll();
}
}
}
long ans = 0;
for (int x : pq) {
ans += x;
}
return ans;
}
}
|
3,462 |
Maximum Sum With at Most K Elements
|
Medium
|
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p>
<ul data-spread="false">
<li>
<p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p>
</li>
</ul>
<p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li>
<li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the first row, we can take at most 2 elements. The element taken is 7.</li>
<li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li>
<li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == limits.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>0 <= grid[i][j] <= 10<sup>5</sup></code></li>
<li><code>0 <= limits[i] <= m</code></li>
<li><code>0 <= k <= min(n * m, sum(limits))</code></li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int:
pq = []
for nums, limit in zip(grid, limits):
nums.sort()
for _ in range(limit):
heappush(pq, nums.pop())
if len(pq) > k:
heappop(pq)
return sum(pq)
|
3,462 |
Maximum Sum With at Most K Elements
|
Medium
|
<p data-pm-slice="1 3 []">You are given a 2D integer matrix <code>grid</code> of size <code>n x m</code>, an integer array <code>limits</code> of length <code>n</code>, and an integer <code>k</code>. The task is to find the <strong>maximum sum</strong> of <strong>at most</strong> <code>k</code> elements from the matrix <code>grid</code> such that:</p>
<ul data-spread="false">
<li>
<p>The number of elements taken from the <code>i<sup>th</sup></code> row of <code>grid</code> does not exceed <code>limits[i]</code>.</p>
</li>
</ul>
<p data-pm-slice="1 1 []">Return the <strong>maximum sum</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[1,2],[3,4]], limits = [1,2], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the second row, we can take at most 2 elements. The elements taken are 4 and 3.</li>
<li>The maximum possible sum of at most 2 selected elements is <code>4 + 3 = 7</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">21</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>From the first row, we can take at most 2 elements. The element taken is 7.</li>
<li>From the second row, we can take at most 2 elements. The elements taken are 8 and 6.</li>
<li>The maximum possible sum of at most 3 selected elements is <code>7 + 8 + 6 = 21</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == limits.length</code></li>
<li><code>m == grid[i].length</code></li>
<li><code>1 <= n, m <= 500</code></li>
<li><code>0 <= grid[i][j] <= 10<sup>5</sup></code></li>
<li><code>0 <= limits[i] <= m</code></li>
<li><code>0 <= k <= min(n * m, sum(limits))</code></li>
</ul>
|
Greedy; Array; Matrix; Sorting; Heap (Priority Queue)
|
TypeScript
|
function maxSum(grid: number[][], limits: number[], k: number): number {
const pq = new MinPriorityQueue();
const n = grid.length;
for (let i = 0; i < n; i++) {
const nums = grid[i];
const limit = limits[i];
nums.sort((a, b) => a - b);
for (let j = 0; j < limit; j++) {
pq.enqueue(nums[nums.length - j - 1]);
if (pq.size() > k) {
pq.dequeue();
}
}
}
let ans = 0;
while (!pq.isEmpty()) {
ans += pq.dequeue() as number;
}
return ans;
}
|
3,465 |
Find Products with Valid Serial Numbers
|
Easy
|
<p>Table: <code>products</code></p>
<pre>
+--------------+------------+
| Column Name | Type |
+--------------+------------+
| product_id | int |
| product_name | varchar |
| description | varchar |
+--------------+------------+
(product_id) is the unique key for this table.
Each row in the table represents a product with its unique ID, name, and description.
</pre>
<p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p>
<ul>
<li>It starts with the letters <strong>SN</strong> (case-sensitive).</li>
<li>Followed by exactly <code>4</code> digits.</li>
<li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li>
<li>The serial number must be within the description (it may not necessarily start at the beginning).</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>product_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>products table:</p>
<pre class="example-io">
+------------+--------------+------------------------------------------------------+
| product_id | product_name | description |
+------------+--------------+------------------------------------------------------+
| 1 | Widget A | This is a sample product with SN1234-5678 |
| 2 | Widget B | A product with serial SN9876-1234 in the description |
| 3 | Widget C | Product SN1234-56789 is available now |
| 4 | Widget D | No serial number here |
| 5 | Widget E | Check out SN4321-8765 in this description |
+------------+--------------+------------------------------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+--------------+------------------------------------------------------+
| product_id | product_name | description |
+------------+--------------+------------------------------------------------------+
| 1 | Widget A | This is a sample product with SN1234-5678 |
| 2 | Widget B | A product with serial SN9876-1234 in the description |
| 5 | Widget E | Check out SN4321-8765 in this description |
+------------+--------------+------------------------------------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Product 1:</strong> Valid serial number SN1234-5678</li>
<li><strong>Product 2:</strong> Valid serial number SN9876-1234</li>
<li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li>
<li><strong>Product 4:</strong> No serial number in the description</li>
<li><strong>Product 5:</strong> Valid serial number SN4321-8765</li>
</ul>
<p>The result table is ordered by product_id in ascending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_valid_serial_products(products: pd.DataFrame) -> pd.DataFrame:
valid_pattern = r"\bSN[0-9]{4}-[0-9]{4}\b"
valid_products = products[
products["description"].str.contains(valid_pattern, regex=True)
]
valid_products = valid_products.sort_values(by="product_id")
return valid_products
|
3,465 |
Find Products with Valid Serial Numbers
|
Easy
|
<p>Table: <code>products</code></p>
<pre>
+--------------+------------+
| Column Name | Type |
+--------------+------------+
| product_id | int |
| product_name | varchar |
| description | varchar |
+--------------+------------+
(product_id) is the unique key for this table.
Each row in the table represents a product with its unique ID, name, and description.
</pre>
<p>Write a solution to find all products whose description <strong>contains a valid serial number</strong> pattern. A valid serial number follows these rules:</p>
<ul>
<li>It starts with the letters <strong>SN</strong> (case-sensitive).</li>
<li>Followed by exactly <code>4</code> digits.</li>
<li>It must have a hyphen (-) <strong>followed by exactly</strong> <code>4</code> digits.</li>
<li>The serial number must be within the description (it may not necessarily start at the beginning).</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>product_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>products table:</p>
<pre class="example-io">
+------------+--------------+------------------------------------------------------+
| product_id | product_name | description |
+------------+--------------+------------------------------------------------------+
| 1 | Widget A | This is a sample product with SN1234-5678 |
| 2 | Widget B | A product with serial SN9876-1234 in the description |
| 3 | Widget C | Product SN1234-56789 is available now |
| 4 | Widget D | No serial number here |
| 5 | Widget E | Check out SN4321-8765 in this description |
+------------+--------------+------------------------------------------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------+--------------+------------------------------------------------------+
| product_id | product_name | description |
+------------+--------------+------------------------------------------------------+
| 1 | Widget A | This is a sample product with SN1234-5678 |
| 2 | Widget B | A product with serial SN9876-1234 in the description |
| 5 | Widget E | Check out SN4321-8765 in this description |
+------------+--------------+------------------------------------------------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Product 1:</strong> Valid serial number SN1234-5678</li>
<li><strong>Product 2:</strong> Valid serial number SN9876-1234</li>
<li><strong>Product 3:</strong> Invalid serial number SN1234-56789 (contains 5 digits after the hyphen)</li>
<li><strong>Product 4:</strong> No serial number in the description</li>
<li><strong>Product 5:</strong> Valid serial number SN4321-8765</li>
</ul>
<p>The result table is ordered by product_id in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT product_id, product_name, description
FROM products
WHERE description REGEXP '\\bSN[0-9]{4}-[0-9]{4}\\b'
ORDER BY 1;
|
3,466 |
Maximum Coin Collection
|
Medium
|
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p>
<ul>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] > 0</code>, Mario gains <code>lane1[i]</code> coins.</li>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] < 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li>
<li>The same rules apply for <code>lane2</code>.</li>
</ul>
<p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p>
<p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p>
<p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p>
<p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario drives the first mile on lane 1.</li>
<li>He then changes to lane 2 and drives for two miles.</li>
<li>He changes back to lane 1 for the last mile.</li>
</ul>
<p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at mile 0 in lane 1 and drives one mile.</li>
<li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li>
</ul>
<p>He collects <code>1 + 3 + 4 = 8</code> coins.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li>
</ul>
<p>He collects a total of <code>2 + 3 = 5</code> coins.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p>
<p><strong>Output:</strong> 11</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li>
</ul>
<p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p>
</div>
<p><strong class="example">Example 5:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li>
</ul>
<p>He collects a total of -2 coins.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= lane1.length == lane2.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= lane1[i], lane2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
long long maxCoins(vector<int>& lane1, vector<int>& lane2) {
int n = lane1.size();
long long ans = -1e18;
vector<vector<vector<long long>>> f(n, vector<vector<long long>>(2, vector<long long>(3, -1e18)));
auto dfs = [&](this auto&& dfs, int i, int j, int k) -> long long {
if (i >= n) {
return 0LL;
}
if (f[i][j][k] != -1e18) {
return f[i][j][k];
}
int x = j == 0 ? lane1[i] : lane2[i];
long long ans = max((long long) x, dfs(i + 1, j, k) + x);
if (k > 0) {
ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x);
ans = max(ans, dfs(i, j ^ 1, k - 1));
}
return f[i][j][k] = ans;
};
for (int i = 0; i < n; ++i) {
ans = max(ans, dfs(i, 0, 2));
}
return ans;
}
};
|
3,466 |
Maximum Coin Collection
|
Medium
|
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p>
<ul>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] > 0</code>, Mario gains <code>lane1[i]</code> coins.</li>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] < 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li>
<li>The same rules apply for <code>lane2</code>.</li>
</ul>
<p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p>
<p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p>
<p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p>
<p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario drives the first mile on lane 1.</li>
<li>He then changes to lane 2 and drives for two miles.</li>
<li>He changes back to lane 1 for the last mile.</li>
</ul>
<p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at mile 0 in lane 1 and drives one mile.</li>
<li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li>
</ul>
<p>He collects <code>1 + 3 + 4 = 8</code> coins.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li>
</ul>
<p>He collects a total of <code>2 + 3 = 5</code> coins.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p>
<p><strong>Output:</strong> 11</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li>
</ul>
<p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p>
</div>
<p><strong class="example">Example 5:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li>
</ul>
<p>He collects a total of -2 coins.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= lane1.length == lane2.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= lane1[i], lane2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func maxCoins(lane1 []int, lane2 []int) int64 {
n := len(lane1)
f := make([][2][3]int64, n)
for i := range f {
for j := range f[i] {
for k := range f[i][j] {
f[i][j][k] = -1
}
}
}
var dfs func(int, int, int) int64
dfs = func(i, j, k int) int64 {
if i >= n {
return 0
}
if f[i][j][k] != -1 {
return f[i][j][k]
}
x := int64(lane1[i])
if j == 1 {
x = int64(lane2[i])
}
ans := max(x, dfs(i+1, j, k)+x)
if k > 0 {
ans = max(ans, dfs(i+1, j^1, k-1)+x)
ans = max(ans, dfs(i, j^1, k-1))
}
f[i][j][k] = ans
return ans
}
ans := int64(-1e18)
for i := range lane1 {
ans = max(ans, dfs(i, 0, 2))
}
return ans
}
|
3,466 |
Maximum Coin Collection
|
Medium
|
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p>
<ul>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] > 0</code>, Mario gains <code>lane1[i]</code> coins.</li>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] < 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li>
<li>The same rules apply for <code>lane2</code>.</li>
</ul>
<p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p>
<p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p>
<p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p>
<p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario drives the first mile on lane 1.</li>
<li>He then changes to lane 2 and drives for two miles.</li>
<li>He changes back to lane 1 for the last mile.</li>
</ul>
<p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at mile 0 in lane 1 and drives one mile.</li>
<li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li>
</ul>
<p>He collects <code>1 + 3 + 4 = 8</code> coins.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li>
</ul>
<p>He collects a total of <code>2 + 3 = 5</code> coins.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p>
<p><strong>Output:</strong> 11</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li>
</ul>
<p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p>
</div>
<p><strong class="example">Example 5:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li>
</ul>
<p>He collects a total of -2 coins.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= lane1.length == lane2.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= lane1[i], lane2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
private int n;
private int[] lane1;
private int[] lane2;
private Long[][][] f;
public long maxCoins(int[] lane1, int[] lane2) {
n = lane1.length;
this.lane1 = lane1;
this.lane2 = lane2;
f = new Long[n][2][3];
long ans = Long.MIN_VALUE;
for (int i = 0; i < n; ++i) {
ans = Math.max(ans, dfs(i, 0, 2));
}
return ans;
}
private long dfs(int i, int j, int k) {
if (i >= n) {
return 0;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int x = j == 0 ? lane1[i] : lane2[i];
long ans = Math.max(x, dfs(i + 1, j, k) + x);
if (k > 0) {
ans = Math.max(ans, dfs(i + 1, j ^ 1, k - 1) + x);
ans = Math.max(ans, dfs(i, j ^ 1, k - 1));
}
return f[i][j][k] = ans;
}
}
|
3,466 |
Maximum Coin Collection
|
Medium
|
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p>
<ul>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] > 0</code>, Mario gains <code>lane1[i]</code> coins.</li>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] < 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li>
<li>The same rules apply for <code>lane2</code>.</li>
</ul>
<p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p>
<p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p>
<p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p>
<p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario drives the first mile on lane 1.</li>
<li>He then changes to lane 2 and drives for two miles.</li>
<li>He changes back to lane 1 for the last mile.</li>
</ul>
<p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at mile 0 in lane 1 and drives one mile.</li>
<li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li>
</ul>
<p>He collects <code>1 + 3 + 4 = 8</code> coins.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li>
</ul>
<p>He collects a total of <code>2 + 3 = 5</code> coins.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p>
<p><strong>Output:</strong> 11</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li>
</ul>
<p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p>
</div>
<p><strong class="example">Example 5:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li>
</ul>
<p>He collects a total of -2 coins.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= lane1.length == lane2.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= lane1[i], lane2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def maxCoins(self, lane1: List[int], lane2: List[int]) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i >= n:
return 0
x = lane1[i] if j == 0 else lane2[i]
ans = max(x, dfs(i + 1, j, k) + x)
if k > 0:
ans = max(ans, dfs(i + 1, j ^ 1, k - 1) + x)
ans = max(ans, dfs(i, j ^ 1, k - 1))
return ans
n = len(lane1)
ans = -inf
for i in range(n):
ans = max(ans, dfs(i, 0, 2))
return ans
|
3,466 |
Maximum Coin Collection
|
Medium
|
<p>Mario drives on a two-lane freeway with coins every mile. You are given two integer arrays, <code>lane1</code> and <code>lane2</code>, where the value at the <code>i<sup>th</sup></code> index represents the number of coins he <em>gains or loses</em> in the <code>i<sup>th</sup></code> mile in that lane.</p>
<ul>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] > 0</code>, Mario gains <code>lane1[i]</code> coins.</li>
<li>If Mario is in lane 1 at mile <code>i</code> and <code>lane1[i] < 0</code>, Mario pays a toll and loses <code>abs(lane1[i])</code> coins.</li>
<li>The same rules apply for <code>lane2</code>.</li>
</ul>
<p>Mario can enter the freeway anywhere and exit anytime after traveling <strong>at least</strong> one mile. Mario always enters the freeway on lane 1 but can switch lanes <strong>at most</strong> 2 times.</p>
<p>A <strong>lane switch</strong> is when Mario goes from lane 1 to lane 2 or vice versa.</p>
<p>Return the <strong>maximum</strong> number of coins Mario can earn after performing <strong>at most 2 lane switches</strong>.</p>
<p><strong>Note:</strong> Mario can switch lanes immediately upon entering or just before exiting the freeway.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-2,-10,3], lane2 = [-5,10,0,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">14</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario drives the first mile on lane 1.</li>
<li>He then changes to lane 2 and drives for two miles.</li>
<li>He changes back to lane 1 for the last mile.</li>
</ul>
<p>Mario collects <code>1 + 10 + 0 + 3 = 14</code> coins.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [1,-1,-1,-1], lane2 = [0,3,4,-5]</span></p>
<p><strong>Output:</strong> <span class="example-io">8</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at mile 0 in lane 1 and drives one mile.</li>
<li>He then changes to lane 2 and drives for two more miles. He exits the freeway before mile 3.</li>
</ul>
<p>He collects <code>1 + 3 + 4 = 8</code> coins.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-5,-4,-3], lane2 = [-1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario enters at mile 1 and immediately switches to lane 2. He stays here the entire way.</li>
</ul>
<p>He collects a total of <code>2 + 3 = 5</code> coins.</p>
</div>
<p><strong class="example">Example 4:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-3,-3,-3], lane2 = [9,-2,4]</span></p>
<p><strong>Output:</strong> 11</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Mario starts at the beginning of the freeway and immediately switches to lane 2. He stays here the whole way.</li>
</ul>
<p>He collects a total of <code>9 + (-2) + 4 = 11</code> coins.</p>
</div>
<p><strong class="example">Example 5:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">lane1 = [-10], lane2 = [-2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Since Mario must ride on the freeway for at least one mile, he rides just one mile in lane 2.</li>
</ul>
<p>He collects a total of -2 coins.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= lane1.length == lane2.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= lane1[i], lane2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function maxCoins(lane1: number[], lane2: number[]): number {
const n = lane1.length;
const NEG_INF = -1e18;
const f: number[][][] = Array.from({ length: n }, () =>
Array.from({ length: 2 }, () => Array(3).fill(NEG_INF)),
);
const dfs = (dfs: Function, i: number, j: number, k: number): number => {
if (i >= n) {
return 0;
}
if (f[i][j][k] !== NEG_INF) {
return f[i][j][k];
}
const x = j === 0 ? lane1[i] : lane2[i];
let ans = Math.max(x, dfs(dfs, i + 1, j, k) + x);
if (k > 0) {
ans = Math.max(ans, dfs(dfs, i + 1, j ^ 1, k - 1) + x);
ans = Math.max(ans, dfs(dfs, i, j ^ 1, k - 1));
}
f[i][j][k] = ans;
return ans;
};
let ans = NEG_INF;
for (let i = 0; i < n; ++i) {
ans = Math.max(ans, dfs(dfs, i, 0, 2));
}
return ans;
}
|
3,467 |
Transform Array by Parity
|
Easy
|
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p>
<ol>
<li>Replace each even number with 0.</li>
<li>Replace each odd numbers with 1.</li>
<li>Sort the modified array in <strong>non-decreasing</strong> order.</li>
</ol>
<p>Return the resulting array after performing these operations.</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,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Counting; Sorting
|
C++
|
class Solution {
public:
vector<int> transformArray(vector<int>& nums) {
int even = 0;
for (int x : nums) {
even += (x & 1 ^ 1);
}
for (int i = 0; i < even; ++i) {
nums[i] = 0;
}
for (int i = even; i < nums.size(); ++i) {
nums[i] = 1;
}
return nums;
}
};
|
3,467 |
Transform Array by Parity
|
Easy
|
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p>
<ol>
<li>Replace each even number with 0.</li>
<li>Replace each odd numbers with 1.</li>
<li>Sort the modified array in <strong>non-decreasing</strong> order.</li>
</ol>
<p>Return the resulting array after performing these operations.</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,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Counting; Sorting
|
Go
|
func transformArray(nums []int) []int {
even := 0
for _, x := range nums {
even += x&1 ^ 1
}
for i := 0; i < even; i++ {
nums[i] = 0
}
for i := even; i < len(nums); i++ {
nums[i] = 1
}
return nums
}
|
3,467 |
Transform Array by Parity
|
Easy
|
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p>
<ol>
<li>Replace each even number with 0.</li>
<li>Replace each odd numbers with 1.</li>
<li>Sort the modified array in <strong>non-decreasing</strong> order.</li>
</ol>
<p>Return the resulting array after performing these operations.</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,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Counting; Sorting
|
Java
|
class Solution {
public int[] transformArray(int[] nums) {
int even = 0;
for (int x : nums) {
even += (x & 1 ^ 1);
}
for (int i = 0; i < even; ++i) {
nums[i] = 0;
}
for (int i = even; i < nums.length; ++i) {
nums[i] = 1;
}
return nums;
}
}
|
3,467 |
Transform Array by Parity
|
Easy
|
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p>
<ol>
<li>Replace each even number with 0.</li>
<li>Replace each odd numbers with 1.</li>
<li>Sort the modified array in <strong>non-decreasing</strong> order.</li>
</ol>
<p>Return the resulting array after performing these operations.</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,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Counting; Sorting
|
Python
|
class Solution:
def transformArray(self, nums: List[int]) -> List[int]:
even = sum(x % 2 == 0 for x in nums)
for i in range(even):
nums[i] = 0
for i in range(even, len(nums)):
nums[i] = 1
return nums
|
3,467 |
Transform Array by Parity
|
Easy
|
<p>You are given an integer array <code>nums</code>. Transform <code>nums</code> by performing the following operations in the <strong>exact</strong> order specified:</p>
<ol>
<li>Replace each even number with 0.</li>
<li>Replace each odd numbers with 1.</li>
<li>Sort the modified array in <strong>non-decreasing</strong> order.</li>
</ol>
<p>Return the resulting array after performing these operations.</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,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (3 and 1) with 1. Now, <code>nums = [0, 1, 0, 1]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,1,4,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,1,1,1]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace the even numbers (4 and 2) with 0 and the odd numbers (1, 5 and 1) with 1. Now, <code>nums = [1, 1, 1, 0, 0]</code>.</li>
<li>After sorting <code>nums</code> in non-descending order, <code>nums = [0, 0, 1, 1, 1]</code>.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Counting; Sorting
|
TypeScript
|
function transformArray(nums: number[]): number[] {
const even = nums.filter(x => x % 2 === 0).length;
for (let i = 0; i < even; ++i) {
nums[i] = 0;
}
for (let i = even; i < nums.length; ++i) {
nums[i] = 1;
}
return nums;
}
|
3,471 |
Find the Largest Almost Missing Integer
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p>
<p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p>
A <strong>subarray</strong> is a contiguous sequence of elements within an array.
<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,2,1,7], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li>
<li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li>
<li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li>
<li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li>
</ul>
<p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li>
<li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li>
</ul>
<p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no integer that appears in only one subarray of size 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int largestInteger(vector<int>& nums, int k) {
if (k == 1) {
unordered_map<int, int> cnt;
for (int x : nums) {
++cnt[x];
}
int ans = -1;
for (auto& [x, v] : cnt) {
if (v == 1) {
ans = max(ans, x);
}
}
return ans;
}
int n = nums.size();
if (k == n) {
return ranges::max(nums);
}
auto f = [&](int k) -> int {
for (int i = 0; i < n; ++i) {
if (i != k && nums[i] == nums[k]) {
return -1;
}
}
return nums[k];
};
return max(f(0), f(n - 1));
}
};
|
3,471 |
Find the Largest Almost Missing Integer
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p>
<p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p>
A <strong>subarray</strong> is a contiguous sequence of elements within an array.
<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,2,1,7], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li>
<li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li>
<li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li>
<li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li>
</ul>
<p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li>
<li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li>
</ul>
<p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no integer that appears in only one subarray of size 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func largestInteger(nums []int, k int) int {
if k == 1 {
cnt := make(map[int]int)
for _, x := range nums {
cnt[x]++
}
ans := -1
for x, v := range cnt {
if v == 1 {
ans = max(ans, x)
}
}
return ans
}
n := len(nums)
if k == n {
return slices.Max(nums)
}
f := func(k int) int {
for i, x := range nums {
if i != k && x == nums[k] {
return -1
}
}
return nums[k]
}
return max(f(0), f(n-1))
}
|
3,471 |
Find the Largest Almost Missing Integer
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p>
<p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p>
A <strong>subarray</strong> is a contiguous sequence of elements within an array.
<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,2,1,7], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li>
<li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li>
<li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li>
<li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li>
</ul>
<p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li>
<li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li>
</ul>
<p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no integer that appears in only one subarray of size 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
private int[] nums;
public int largestInteger(int[] nums, int k) {
this.nums = nums;
if (k == 1) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int ans = -1;
for (var e : cnt.entrySet()) {
if (e.getValue() == 1) {
ans = Math.max(ans, e.getKey());
}
}
return ans;
}
if (k == nums.length) {
return Arrays.stream(nums).max().getAsInt();
}
return Math.max(f(0), f(nums.length - 1));
}
private int f(int k) {
for (int i = 0; i < nums.length; ++i) {
if (i != k && nums[i] == nums[k]) {
return -1;
}
}
return nums[k];
}
}
|
3,471 |
Find the Largest Almost Missing Integer
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p>
<p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p>
A <strong>subarray</strong> is a contiguous sequence of elements within an array.
<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,2,1,7], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li>
<li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li>
<li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li>
<li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li>
</ul>
<p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li>
<li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li>
</ul>
<p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no integer that appears in only one subarray of size 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def largestInteger(self, nums: List[int], k: int) -> int:
def f(k: int) -> int:
for i, x in enumerate(nums):
if i != k and x == nums[k]:
return -1
return nums[k]
if k == 1:
cnt = Counter(nums)
return max((x for x, v in cnt.items() if v == 1), default=-1)
if k == len(nums):
return max(nums)
return max(f(0), f(len(nums) - 1))
|
3,471 |
Find the Largest Almost Missing Integer
|
Easy
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>An integer <code>x</code> is <strong>almost missing</strong> from <code>nums</code> if <code>x</code> appears in <em>exactly</em> one subarray of size <code>k</code> within <code>nums</code>.</p>
<p>Return the <b>largest</b> <strong>almost missing</strong> integer from <code>nums</code>. If no such integer exists, return <code>-1</code>.</p>
A <strong>subarray</strong> is a contiguous sequence of elements within an array.
<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,2,1,7], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 3: <code>[9, 2, 1]</code> and <code>[2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 3: <code>[3, 9, 2]</code>, <code>[9, 2, 1]</code>, <code>[2, 1, 7]</code>.</li>
<li index="2">3 appears in 1 subarray of size 3: <code>[3, 9, 2]</code>.</li>
<li index="3">7 appears in 1 subarray of size 3: <code>[2, 1, 7]</code>.</li>
<li index="4">9 appears in 2 subarrays of size 3: <code>[3, 9, 2]</code>, and <code>[9, 2, 1]</code>.</li>
</ul>
<p>We return 7 since it is the largest integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,9,7,2,1,7], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>1 appears in 2 subarrays of size 4: <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>2 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>3 appears in 1 subarray of size 4: <code>[3, 9, 7, 2]</code>.</li>
<li>7 appears in 3 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>, <code>[7, 2, 1, 7]</code>.</li>
<li>9 appears in 2 subarrays of size 4: <code>[3, 9, 7, 2]</code>, <code>[9, 7, 2, 1]</code>.</li>
</ul>
<p>We return 3 since it is the largest and only integer that appears in exactly one subarray of size <code>k</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,0], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no integer that appears in only one subarray of size 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function largestInteger(nums: number[], k: number): number {
if (k === 1) {
const cnt = new Map<number, number>();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
let ans = -1;
for (const [x, v] of cnt.entries()) {
if (v === 1 && x > ans) {
ans = x;
}
}
return ans;
}
const n = nums.length;
if (k === n) {
return Math.max(...nums);
}
const f = (k: number): number => {
for (let i = 0; i < n; i++) {
if (i !== k && nums[i] === nums[k]) {
return -1;
}
}
return nums[k];
};
return Math.max(f(0), f(n - 1));
}
|
3,472 |
Longest Palindromic Subsequence After at Most K Operations
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>'a'</code> is after <code>'z'</code>). For example, replacing <code>'a'</code> with the next letter results in <code>'b'</code>, and replacing <code>'a'</code> with the previous letter results in <code>'z'</code>. Similarly, replacing <code>'z'</code> with the next letter results in <code>'a'</code>, and replacing <code>'z'</code> with the previous letter results in <code>'y'</code>.</p>
<p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abced", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>"acced"</code>.</li>
<li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>"accec"</code>.</li>
</ul>
<p>The subsequence <code>"ccc"</code> forms a palindrome of length 3, which is the maximum.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "</span>aaazzz<span class="example-io">", k = 4</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>"zaazzz"</code>.</li>
<li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>"zaazaz"</code>.</li>
<li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>"zaaaaz"</code>.</li>
</ul>
<p>The entire string forms a palindrome of length 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 200</code></li>
<li><code>1 <= k <= 200</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int longestPalindromicSubsequence(string s, int k) {
int n = s.size();
vector f(n, vector(n, vector<int>(k + 1, -1)));
auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int {
if (i > j) {
return 0;
}
if (i == j) {
return 1;
}
if (f[i][j][k] != -1) {
return f[i][j][k];
}
int res = max(dfs(i + 1, j, k), dfs(i, j - 1, k));
int d = abs(s[i] - s[j]);
int t = min(d, 26 - d);
if (t <= k) {
res = max(res, 2 + dfs(i + 1, j - 1, k - t));
}
return f[i][j][k] = res;
};
return dfs(0, n - 1, k);
}
};
|
3,472 |
Longest Palindromic Subsequence After at Most K Operations
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>'a'</code> is after <code>'z'</code>). For example, replacing <code>'a'</code> with the next letter results in <code>'b'</code>, and replacing <code>'a'</code> with the previous letter results in <code>'z'</code>. Similarly, replacing <code>'z'</code> with the next letter results in <code>'a'</code>, and replacing <code>'z'</code> with the previous letter results in <code>'y'</code>.</p>
<p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abced", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>"acced"</code>.</li>
<li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>"accec"</code>.</li>
</ul>
<p>The subsequence <code>"ccc"</code> forms a palindrome of length 3, which is the maximum.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "</span>aaazzz<span class="example-io">", k = 4</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>"zaazzz"</code>.</li>
<li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>"zaazaz"</code>.</li>
<li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>"zaaaaz"</code>.</li>
</ul>
<p>The entire string forms a palindrome of length 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 200</code></li>
<li><code>1 <= k <= 200</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func longestPalindromicSubsequence(s string, k int) int {
n := len(s)
f := make([][][]int, n)
for i := range f {
f[i] = make([][]int, n)
for j := range f[i] {
f[i][j] = make([]int, k+1)
for l := range f[i][j] {
f[i][j][l] = -1
}
}
}
var dfs func(int, int, int) int
dfs = func(i, j, k int) int {
if i > j {
return 0
}
if i == j {
return 1
}
if f[i][j][k] != -1 {
return f[i][j][k]
}
res := max(dfs(i+1, j, k), dfs(i, j-1, k))
d := abs(int(s[i]) - int(s[j]))
t := min(d, 26-d)
if t <= k {
res = max(res, 2+dfs(i+1, j-1, k-t))
}
f[i][j][k] = res
return res
}
return dfs(0, n-1, k)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,472 |
Longest Palindromic Subsequence After at Most K Operations
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>'a'</code> is after <code>'z'</code>). For example, replacing <code>'a'</code> with the next letter results in <code>'b'</code>, and replacing <code>'a'</code> with the previous letter results in <code>'z'</code>. Similarly, replacing <code>'z'</code> with the next letter results in <code>'a'</code>, and replacing <code>'z'</code> with the previous letter results in <code>'y'</code>.</p>
<p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abced", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>"acced"</code>.</li>
<li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>"accec"</code>.</li>
</ul>
<p>The subsequence <code>"ccc"</code> forms a palindrome of length 3, which is the maximum.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "</span>aaazzz<span class="example-io">", k = 4</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>"zaazzz"</code>.</li>
<li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>"zaazaz"</code>.</li>
<li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>"zaaaaz"</code>.</li>
</ul>
<p>The entire string forms a palindrome of length 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 200</code></li>
<li><code>1 <= k <= 200</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
private char[] s;
private Integer[][][] f;
public int longestPalindromicSubsequence(String s, int k) {
this.s = s.toCharArray();
int n = s.length();
f = new Integer[n][n][k + 1];
return dfs(0, n - 1, k);
}
private int dfs(int i, int j, int k) {
if (i > j) {
return 0;
}
if (i == j) {
return 1;
}
if (f[i][j][k] != null) {
return f[i][j][k];
}
int res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k));
int d = Math.abs(s[i] - s[j]);
int t = Math.min(d, 26 - d);
if (t <= k) {
res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t));
}
f[i][j][k] = res;
return res;
}
}
|
3,472 |
Longest Palindromic Subsequence After at Most K Operations
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>'a'</code> is after <code>'z'</code>). For example, replacing <code>'a'</code> with the next letter results in <code>'b'</code>, and replacing <code>'a'</code> with the previous letter results in <code>'z'</code>. Similarly, replacing <code>'z'</code> with the next letter results in <code>'a'</code>, and replacing <code>'z'</code> with the previous letter results in <code>'y'</code>.</p>
<p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abced", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>"acced"</code>.</li>
<li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>"accec"</code>.</li>
</ul>
<p>The subsequence <code>"ccc"</code> forms a palindrome of length 3, which is the maximum.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "</span>aaazzz<span class="example-io">", k = 4</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>"zaazzz"</code>.</li>
<li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>"zaazaz"</code>.</li>
<li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>"zaaaaz"</code>.</li>
</ul>
<p>The entire string forms a palindrome of length 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 200</code></li>
<li><code>1 <= k <= 200</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def longestPalindromicSubsequence(self, s: str, k: int) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i > j:
return 0
if i == j:
return 1
res = max(dfs(i + 1, j, k), dfs(i, j - 1, k))
d = abs(s[i] - s[j])
t = min(d, 26 - d)
if t <= k:
res = max(res, dfs(i + 1, j - 1, k - t) + 2)
return res
s = list(map(ord, s))
n = len(s)
ans = dfs(0, n - 1, k)
dfs.cache_clear()
return ans
|
3,472 |
Longest Palindromic Subsequence After at Most K Operations
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that <code>'a'</code> is after <code>'z'</code>). For example, replacing <code>'a'</code> with the next letter results in <code>'b'</code>, and replacing <code>'a'</code> with the previous letter results in <code>'z'</code>. Similarly, replacing <code>'z'</code> with the next letter results in <code>'a'</code>, and replacing <code>'z'</code> with the previous letter results in <code>'y'</code>.</p>
<p>Return the length of the <strong>longest <span data-keyword="palindrome-string">palindromic</span> <span data-keyword="subsequence-string-nonempty">subsequence</span></strong> of <code>s</code> that can be obtained after performing <strong>at most</strong> <code>k</code> operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abced", k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[1]</code> with the next letter, and <code>s</code> becomes <code>"acced"</code>.</li>
<li>Replace <code>s[4]</code> with the previous letter, and <code>s</code> becomes <code>"accec"</code>.</li>
</ul>
<p>The subsequence <code>"ccc"</code> forms a palindrome of length 3, which is the maximum.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "</span>aaazzz<span class="example-io">", k = 4</span></p>
<p><strong>Output:</strong> 6</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Replace <code>s[0]</code> with the previous letter, and <code>s</code> becomes <code>"zaazzz"</code>.</li>
<li>Replace <code>s[4]</code> with the next letter, and <code>s</code> becomes <code>"zaazaz"</code>.</li>
<li>Replace <code>s[3]</code> with the next letter, and <code>s</code> becomes <code>"zaaaaz"</code>.</li>
</ul>
<p>The entire string forms a palindrome of length 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 200</code></li>
<li><code>1 <= k <= 200</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function longestPalindromicSubsequence(s: string, k: number): number {
const n = s.length;
const sCodes = s.split('').map(c => c.charCodeAt(0));
const f: number[][][] = Array.from({ length: n }, () =>
Array.from({ length: n }, () => Array(k + 1).fill(-1)),
);
function dfs(i: number, j: number, k: number): number {
if (i > j) {
return 0;
}
if (i === j) {
return 1;
}
if (f[i][j][k] !== -1) {
return f[i][j][k];
}
let res = Math.max(dfs(i + 1, j, k), dfs(i, j - 1, k));
const d = Math.abs(sCodes[i] - sCodes[j]);
const t = Math.min(d, 26 - d);
if (t <= k) {
res = Math.max(res, 2 + dfs(i + 1, j - 1, k - t));
}
return (f[i][j][k] = res);
}
return dfs(0, n - 1, k);
}
|
3,475 |
DNA Pattern Recognition
|
Medium
|
<p>Table: <code>Samples</code></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| sample_id | int |
| dna_sequence | varchar |
| species | varchar |
+----------------+---------+
sample_id is the unique key for this table.
Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from.
</pre>
<p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p>
<ul>
<li>Sequences that <strong>start</strong> with <strong>ATG</strong> (a common <strong>start codon</strong>)</li>
<li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong> (<strong>stop codons</strong>)</li>
<li>Sequences containing the motif <strong>ATAT</strong> (a simple repeated pattern)</li>
<li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong> (like <strong>GGG</strong> or <strong>GGGG</strong>)</li>
</ul>
<p>Return <em>the result table ordered by </em><em>sample_id 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>Samples table:</p>
<pre class="example-io">
+-----------+------------------+-----------+
| sample_id | dna_sequence | species |
+-----------+------------------+-----------+
| 1 | ATGCTAGCTAGCTAA | Human |
| 2 | GGGTCAATCATC | Human |
| 3 | ATATATCGTAGCTA | Human |
| 4 | ATGGGGTCATCATAA | Mouse |
| 5 | TCAGTCAGTCAG | Mouse |
| 6 | ATATCGCGCTAG | Zebrafish |
| 7 | CGTATGCGTCGTA | Zebrafish |
+-----------+------------------+-----------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+------------------+-------------+-------------+------------+------------+------------+
| sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg |
+-----------+------------------+-------------+-------------+------------+------------+------------+
| 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 |
| 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 |
| 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 |
| 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 |
| 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 |
| 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 |
| 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 |
+-----------+------------------+-------------+-------------+------------+------------+------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Sample 1 (ATGCTAGCTAGCTAA):
<ul>
<li>Starts with ATG (has_start = 1)</li>
<li>Ends with TAA (has_stop = 1)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 2 (GGGTCAATCATC):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, TAG, or TGA (has_stop = 0)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Contains GGG (has_ggg = 1)</li>
</ul>
</li>
<li>Sample 3 (ATATATCGTAGCTA):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, TAG, or TGA (has_stop = 0)</li>
<li>Contains ATAT (has_atat = 1)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 4 (ATGGGGTCATCATAA):
<ul>
<li>Starts with ATG (has_start = 1)</li>
<li>Ends with TAA (has_stop = 1)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Contains GGGG (has_ggg = 1)</li>
</ul>
</li>
<li>Sample 5 (TCAGTCAGTCAG):
<ul>
<li>Does not match any patterns (all fields = 0)</li>
</ul>
</li>
<li>Sample 6 (ATATCGCGCTAG):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Ends with TAG (has_stop = 1)</li>
<li>Starts with ATAT (has_atat = 1)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 7 (CGTATGCGTCGTA):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, "TAG", or "TGA" (has_stop = 0)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong></p>
<ul>
<li>The result is ordered by sample_id in ascending order</li>
<li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def analyze_dna_patterns(samples: pd.DataFrame) -> pd.DataFrame:
samples["has_start"] = samples["dna_sequence"].str.startswith("ATG").astype(int)
samples["has_stop"] = (
samples["dna_sequence"].str.endswith(("TAA", "TAG", "TGA")).astype(int)
)
samples["has_atat"] = samples["dna_sequence"].str.contains("ATAT").astype(int)
samples["has_ggg"] = samples["dna_sequence"].str.contains("GGG+").astype(int)
return samples.sort_values(by="sample_id").reset_index(drop=True)
|
3,475 |
DNA Pattern Recognition
|
Medium
|
<p>Table: <code>Samples</code></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| sample_id | int |
| dna_sequence | varchar |
| species | varchar |
+----------------+---------+
sample_id is the unique key for this table.
Each row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from.
</pre>
<p>Biologists are studying basic patterns in DNA sequences. Write a solution to identify <code>sample_id</code> with the following patterns:</p>
<ul>
<li>Sequences that <strong>start</strong> with <strong>ATG</strong> (a common <strong>start codon</strong>)</li>
<li>Sequences that <strong>end</strong> with either <strong>TAA</strong>, <strong>TAG</strong>, or <strong>TGA</strong> (<strong>stop codons</strong>)</li>
<li>Sequences containing the motif <strong>ATAT</strong> (a simple repeated pattern)</li>
<li>Sequences that have <strong>at least</strong> <code>3</code> <strong>consecutive</strong> <strong>G</strong> (like <strong>GGG</strong> or <strong>GGGG</strong>)</li>
</ul>
<p>Return <em>the result table ordered by </em><em>sample_id 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>Samples table:</p>
<pre class="example-io">
+-----------+------------------+-----------+
| sample_id | dna_sequence | species |
+-----------+------------------+-----------+
| 1 | ATGCTAGCTAGCTAA | Human |
| 2 | GGGTCAATCATC | Human |
| 3 | ATATATCGTAGCTA | Human |
| 4 | ATGGGGTCATCATAA | Mouse |
| 5 | TCAGTCAGTCAG | Mouse |
| 6 | ATATCGCGCTAG | Zebrafish |
| 7 | CGTATGCGTCGTA | Zebrafish |
+-----------+------------------+-----------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+------------------+-------------+-------------+------------+------------+------------+
| sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg |
+-----------+------------------+-------------+-------------+------------+------------+------------+
| 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 |
| 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 |
| 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 |
| 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 |
| 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 |
| 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 |
| 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 |
+-----------+------------------+-------------+-------------+------------+------------+------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Sample 1 (ATGCTAGCTAGCTAA):
<ul>
<li>Starts with ATG (has_start = 1)</li>
<li>Ends with TAA (has_stop = 1)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 2 (GGGTCAATCATC):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, TAG, or TGA (has_stop = 0)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Contains GGG (has_ggg = 1)</li>
</ul>
</li>
<li>Sample 3 (ATATATCGTAGCTA):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, TAG, or TGA (has_stop = 0)</li>
<li>Contains ATAT (has_atat = 1)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 4 (ATGGGGTCATCATAA):
<ul>
<li>Starts with ATG (has_start = 1)</li>
<li>Ends with TAA (has_stop = 1)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Contains GGGG (has_ggg = 1)</li>
</ul>
</li>
<li>Sample 5 (TCAGTCAGTCAG):
<ul>
<li>Does not match any patterns (all fields = 0)</li>
</ul>
</li>
<li>Sample 6 (ATATCGCGCTAG):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Ends with TAG (has_stop = 1)</li>
<li>Starts with ATAT (has_atat = 1)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
<li>Sample 7 (CGTATGCGTCGTA):
<ul>
<li>Does not start with ATG (has_start = 0)</li>
<li>Does not end with TAA, "TAG", or "TGA" (has_stop = 0)</li>
<li>Does not contain ATAT (has_atat = 0)</li>
<li>Does not contain at least 3 consecutive 'G's (has_ggg = 0)</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong></p>
<ul>
<li>The result is ordered by sample_id in ascending order</li>
<li>For each pattern, 1 indicates the pattern is present and 0 indicates it is not present</li>
</ul>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
sample_id,
dna_sequence,
species,
dna_sequence LIKE 'ATG%' AS has_start,
dna_sequence REGEXP 'TAA$|TAG$|TGA$' AS has_stop,
dna_sequence LIKE '%ATAT%' AS has_atat,
dna_sequence REGEXP 'GGG+' AS has_ggg
FROM Samples
ORDER BY 1;
|
3,476 |
Maximize Profit from Task Assignment
|
Medium
|
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p>
<ul>
<li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li>
<li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li>
</ul>
<p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task's skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p>
<p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1000</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Worker 0 completes task 0.</li>
<li>Worker 1 completes task 1.</li>
<li>Worker 2 completes task 3.</li>
<li>The additional worker completes task 2.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p>
<p><strong>Output:</strong> <span class="example-io">100</span></p>
<p><strong>Explanation:</strong></p>
<p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= workers.length <= 10<sup>5</sup></code></li>
<li><code>1 <= workers[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>tasks[i].length == 2</code></li>
<li><code>1 <= tasks[i][0], tasks[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long maxProfit(vector<int>& workers, vector<vector<int>>& tasks) {
unordered_map<int, priority_queue<int>> d;
for (const auto& t : tasks) {
d[t[0]].push(t[1]);
}
long long ans = 0;
for (int skill : workers) {
if (d.contains(skill)) {
auto& pq = d[skill];
ans += pq.top();
pq.pop();
if (pq.empty()) {
d.erase(skill);
}
}
}
int mx = 0;
for (const auto& [_, pq] : d) {
mx = max(mx, pq.top());
}
ans += mx;
return ans;
}
};
|
3,476 |
Maximize Profit from Task Assignment
|
Medium
|
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p>
<ul>
<li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li>
<li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li>
</ul>
<p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task's skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p>
<p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1000</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Worker 0 completes task 0.</li>
<li>Worker 1 completes task 1.</li>
<li>Worker 2 completes task 3.</li>
<li>The additional worker completes task 2.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p>
<p><strong>Output:</strong> <span class="example-io">100</span></p>
<p><strong>Explanation:</strong></p>
<p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= workers.length <= 10<sup>5</sup></code></li>
<li><code>1 <= workers[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>tasks[i].length == 2</code></li>
<li><code>1 <= tasks[i][0], tasks[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Go
|
func maxProfit(workers []int, tasks [][]int) (ans int64) {
d := make(map[int]*hp)
for _, t := range tasks {
skill, profit := t[0], t[1]
if _, ok := d[skill]; !ok {
d[skill] = &hp{}
}
d[skill].push(profit)
}
for _, skill := range workers {
if _, ok := d[skill]; !ok {
continue
}
ans += int64(d[skill].pop())
if d[skill].Len() == 0 {
delete(d, skill)
}
}
mx := 0
for _, pq := range d {
for pq.Len() > 0 {
mx = max(mx, pq.pop())
}
}
ans += int64(mx)
return
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
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
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
|
3,476 |
Maximize Profit from Task Assignment
|
Medium
|
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p>
<ul>
<li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li>
<li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li>
</ul>
<p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task's skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p>
<p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1000</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Worker 0 completes task 0.</li>
<li>Worker 1 completes task 1.</li>
<li>Worker 2 completes task 3.</li>
<li>The additional worker completes task 2.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p>
<p><strong>Output:</strong> <span class="example-io">100</span></p>
<p><strong>Explanation:</strong></p>
<p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= workers.length <= 10<sup>5</sup></code></li>
<li><code>1 <= workers[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>tasks[i].length == 2</code></li>
<li><code>1 <= tasks[i][0], tasks[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long maxProfit(int[] workers, int[][] tasks) {
Map<Integer, PriorityQueue<Integer>> d = new HashMap<>();
for (var t : tasks) {
int skill = t[0], profit = t[1];
d.computeIfAbsent(skill, k -> new PriorityQueue<>((a, b) -> b - a)).offer(profit);
}
long ans = 0;
for (int skill : workers) {
if (d.containsKey(skill)) {
var pq = d.get(skill);
ans += pq.poll();
if (pq.isEmpty()) {
d.remove(skill);
}
}
}
int mx = 0;
for (var pq : d.values()) {
mx = Math.max(mx, pq.peek());
}
ans += mx;
return ans;
}
}
|
3,476 |
Maximize Profit from Task Assignment
|
Medium
|
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p>
<ul>
<li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li>
<li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li>
</ul>
<p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task's skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p>
<p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1000</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Worker 0 completes task 0.</li>
<li>Worker 1 completes task 1.</li>
<li>Worker 2 completes task 3.</li>
<li>The additional worker completes task 2.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p>
<p><strong>Output:</strong> <span class="example-io">100</span></p>
<p><strong>Explanation:</strong></p>
<p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= workers.length <= 10<sup>5</sup></code></li>
<li><code>1 <= workers[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>tasks[i].length == 2</code></li>
<li><code>1 <= tasks[i][0], tasks[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def maxProfit(self, workers: List[int], tasks: List[List[int]]) -> int:
d = defaultdict(SortedList)
for skill, profit in tasks:
d[skill].add(profit)
ans = 0
for skill in workers:
if not d[skill]:
continue
ans += d[skill].pop()
mx = 0
for ls in d.values():
if ls:
mx = max(mx, ls[-1])
ans += mx
return ans
|
3,476 |
Maximize Profit from Task Assignment
|
Medium
|
<p>You are given an integer array <code>workers</code>, where <code>workers[i]</code> represents the skill level of the <code>i<sup>th</sup></code> worker. You are also given a 2D integer array <code>tasks</code>, where:</p>
<ul>
<li><code>tasks[i][0]</code> represents the skill requirement needed to complete the task.</li>
<li><code>tasks[i][1]</code> represents the profit earned from completing the task.</li>
</ul>
<p>Each worker can complete <strong>at most</strong> one task, and they can only take a task if their skill level is <strong>equal</strong> to the task's skill requirement. An <strong>additional</strong> worker joins today who can take up <em>any</em> task, <strong>regardless</strong> of the skill requirement.</p>
<p>Return the <strong>maximum</strong> total profit that can be earned by optimally assigning the tasks to the workers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [1,2,3,4,5], tasks = [[1,100],[2,400],[3,100],[3,400]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1000</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Worker 0 completes task 0.</li>
<li>Worker 1 completes task 1.</li>
<li>Worker 2 completes task 3.</li>
<li>The additional worker completes task 2.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [10,10000,100000000], tasks = [[1,100]]</span></p>
<p><strong>Output:</strong> <span class="example-io">100</span></p>
<p><strong>Explanation:</strong></p>
<p>Since no worker matches the skill requirement, only the additional worker can complete task 0.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">workers = [7], tasks = [[3,3],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The additional worker completes task 1. Worker 0 cannot work since no task has a skill requirement of 7.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= workers.length <= 10<sup>5</sup></code></li>
<li><code>1 <= workers[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>tasks[i].length == 2</code></li>
<li><code>1 <= tasks[i][0], tasks[i][1] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
TypeScript
|
function maxProfit(workers: number[], tasks: number[][]): number {
const d = new Map();
for (const [skill, profit] of tasks) {
if (!d.has(skill)) {
d.set(skill, new MaxPriorityQueue());
}
d.get(skill).enqueue(profit);
}
let ans = 0;
for (const skill of workers) {
const pq = d.get(skill);
if (pq) {
ans += pq.dequeue();
if (pq.size() === 0) {
d.delete(skill);
}
}
}
let mx = 0;
for (const pq of d.values()) {
mx = Math.max(mx, pq.front());
}
ans += mx;
return ans;
}
|
3,477 |
Fruits Into Baskets II
|
Easy
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= fruits[i], baskets[i] <= 1000</code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set; Simulation
|
C++
|
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
int n = fruits.size();
vector<bool> vis(n);
int ans = n;
for (int x : fruits) {
for (int i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
};
|
3,477 |
Fruits Into Baskets II
|
Easy
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= fruits[i], baskets[i] <= 1000</code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set; Simulation
|
Go
|
func numOfUnplacedFruits(fruits []int, baskets []int) int {
n := len(fruits)
ans := n
vis := make([]bool, n)
for _, x := range fruits {
for i, y := range baskets {
if y >= x && !vis[i] {
vis[i] = true
ans--
break
}
}
}
return ans
}
|
3,477 |
Fruits Into Baskets II
|
Easy
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= fruits[i], baskets[i] <= 1000</code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set; Simulation
|
Java
|
class Solution {
public int numOfUnplacedFruits(int[] fruits, int[] baskets) {
int n = fruits.length;
boolean[] vis = new boolean[n];
int ans = n;
for (int x : fruits) {
for (int i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
}
|
3,477 |
Fruits Into Baskets II
|
Easy
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= fruits[i], baskets[i] <= 1000</code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set; Simulation
|
Python
|
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
n = len(fruits)
vis = [False] * n
ans = n
for x in fruits:
for i, y in enumerate(baskets):
if y >= x and not vis[i]:
vis[i] = True
ans -= 1
break
return ans
|
3,477 |
Fruits Into Baskets II
|
Easy
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 100</code></li>
<li><code>1 <= fruits[i], baskets[i] <= 1000</code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set; Simulation
|
TypeScript
|
function numOfUnplacedFruits(fruits: number[], baskets: number[]): number {
const n = fruits.length;
const vis: boolean[] = Array(n).fill(false);
let ans = n;
for (const x of fruits) {
for (let i = 0; i < n; ++i) {
if (baskets[i] >= x && !vis[i]) {
vis[i] = true;
--ans;
break;
}
}
}
return ans;
}
|
3,478 |
Choose K Elements With Maximum Sum
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p>
<p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p>
<ul>
<li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li>
<li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li>
</ul>
<p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] < nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] < nums1[1]</code>, resulting in 30.</li>
<li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] < nums1[2]</code>, resulting in 0.</li>
<li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] < nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] < nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] < nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<long long> findMaxSum(vector<int>& nums1, vector<int>& nums2, int k) {
int n = nums1.size();
vector<pair<int, int>> arr(n);
for (int i = 0; i < n; ++i) {
arr[i] = {nums1[i], i};
}
ranges::sort(arr);
priority_queue<int, vector<int>, greater<int>> pq;
long long s = 0;
int j = 0;
vector<long long> ans(n);
for (int h = 0; h < n; ++h) {
auto [x, i] = arr[h];
while (j < h && arr[j].first < x) {
int y = nums2[arr[j].second];
pq.push(y);
s += y;
if (pq.size() > k) {
s -= pq.top();
pq.pop();
}
++j;
}
ans[i] = s;
}
return ans;
}
};
|
3,478 |
Choose K Elements With Maximum Sum
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p>
<p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p>
<ul>
<li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li>
<li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li>
</ul>
<p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] < nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] < nums1[1]</code>, resulting in 30.</li>
<li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] < nums1[2]</code>, resulting in 0.</li>
<li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] < nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] < nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] < nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sorting; Heap (Priority Queue)
|
Go
|
func findMaxSum(nums1 []int, nums2 []int, k int) []int64 {
n := len(nums1)
arr := make([][2]int, n)
for i, x := range nums1 {
arr[i] = [2]int{x, i}
}
ans := make([]int64, n)
sort.Slice(arr, func(i, j int) bool { return arr[i][0] < arr[j][0] })
pq := hp{}
var s int64
j := 0
for h, e := range arr {
x, i := e[0], e[1]
for j < h && arr[j][0] < x {
y := nums2[arr[j][1]]
heap.Push(&pq, y)
s += int64(y)
if pq.Len() > k {
s -= int64(heap.Pop(&pq).(int))
}
j++
}
ans[i] = s
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
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,478 |
Choose K Elements With Maximum Sum
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p>
<p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p>
<ul>
<li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li>
<li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li>
</ul>
<p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] < nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] < nums1[1]</code>, resulting in 30.</li>
<li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] < nums1[2]</code>, resulting in 0.</li>
<li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] < nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] < nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] < nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long[] findMaxSum(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
int[][] arr = new int[n][0];
for (int i = 0; i < n; ++i) {
arr[i] = new int[] {nums1[i], i};
}
Arrays.sort(arr, (a, b) -> a[0] - b[0]);
PriorityQueue<Integer> pq = new PriorityQueue<>();
long s = 0;
long[] ans = new long[n];
int j = 0;
for (int h = 0; h < n; ++h) {
int x = arr[h][0], i = arr[h][1];
while (j < h && arr[j][0] < x) {
int y = nums2[arr[j][1]];
pq.offer(y);
s += y;
if (pq.size() > k) {
s -= pq.poll();
}
++j;
}
ans[i] = s;
}
return ans;
}
}
|
3,478 |
Choose K Elements With Maximum Sum
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p>
<p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p>
<ul>
<li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li>
<li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li>
</ul>
<p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] < nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] < nums1[1]</code>, resulting in 30.</li>
<li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] < nums1[2]</code>, resulting in 0.</li>
<li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] < nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] < nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] < nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def findMaxSum(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
arr = [(x, i) for i, x in enumerate(nums1)]
arr.sort()
pq = []
s = j = 0
n = len(arr)
ans = [0] * n
for h, (x, i) in enumerate(arr):
while j < h and arr[j][0] < x:
y = nums2[arr[j][1]]
heappush(pq, y)
s += y
if len(pq) > k:
s -= heappop(pq)
j += 1
ans[i] = s
return ans
|
3,478 |
Choose K Elements With Maximum Sum
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, both of length <code>n</code>, along with a positive integer <code>k</code>.</p>
<p>For each index <code>i</code> from <code>0</code> to <code>n - 1</code>, perform the following:</p>
<ul>
<li>Find <strong>all</strong> indices <code>j</code> where <code>nums1[j]</code> is less than <code>nums1[i]</code>.</li>
<li>Choose <strong>at most</strong> <code>k</code> values of <code>nums2[j]</code> at these indices to <strong>maximize</strong> the total sum.</li>
</ul>
<p>Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> represents the result for the corresponding index <code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[80,30,0,80,50]</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2, 4]</code> where <code>nums1[j] < nums1[0]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 1</code>: Select the 2 largest values from <code>nums2</code> at index <code>[2]</code> where <code>nums1[j] < nums1[1]</code>, resulting in 30.</li>
<li>For <code>i = 2</code>: No indices satisfy <code>nums1[j] < nums1[2]</code>, resulting in 0.</li>
<li>For <code>i = 3</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[0, 1, 2, 4]</code> where <code>nums1[j] < nums1[3]</code>, resulting in <code>50 + 30 = 80</code>.</li>
<li>For <code>i = 4</code>: Select the 2 largest values from <code>nums2</code> at indices <code>[1, 2]</code> where <code>nums1[j] < nums1[4]</code>, resulting in <code>30 + 20 = 50</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,0,0,0]</span></p>
<p><strong>Explanation:</strong></p>
<p>Since all elements in <code>nums1</code> are equal, no indices satisfy the condition <code>nums1[j] < nums1[i]</code> for any <code>i</code>, resulting in 0 for all positions.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Array; Sorting; Heap (Priority Queue)
|
TypeScript
|
function findMaxSum(nums1: number[], nums2: number[], k: number): number[] {
const n = nums1.length;
const arr = nums1.map((x, i) => [x, i]).sort((a, b) => a[0] - b[0]);
const pq = new MinPriorityQueue();
let [s, j] = [0, 0];
const ans: number[] = Array(k).fill(0);
for (let h = 0; h < n; ++h) {
const [x, i] = arr[h];
while (j < h && arr[j][0] < x) {
const y = nums2[arr[j++][1]];
pq.enqueue(y);
s += y;
if (pq.size() > k) {
s -= pq.dequeue();
}
}
ans[i] = s;
}
return ans;
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
C++
|
class SegmentTree {
public:
vector<int> nums, tr;
SegmentTree(vector<int>& nums) {
this->nums = nums;
int n = nums.size();
tr.resize(n * 4);
build(1, 1, n);
}
void build(int u, int l, int r) {
if (l == r) {
tr[u] = nums[l - 1];
return;
}
int mid = (l + r) >> 1;
build(u * 2, l, mid);
build(u * 2 + 1, mid + 1, r);
pushup(u);
}
void modify(int u, int l, int r, int i, int v) {
if (l == r) {
tr[u] = v;
return;
}
int mid = (l + r) >> 1;
if (i <= mid) {
modify(u * 2, l, mid, i, v);
} else {
modify(u * 2 + 1, mid + 1, r, i, v);
}
pushup(u);
}
int query(int u, int l, int r, int v) {
if (tr[u] < v) {
return -1;
}
if (l == r) {
return l;
}
int mid = (l + r) >> 1;
if (tr[u * 2] >= v) {
return query(u * 2, l, mid, v);
}
return query(u * 2 + 1, mid + 1, r, v);
}
void pushup(int u) {
tr[u] = max(tr[u * 2], tr[u * 2 + 1]);
}
};
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
SegmentTree tree(baskets);
int n = baskets.size();
int ans = 0;
for (int x : fruits) {
int i = tree.query(1, 1, n, x);
if (i < 0) {
ans++;
} else {
tree.modify(1, 1, n, i, 0);
}
}
return ans;
}
};
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
C#
|
public class SegmentTree {
int[] nums;
int[] tr;
public SegmentTree(int[] nums) {
this.nums = nums;
int n = nums.Length;
this.tr = new int[n << 2];
Build(1, 1, n);
}
public void Build(int u, int l, int r) {
if (l == r) {
tr[u] = nums[l - 1];
return;
}
int mid = (l + r) >> 1;
Build(u << 1, l, mid);
Build(u << 1 | 1, mid + 1, r);
Pushup(u);
}
public void Modify(int u, int l, int r, int i, int v) {
if (l == r) {
tr[u] = v;
return;
}
int mid = (l + r) >> 1;
if (i <= mid) {
Modify(u << 1, l, mid, i, v);
} else {
Modify(u << 1 | 1, mid + 1, r, i, v);
}
Pushup(u);
}
public int Query(int u, int l, int r, int v) {
if (tr[u] < v) {
return -1;
}
if (l == r) {
return l;
}
int mid = (l + r) >> 1;
if (tr[u << 1] >= v) {
return Query(u << 1, l, mid, v);
}
return Query(u << 1 | 1, mid + 1, r, v);
}
public void Pushup(int u) {
tr[u] = Math.Max(tr[u << 1], tr[u << 1 | 1]);
}
}
public class Solution {
public int NumOfUnplacedFruits(int[] fruits, int[] baskets) {
SegmentTree tree = new SegmentTree(baskets);
int n = baskets.Length;
int ans = 0;
foreach (var x in fruits) {
int i = tree.Query(1, 1, n, x);
if (i < 0) {
ans++;
} else {
tree.Modify(1, 1, n, i, 0);
}
}
return ans;
}
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
Go
|
type SegmentTree struct {
nums, tr []int
}
func NewSegmentTree(nums []int) *SegmentTree {
n := len(nums)
tree := &SegmentTree{
nums: nums,
tr: make([]int, n*4),
}
tree.build(1, 1, n)
return tree
}
func (st *SegmentTree) build(u, l, r int) {
if l == r {
st.tr[u] = st.nums[l-1]
return
}
mid := (l + r) >> 1
st.build(u*2, l, mid)
st.build(u*2+1, mid+1, r)
st.pushup(u)
}
func (st *SegmentTree) modify(u, l, r, i, v int) {
if l == r {
st.tr[u] = v
return
}
mid := (l + r) >> 1
if i <= mid {
st.modify(u*2, l, mid, i, v)
} else {
st.modify(u*2+1, mid+1, r, i, v)
}
st.pushup(u)
}
func (st *SegmentTree) query(u, l, r, v int) int {
if st.tr[u] < v {
return -1
}
if l == r {
return l
}
mid := (l + r) >> 1
if st.tr[u*2] >= v {
return st.query(u*2, l, mid, v)
}
return st.query(u*2+1, mid+1, r, v)
}
func (st *SegmentTree) pushup(u int) {
st.tr[u] = max(st.tr[u*2], st.tr[u*2+1])
}
func numOfUnplacedFruits(fruits []int, baskets []int) (ans int) {
tree := NewSegmentTree(baskets)
n := len(baskets)
for _, x := range fruits {
i := tree.query(1, 1, n, x)
if i < 0 {
ans++
} else {
tree.modify(1, 1, n, i, 0)
}
}
return
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
Java
|
class SegmentTree {
int[] nums;
int[] tr;
public SegmentTree(int[] nums) {
this.nums = nums;
int n = nums.length;
this.tr = new int[n << 2];
build(1, 1, n);
}
public void build(int u, int l, int r) {
if (l == r) {
tr[u] = nums[l - 1];
return;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
public void modify(int u, int l, int r, int i, int v) {
if (l == r) {
tr[u] = v;
return;
}
int mid = (l + r) >> 1;
if (i <= mid) {
modify(u << 1, l, mid, i, v);
} else {
modify(u << 1 | 1, mid + 1, r, i, v);
}
pushup(u);
}
public int query(int u, int l, int r, int v) {
if (tr[u] < v) {
return -1;
}
if (l == r) {
return l;
}
int mid = (l + r) >> 1;
if (tr[u << 1] >= v) {
return query(u << 1, l, mid, v);
}
return query(u << 1 | 1, mid + 1, r, v);
}
public void pushup(int u) {
tr[u] = Math.max(tr[u << 1], tr[u << 1 | 1]);
}
}
class Solution {
public int numOfUnplacedFruits(int[] fruits, int[] baskets) {
SegmentTree tree = new SegmentTree(baskets);
int n = baskets.length;
int ans = 0;
for (int x : fruits) {
int i = tree.query(1, 1, n, x);
if (i < 0) {
ans++;
} else {
tree.modify(1, 1, n, i, 0);
}
}
return ans;
}
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
Python
|
class SegmentTree:
__slots__ = ["nums", "tr"]
def __init__(self, nums):
self.nums = nums
n = len(nums)
self.tr = [0] * (n << 2)
self.build(1, 1, n)
def build(self, u, l, r):
if l == r:
self.tr[u] = self.nums[l - 1]
return
mid = (l + r) >> 1
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
self.pushup(u)
def modify(self, u, l, r, i, v):
if l == r:
self.tr[u] = v
return
mid = (l + r) >> 1
if i <= mid:
self.modify(u << 1, l, mid, i, v)
else:
self.modify(u << 1 | 1, mid + 1, r, i, v)
self.pushup(u)
def query(self, u, l, r, v):
if self.tr[u] < v:
return -1
if l == r:
return l
mid = (l + r) >> 1
if self.tr[u << 1] >= v:
return self.query(u << 1, l, mid, v)
return self.query(u << 1 | 1, mid + 1, r, v)
def pushup(self, u):
self.tr[u] = max(self.tr[u << 1], self.tr[u << 1 | 1])
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
tree = SegmentTree(baskets)
n = len(baskets)
ans = 0
for x in fruits:
i = tree.query(1, 1, n, x)
if i < 0:
ans += 1
else:
tree.modify(1, 1, n, i, 0)
return ans
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
Rust
|
struct SegmentTree<'a> {
nums: &'a [i32],
tr: Vec<i32>,
}
impl<'a> SegmentTree<'a> {
fn new(nums: &'a [i32]) -> Self {
let n = nums.len();
let mut tree = SegmentTree {
nums,
tr: vec![0; n * 4],
};
tree.build(1, 1, n);
tree
}
fn build(&mut self, u: usize, l: usize, r: usize) {
if l == r {
self.tr[u] = self.nums[l - 1];
return;
}
let mid = (l + r) >> 1;
self.build(u * 2, l, mid);
self.build(u * 2 + 1, mid + 1, r);
self.pushup(u);
}
fn modify(&mut self, u: usize, l: usize, r: usize, i: usize, v: i32) {
if l == r {
self.tr[u] = v;
return;
}
let mid = (l + r) >> 1;
if i <= mid {
self.modify(u * 2, l, mid, i, v);
} else {
self.modify(u * 2 + 1, mid + 1, r, i, v);
}
self.pushup(u);
}
fn query(&self, u: usize, l: usize, r: usize, v: i32) -> i32 {
if self.tr[u] < v {
return -1;
}
if l == r {
return l as i32;
}
let mid = (l + r) >> 1;
if self.tr[u * 2] >= v {
return self.query(u * 2, l, mid, v);
}
self.query(u * 2 + 1, mid + 1, r, v)
}
fn pushup(&mut self, u: usize) {
self.tr[u] = self.tr[u * 2].max(self.tr[u * 2 + 1]);
}
}
impl Solution {
pub fn num_of_unplaced_fruits(fruits: Vec<i32>, baskets: Vec<i32>) -> i32 {
let mut tree = SegmentTree::new(&baskets);
let n = baskets.len();
let mut ans = 0;
for &x in fruits.iter() {
let i = tree.query(1, 1, n, x);
if i < 0 {
ans += 1;
} else {
tree.modify(1, 1, n, i as usize, 0);
}
}
ans
}
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
Swift
|
class SegmentTree {
var nums: [Int]
var tr: [Int]
init(_ nums: [Int]) {
self.nums = nums
let n = nums.count
self.tr = [Int](repeating: 0, count: n << 2)
build(1, 1, n)
}
func build(_ u: Int, _ l: Int, _ r: Int) {
if l == r {
tr[u] = nums[l - 1]
return
}
let mid = (l + r) >> 1
build(u << 1, l, mid)
build(u << 1 | 1, mid + 1, r)
pushup(u)
}
func modify(_ u: Int, _ l: Int, _ r: Int, _ i: Int, _ v: Int) {
if l == r {
tr[u] = v
return
}
let mid = (l + r) >> 1
if i <= mid {
modify(u << 1, l, mid, i, v)
} else {
modify(u << 1 | 1, mid + 1, r, i, v)
}
pushup(u)
}
func query(_ u: Int, _ l: Int, _ r: Int, _ v: Int) -> Int {
if tr[u] < v {
return -1
}
if l == r {
return l
}
let mid = (l + r) >> 1
if tr[u << 1] >= v {
return query(u << 1, l, mid, v)
}
return query(u << 1 | 1, mid + 1, r, v)
}
func pushup(_ u: Int) {
tr[u] = max(tr[u << 1], tr[u << 1 | 1])
}
}
class Solution {
func numOfUnplacedFruits(_ fruits: [Int], _ baskets: [Int]) -> Int {
let tree = SegmentTree(baskets)
let n = baskets.count
var ans = 0
for x in fruits {
let i = tree.query(1, 1, n, x)
if i < 0 {
ans += 1
} else {
tree.modify(1, 1, n, i, 0)
}
}
return ans
}
}
|
3,479 |
Fruits Into Baskets III
|
Medium
|
<p>You are given two arrays of integers, <code>fruits</code> and <code>baskets</code>, each of length <code>n</code>, where <code>fruits[i]</code> represents the <strong>quantity</strong> of the <code>i<sup>th</sup></code> type of fruit, and <code>baskets[j]</code> represents the <strong>capacity</strong> of the <code>j<sup>th</sup></code> basket.</p>
<p>From left to right, place the fruits according to these rules:</p>
<ul>
<li>Each fruit type must be placed in the <strong>leftmost available basket</strong> with a capacity <strong>greater than or equal</strong> to the quantity of that fruit type.</li>
<li>Each basket can hold <b>only one</b> type of fruit.</li>
<li>If a fruit type <b>cannot be placed</b> in any basket, it remains <b>unplaced</b>.</li>
</ul>
<p>Return the number of fruit types that remain unplaced after all possible allocations are made.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [4,2,5], baskets = [3,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 4</code> is placed in <code>baskets[1] = 5</code>.</li>
<li><code>fruits[1] = 2</code> is placed in <code>baskets[0] = 3</code>.</li>
<li><code>fruits[2] = 5</code> cannot be placed in <code>baskets[2] = 4</code>.</li>
</ul>
<p>Since one fruit type remains unplaced, we return 1.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">fruits = [3,6,1], baskets = [6,4,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><code>fruits[0] = 3</code> is placed in <code>baskets[0] = 6</code>.</li>
<li><code>fruits[1] = 6</code> cannot be placed in <code>baskets[1] = 4</code> (insufficient capacity) but can be placed in the next available basket, <code>baskets[2] = 7</code>.</li>
<li><code>fruits[2] = 1</code> is placed in <code>baskets[1] = 4</code>.</li>
</ul>
<p>Since all fruits are successfully placed, we return 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == fruits.length == baskets.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= fruits[i], baskets[i] <= 10<sup>9</sup></code></li>
</ul>
|
Segment Tree; Array; Binary Search; Ordered Set
|
TypeScript
|
class SegmentTree {
nums: number[];
tr: number[];
constructor(nums: number[]) {
this.nums = nums;
const n = nums.length;
this.tr = Array(n * 4).fill(0);
this.build(1, 1, n);
}
build(u: number, l: number, r: number): void {
if (l === r) {
this.tr[u] = this.nums[l - 1];
return;
}
const mid = (l + r) >> 1;
this.build(u * 2, l, mid);
this.build(u * 2 + 1, mid + 1, r);
this.pushup(u);
}
modify(u: number, l: number, r: number, i: number, v: number): void {
if (l === r) {
this.tr[u] = v;
return;
}
const mid = (l + r) >> 1;
if (i <= mid) {
this.modify(u * 2, l, mid, i, v);
} else {
this.modify(u * 2 + 1, mid + 1, r, i, v);
}
this.pushup(u);
}
query(u: number, l: number, r: number, v: number): number {
if (this.tr[u] < v) {
return -1;
}
if (l === r) {
return l;
}
const mid = (l + r) >> 1;
if (this.tr[u * 2] >= v) {
return this.query(u * 2, l, mid, v);
}
return this.query(u * 2 + 1, mid + 1, r, v);
}
pushup(u: number): void {
this.tr[u] = Math.max(this.tr[u * 2], this.tr[u * 2 + 1]);
}
}
function numOfUnplacedFruits(fruits: number[], baskets: number[]): number {
const tree = new SegmentTree(baskets);
const n = baskets.length;
let ans = 0;
for (const x of fruits) {
const i = tree.query(1, 1, n, x);
if (i < 0) {
ans++;
} else {
tree.modify(1, 1, n, i, 0);
}
}
return ans;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.