id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
2,903
|
Find Indices With Index and Value Difference I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= indexDifference <= 100</code></li>
<li><code>0 <= valueDifference <= 50</code></li>
</ul>
|
Array; Two Pointers
|
Go
|
func findIndices(nums []int, indexDifference int, valueDifference int) []int {
mi, mx := 0, 0
for i := indexDifference; i < len(nums); i++ {
j := i - indexDifference
if nums[j] < nums[mi] {
mi = j
}
if nums[j] > nums[mx] {
mx = j
}
if nums[i]-nums[mi] >= valueDifference {
return []int{mi, i}
}
if nums[mx]-nums[i] >= valueDifference {
return []int{mx, i}
}
}
return []int{-1, -1}
}
|
2,903
|
Find Indices With Index and Value Difference I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= indexDifference <= 100</code></li>
<li><code>0 <= valueDifference <= 50</code></li>
</ul>
|
Array; Two Pointers
|
Java
|
class Solution {
public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
int mi = 0;
int mx = 0;
for (int i = indexDifference; i < nums.length; ++i) {
int j = i - indexDifference;
if (nums[j] < nums[mi]) {
mi = j;
}
if (nums[j] > nums[mx]) {
mx = j;
}
if (nums[i] - nums[mi] >= valueDifference) {
return new int[] {mi, i};
}
if (nums[mx] - nums[i] >= valueDifference) {
return new int[] {mx, i};
}
}
return new int[] {-1, -1};
}
}
|
2,903
|
Find Indices With Index and Value Difference I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= indexDifference <= 100</code></li>
<li><code>0 <= valueDifference <= 50</code></li>
</ul>
|
Array; Two Pointers
|
Python
|
class Solution:
def findIndices(
self, nums: List[int], indexDifference: int, valueDifference: int
) -> List[int]:
mi = mx = 0
for i in range(indexDifference, len(nums)):
j = i - indexDifference
if nums[j] < nums[mi]:
mi = j
if nums[j] > nums[mx]:
mx = j
if nums[i] - nums[mi] >= valueDifference:
return [mi, i]
if nums[mx] - nums[i] >= valueDifference:
return [mx, i]
return [-1, -1]
|
2,903
|
Find Indices With Index and Value Difference I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= indexDifference <= 100</code></li>
<li><code>0 <= valueDifference <= 50</code></li>
</ul>
|
Array; Two Pointers
|
Rust
|
impl Solution {
pub fn find_indices(nums: Vec<i32>, index_difference: i32, value_difference: i32) -> Vec<i32> {
let index_difference = index_difference as usize;
let mut mi = 0;
let mut mx = 0;
for i in index_difference..nums.len() {
let j = i - index_difference;
if nums[j] < nums[mi] {
mi = j;
}
if nums[j] > nums[mx] {
mx = j;
}
if nums[i] - nums[mi] >= value_difference {
return vec![mi as i32, i as i32];
}
if nums[mx] - nums[i] >= value_difference {
return vec![mx as i32, i as i32];
}
}
vec![-1, -1]
}
}
|
2,903
|
Find Indices With Index and Value Difference I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 50</code></li>
<li><code>0 <= indexDifference <= 100</code></li>
<li><code>0 <= valueDifference <= 50</code></li>
</ul>
|
Array; Two Pointers
|
TypeScript
|
function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] {
let [mi, mx] = [0, 0];
for (let i = indexDifference; i < nums.length; ++i) {
const j = i - indexDifference;
if (nums[j] < nums[mi]) {
mi = j;
}
if (nums[j] > nums[mx]) {
mx = j;
}
if (nums[i] - nums[mi] >= valueDifference) {
return [mi, i];
}
if (nums[mx] - nums[i] >= valueDifference) {
return [mx, i];
}
}
return [-1, -1];
}
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
C++
|
class Solution {
public:
string shortestBeautifulSubstring(string s, int k) {
int n = s.size();
string ans = "";
for (int i = 0; i < n; ++i) {
for (int j = i + k; j <= n; ++j) {
string t = s.substr(i, j - i);
int cnt = count(t.begin(), t.end(), '1');
if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) {
ans = t;
}
}
}
return ans;
}
};
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
Go
|
func shortestBeautifulSubstring(s string, k int) (ans string) {
n := len(s)
for i := 0; i < n; i++ {
for j := i + k; j <= n; j++ {
t := s[i:j]
cnt := 0
for _, c := range t {
if c == '1' {
cnt++
}
}
if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) {
ans = t
}
}
}
return
}
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
Java
|
class Solution {
public String shortestBeautifulSubstring(String s, int k) {
int n = s.length();
String ans = "";
for (int i = 0; i < n; ++i) {
for (int j = i + k; j <= n; ++j) {
String t = s.substring(i, j);
int cnt = 0;
for (char c : t.toCharArray()) {
cnt += c - '0';
}
if (cnt == k
&& ("".equals(ans) || j - i < ans.length()
|| (j - i == ans.length() && t.compareTo(ans) < 0))) {
ans = t;
}
}
}
return ans;
}
}
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
Python
|
class Solution:
def shortestBeautifulSubstring(self, s: str, k: int) -> str:
n = len(s)
ans = ""
for i in range(n):
for j in range(i + k, n + 1):
t = s[i:j]
if t.count("1") == k and (
not ans or j - i < len(ans) or (j - i == len(ans) and t < ans)
):
ans = t
return ans
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
Rust
|
impl Solution {
pub fn shortest_beautiful_substring(s: String, k: i32) -> String {
let n = s.len();
let mut ans = String::new();
for i in 0..n {
for j in i + (k as usize)..=n {
let t = &s[i..j];
if (t.matches('1').count() as i32) == k
&& (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans))
{
ans = t.to_string();
}
}
}
ans
}
}
|
2,904
|
Shortest and Lexicographically Smallest Beautiful String
|
Medium
|
<p>You are given a binary string <code>s</code> and a positive integer <code>k</code>.</p>
<p>A substring of <code>s</code> is <strong>beautiful</strong> if the number of <code>1</code>'s in it is exactly <code>k</code>.</p>
<p>Let <code>len</code> be the length of the <strong>shortest</strong> beautiful substring.</p>
<p>Return <em>the lexicographically <strong>smallest</strong> beautiful substring of string </em><code>s</code><em> with length equal to </em><code>len</code>. If <code>s</code> doesn't contain a beautiful substring, return <em>an <strong>empty</strong> string</em>.</p>
<p>A string <code>a</code> is lexicographically <strong>larger</strong> than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p>
<ul>
<li>For example, <code>"abcd"</code> is lexicographically larger than <code>"abcc"</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "100011001", k = 3
<strong>Output:</strong> "11001"
<strong>Explanation:</strong> There are 7 beautiful substrings in this example:
1. The substring "<u>100011</u>001".
2. The substring "<u>1000110</u>01".
3. The substring "<u>10001100</u>1".
4. The substring "1<u>00011001</u>".
5. The substring "10<u>0011001</u>".
6. The substring "100<u>011001</u>".
7. The substring "1000<u>11001</u>".
The length of the shortest beautiful substring is 5.
The lexicographically smallest beautiful substring with length 5 is the substring "11001".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "1011", k = 2
<strong>Output:</strong> "11"
<strong>Explanation:</strong> There are 3 beautiful substrings in this example:
1. The substring "<u>101</u>1".
2. The substring "1<u>011</u>".
3. The substring "10<u>11</u>".
The length of the shortest beautiful substring is 2.
The lexicographically smallest beautiful substring with length 2 is the substring "11".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "000", k = 1
<strong>Output:</strong> ""
<strong>Explanation:</strong> There are no beautiful substrings in this example.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= s.length</code></li>
</ul>
|
String; Sliding Window
|
TypeScript
|
function shortestBeautifulSubstring(s: string, k: number): string {
const n = s.length;
let ans: string = '';
for (let i = 0; i < n; ++i) {
for (let j = i + k; j <= n; ++j) {
const t = s.slice(i, j);
const cnt = t.split('').filter(c => c === '1').length;
if (
cnt === k &&
(ans === '' || j - i < ans.length || (j - i === ans.length && t < ans))
) {
ans = t;
}
}
}
return ans;
}
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
C++
|
class Solution {
public:
vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {
int mi = 0, mx = 0;
for (int i = indexDifference; i < nums.size(); ++i) {
int j = i - indexDifference;
if (nums[j] < nums[mi]) {
mi = j;
}
if (nums[j] > nums[mx]) {
mx = j;
}
if (nums[i] - nums[mi] >= valueDifference) {
return {mi, i};
}
if (nums[mx] - nums[i] >= valueDifference) {
return {mx, i};
}
}
return {-1, -1};
}
};
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
Go
|
func findIndices(nums []int, indexDifference int, valueDifference int) []int {
mi, mx := 0, 0
for i := indexDifference; i < len(nums); i++ {
j := i - indexDifference
if nums[j] < nums[mi] {
mi = j
}
if nums[j] > nums[mx] {
mx = j
}
if nums[i]-nums[mi] >= valueDifference {
return []int{mi, i}
}
if nums[mx]-nums[i] >= valueDifference {
return []int{mx, i}
}
}
return []int{-1, -1}
}
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
Java
|
class Solution {
public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
int mi = 0;
int mx = 0;
for (int i = indexDifference; i < nums.length; ++i) {
int j = i - indexDifference;
if (nums[j] < nums[mi]) {
mi = j;
}
if (nums[j] > nums[mx]) {
mx = j;
}
if (nums[i] - nums[mi] >= valueDifference) {
return new int[] {mi, i};
}
if (nums[mx] - nums[i] >= valueDifference) {
return new int[] {mx, i};
}
}
return new int[] {-1, -1};
}
}
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
Python
|
class Solution:
def findIndices(
self, nums: List[int], indexDifference: int, valueDifference: int
) -> List[int]:
mi = mx = 0
for i in range(indexDifference, len(nums)):
j = i - indexDifference
if nums[j] < nums[mi]:
mi = j
if nums[j] > nums[mx]:
mx = j
if nums[i] - nums[mi] >= valueDifference:
return [mi, i]
if nums[mx] - nums[i] >= valueDifference:
return [mx, i]
return [-1, -1]
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
Rust
|
impl Solution {
pub fn find_indices(nums: Vec<i32>, index_difference: i32, value_difference: i32) -> Vec<i32> {
let index_difference = index_difference as usize;
let mut mi = 0;
let mut mx = 0;
for i in index_difference..nums.len() {
let j = i - index_difference;
if nums[j] < nums[mi] {
mi = j;
}
if nums[j] > nums[mx] {
mx = j;
}
if nums[i] - nums[mi] >= value_difference {
return vec![mi as i32, i as i32];
}
if nums[mx] - nums[i] >= value_difference {
return vec![mx as i32, i as i32];
}
}
vec![-1, -1]
}
}
|
2,905
|
Find Indices With Index and Value Difference II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, an integer <code>indexDifference</code>, and an integer <code>valueDifference</code>.</p>
<p>Your task is to find <strong>two</strong> indices <code>i</code> and <code>j</code>, both in the range <code>[0, n - 1]</code>, that satisfy the following conditions:</p>
<ul>
<li><code>abs(i - j) >= indexDifference</code>, and</li>
<li><code>abs(nums[i] - nums[j]) >= valueDifference</code></li>
</ul>
<p>Return <em>an integer array</em> <code>answer</code>, <em>where</em> <code>answer = [i, j]</code> <em>if there are two such indices</em>, <em>and</em> <code>answer = [-1, -1]</code> <em>otherwise</em>. If there are multiple choices for the two indices, return <em>any of them</em>.</p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be <strong>equal</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [0,3]
<strong>Explanation:</strong> In this example, i = 0 and j = 3 can be selected.
abs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.
Hence, a valid answer is [0,3].
[3,0] is also a valid answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1], indexDifference = 0, valueDifference = 0
<strong>Output:</strong> [0,0]
<strong>Explanation:</strong> In this example, i = 0 and j = 0 can be selected.
abs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.
Hence, a valid answer is [0,0].
Other valid answers are [0,1], [1,0], and [1,1].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3], indexDifference = 2, valueDifference = 4
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.
Hence, [-1,-1] is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= indexDifference <= 10<sup>5</sup></code></li>
<li><code>0 <= valueDifference <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers
|
TypeScript
|
function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] {
let [mi, mx] = [0, 0];
for (let i = indexDifference; i < nums.length; ++i) {
const j = i - indexDifference;
if (nums[j] < nums[mi]) {
mi = j;
}
if (nums[j] > nums[mx]) {
mx = j;
}
if (nums[i] - nums[mi] >= valueDifference) {
return [mi, i];
}
if (nums[mx] - nums[i] >= valueDifference) {
return [mx, i];
}
}
return [-1, -1];
}
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
C++
|
class Solution {
public:
vector<vector<int>> constructProductMatrix(vector<vector<int>>& grid) {
const int mod = 12345;
int n = grid.size(), m = grid[0].size();
vector<vector<int>> p(n, vector<int>(m));
long long suf = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
p[i][j] = suf;
suf = suf * grid[i][j] % mod;
}
}
long long pre = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
p[i][j] = p[i][j] * pre % mod;
pre = pre * grid[i][j] % mod;
}
}
return p;
}
};
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Go
|
func constructProductMatrix(grid [][]int) [][]int {
const mod int = 12345
n, m := len(grid), len(grid[0])
p := make([][]int, n)
for i := range p {
p[i] = make([]int, m)
}
suf := 1
for i := n - 1; i >= 0; i-- {
for j := m - 1; j >= 0; j-- {
p[i][j] = suf
suf = suf * grid[i][j] % mod
}
}
pre := 1
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
p[i][j] = p[i][j] * pre % mod
pre = pre * grid[i][j] % mod
}
}
return p
}
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Java
|
class Solution {
public int[][] constructProductMatrix(int[][] grid) {
final int mod = 12345;
int n = grid.length, m = grid[0].length;
int[][] p = new int[n][m];
long suf = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
p[i][j] = (int) suf;
suf = suf * grid[i][j] % mod;
}
}
long pre = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
p[i][j] = (int) (p[i][j] * pre % mod);
pre = pre * grid[i][j] % mod;
}
}
return p;
}
}
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Python
|
class Solution:
def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n, m = len(grid), len(grid[0])
p = [[0] * m for _ in range(n)]
mod = 12345
suf = 1
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
p[i][j] = suf
suf = suf * grid[i][j] % mod
pre = 1
for i in range(n):
for j in range(m):
p[i][j] = p[i][j] * pre % mod
pre = pre * grid[i][j] % mod
return p
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Rust
|
impl Solution {
pub fn construct_product_matrix(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let modulo: i32 = 12345;
let n = grid.len();
let m = grid[0].len();
let mut p: Vec<Vec<i32>> = vec![vec![0; m]; n];
let mut suf = 1;
for i in (0..n).rev() {
for j in (0..m).rev() {
p[i][j] = suf;
suf = (((suf as i64) * (grid[i][j] as i64)) % (modulo as i64)) as i32;
}
}
let mut pre = 1;
for i in 0..n {
for j in 0..m {
p[i][j] = (((p[i][j] as i64) * (pre as i64)) % (modulo as i64)) as i32;
pre = (((pre as i64) * (grid[i][j] as i64)) % (modulo as i64)) as i32;
}
}
p
}
}
|
2,906
|
Construct Product Matrix
|
Medium
|
<p>Given a <strong>0-indexed</strong> 2D integer matrix <code><font face="monospace">grid</font></code><font face="monospace"> </font>of size <code>n * m</code>, we define a <strong>0-indexed</strong> 2D matrix <code>p</code> of size <code>n * m</code> as the <strong>product</strong> matrix of <code>grid</code> if the following condition is met:</p>
<ul>
<li>Each element <code>p[i][j]</code> is calculated as the product of all elements in <code>grid</code> except for the element <code>grid[i][j]</code>. This product is then taken modulo <code><font face="monospace">12345</font></code>.</li>
</ul>
<p>Return <em>the product matrix of</em> <code><font face="monospace">grid</font></code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,2],[3,4]]
<strong>Output:</strong> [[24,12],[8,6]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24
p[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12
p[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8
p[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6
So the answer is [[24,12],[8,6]].</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[12345],[2],[1]]
<strong>Output:</strong> [[2],[0],[0]]
<strong>Explanation:</strong> p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.
p[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.
p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.
So the answer is [[2],[0],[0]].</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == grid.length <= 10<sup>5</sup></code></li>
<li><code>1 <= m == grid[i].length <= 10<sup>5</sup></code></li>
<li><code>2 <= n * m <= 10<sup>5</sup></code></li>
<li><code>1 <= grid[i][j] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
TypeScript
|
function constructProductMatrix(grid: number[][]): number[][] {
const mod = 12345;
const [n, m] = [grid.length, grid[0].length];
const p: number[][] = Array.from({ length: n }, () => Array.from({ length: m }, () => 0));
let suf = 1;
for (let i = n - 1; ~i; --i) {
for (let j = m - 1; ~j; --j) {
p[i][j] = suf;
suf = (suf * grid[i][j]) % mod;
}
}
let pre = 1;
for (let i = 0; i < n; ++i) {
for (let j = 0; j < m; ++j) {
p[i][j] = (p[i][j] * pre) % mod;
pre = (pre * grid[i][j]) % mod;
}
}
return p;
}
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
C++
|
class Solution {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
int n = prices.size();
int ans = -1;
for (int j = 0; j < n; ++j) {
int left = 0, right = 0;
for (int i = 0; i < j; ++i) {
if (prices[i] < prices[j]) {
left = max(left, profits[i]);
}
}
for (int k = j + 1; k < n; ++k) {
if (prices[j] < prices[k]) {
right = max(right, profits[k]);
}
}
if (left && right) {
ans = max(ans, left + profits[j] + right);
}
}
return ans;
}
};
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Go
|
func maxProfit(prices []int, profits []int) int {
n := len(prices)
ans := -1
for j, x := range profits {
left, right := 0, 0
for i := 0; i < j; i++ {
if prices[i] < prices[j] {
left = max(left, profits[i])
}
}
for k := j + 1; k < n; k++ {
if prices[j] < prices[k] {
right = max(right, profits[k])
}
}
if left > 0 && right > 0 {
ans = max(ans, left+x+right)
}
}
return ans
}
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Java
|
class Solution {
public int maxProfit(int[] prices, int[] profits) {
int n = prices.length;
int ans = -1;
for (int j = 0; j < n; ++j) {
int left = 0, right = 0;
for (int i = 0; i < j; ++i) {
if (prices[i] < prices[j]) {
left = Math.max(left, profits[i]);
}
}
for (int k = j + 1; k < n; ++k) {
if (prices[j] < prices[k]) {
right = Math.max(right, profits[k]);
}
}
if (left > 0 && right > 0) {
ans = Math.max(ans, left + profits[j] + right);
}
}
return ans;
}
}
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Python
|
class Solution:
def maxProfit(self, prices: List[int], profits: List[int]) -> int:
n = len(prices)
ans = -1
for j, x in enumerate(profits):
left = right = 0
for i in range(j):
if prices[i] < prices[j] and left < profits[i]:
left = profits[i]
for k in range(j + 1, n):
if prices[j] < prices[k] and right < profits[k]:
right = profits[k]
if left and right:
ans = max(ans, left + x + right)
return ans
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Rust
|
impl Solution {
pub fn max_profit(prices: Vec<i32>, profits: Vec<i32>) -> i32 {
let n = prices.len();
let mut ans = -1;
for j in 0..n {
let mut left = 0;
let mut right = 0;
for i in 0..j {
if prices[i] < prices[j] {
left = left.max(profits[i]);
}
}
for k in j + 1..n {
if prices[j] < prices[k] {
right = right.max(profits[k]);
}
}
if left > 0 && right > 0 {
ans = ans.max(left + profits[j] + right);
}
}
ans
}
}
|
2,907
|
Maximum Profitable Triplets With Increasing Prices I
|
Medium
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 2000</code></li>
<li><code>1 <= prices[i] <= 10<sup>6</sup></code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
TypeScript
|
function maxProfit(prices: number[], profits: number[]): number {
const n = prices.length;
let ans = -1;
for (let j = 0; j < n; ++j) {
let [left, right] = [0, 0];
for (let i = 0; i < j; ++i) {
if (prices[i] < prices[j]) {
left = Math.max(left, profits[i]);
}
}
for (let k = j + 1; k < n; ++k) {
if (prices[j] < prices[k]) {
right = Math.max(right, profits[k]);
}
}
if (left > 0 && right > 0) {
ans = Math.max(ans, left + profits[j] + right);
}
}
return ans;
}
|
2,908
|
Minimum Sum of Mountain Triplets I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int minimumSum(vector<int>& nums) {
int n = nums.size();
const int inf = 1 << 30;
int right[n + 1];
right[n] = inf;
for (int i = n - 1; ~i; --i) {
right[i] = min(right[i + 1], nums[i]);
}
int ans = inf, left = inf;
for (int i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = min(ans, left + nums[i] + right[i + 1]);
}
left = min(left, nums[i]);
}
return ans == inf ? -1 : ans;
}
};
|
2,908
|
Minimum Sum of Mountain Triplets I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Go
|
func minimumSum(nums []int) int {
n := len(nums)
const inf = 1 << 30
right := make([]int, n+1)
right[n] = inf
for i := n - 1; i >= 0; i-- {
right[i] = min(right[i+1], nums[i])
}
ans, left := inf, inf
for i, x := range nums {
if left < x && right[i+1] < x {
ans = min(ans, left+x+right[i+1])
}
left = min(left, x)
}
if ans == inf {
return -1
}
return ans
}
|
2,908
|
Minimum Sum of Mountain Triplets I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int minimumSum(int[] nums) {
int n = nums.length;
int[] right = new int[n + 1];
final int inf = 1 << 30;
right[n] = inf;
for (int i = n - 1; i >= 0; --i) {
right[i] = Math.min(right[i + 1], nums[i]);
}
int ans = inf, left = inf;
for (int i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = Math.min(ans, left + nums[i] + right[i + 1]);
}
left = Math.min(left, nums[i]);
}
return ans == inf ? -1 : ans;
}
}
|
2,908
|
Minimum Sum of Mountain Triplets I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Python
|
class Solution:
def minimumSum(self, nums: List[int]) -> int:
n = len(nums)
right = [inf] * (n + 1)
for i in range(n - 1, -1, -1):
right[i] = min(right[i + 1], nums[i])
ans = left = inf
for i, x in enumerate(nums):
if left < x and right[i + 1] < x:
ans = min(ans, left + x + right[i + 1])
left = min(left, x)
return -1 if ans == inf else ans
|
2,908
|
Minimum Sum of Mountain Triplets I
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
TypeScript
|
function minimumSum(nums: number[]): number {
const n = nums.length;
const right: number[] = Array(n + 1).fill(Infinity);
for (let i = n - 1; ~i; --i) {
right[i] = Math.min(right[i + 1], nums[i]);
}
let [ans, left] = [Infinity, Infinity];
for (let i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = Math.min(ans, left + nums[i] + right[i + 1]);
}
left = Math.min(left, nums[i]);
}
return ans === Infinity ? -1 : ans;
}
|
2,909
|
Minimum Sum of Mountain Triplets II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>8</sup></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int minimumSum(vector<int>& nums) {
int n = nums.size();
const int inf = 1 << 30;
int right[n + 1];
right[n] = inf;
for (int i = n - 1; ~i; --i) {
right[i] = min(right[i + 1], nums[i]);
}
int ans = inf, left = inf;
for (int i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = min(ans, left + nums[i] + right[i + 1]);
}
left = min(left, nums[i]);
}
return ans == inf ? -1 : ans;
}
};
|
2,909
|
Minimum Sum of Mountain Triplets II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>8</sup></code></li>
</ul>
|
Array
|
Go
|
func minimumSum(nums []int) int {
n := len(nums)
const inf = 1 << 30
right := make([]int, n+1)
right[n] = inf
for i := n - 1; i >= 0; i-- {
right[i] = min(right[i+1], nums[i])
}
ans, left := inf, inf
for i, x := range nums {
if left < x && right[i+1] < x {
ans = min(ans, left+x+right[i+1])
}
left = min(left, x)
}
if ans == inf {
return -1
}
return ans
}
|
2,909
|
Minimum Sum of Mountain Triplets II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>8</sup></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int minimumSum(int[] nums) {
int n = nums.length;
int[] right = new int[n + 1];
final int inf = 1 << 30;
right[n] = inf;
for (int i = n - 1; i >= 0; --i) {
right[i] = Math.min(right[i + 1], nums[i]);
}
int ans = inf, left = inf;
for (int i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = Math.min(ans, left + nums[i] + right[i + 1]);
}
left = Math.min(left, nums[i]);
}
return ans == inf ? -1 : ans;
}
}
|
2,909
|
Minimum Sum of Mountain Triplets II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>8</sup></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def minimumSum(self, nums: List[int]) -> int:
n = len(nums)
right = [inf] * (n + 1)
for i in range(n - 1, -1, -1):
right[i] = min(right[i + 1], nums[i])
ans = left = inf
for i, x in enumerate(nums):
if left < x and right[i + 1] < x:
ans = min(ans, left + x + right[i + 1])
left = min(left, x)
return -1 if ans == inf else ans
|
2,909
|
Minimum Sum of Mountain Triplets II
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of integers.</p>
<p>A triplet of indices <code>(i, j, k)</code> is a <strong>mountain</strong> if:</p>
<ul>
<li><code>i < j < k</code></li>
<li><code>nums[i] < nums[j]</code> and <code>nums[k] < nums[j]</code></li>
</ul>
<p>Return <em>the <strong>minimum possible sum</strong> of a mountain triplet of</em> <code>nums</code>. <em>If no such triplet exists, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,6,1,5,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Triplet (2, 3, 4) is a mountain triplet of sum 9 since:
- 2 < 3 < 4
- nums[2] < nums[3] and nums[4] < nums[3]
And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,8,7,10,2]
<strong>Output:</strong> 13
<strong>Explanation:</strong> Triplet (1, 3, 5) is a mountain triplet of sum 13 since:
- 1 < 3 < 5
- nums[1] < nums[3] and nums[5] < nums[3]
And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [6,5,4,3,4,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that there are no mountain triplets in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>8</sup></code></li>
</ul>
|
Array
|
TypeScript
|
function minimumSum(nums: number[]): number {
const n = nums.length;
const right: number[] = Array(n + 1).fill(Infinity);
for (let i = n - 1; ~i; --i) {
right[i] = Math.min(right[i + 1], nums[i]);
}
let [ans, left] = [Infinity, Infinity];
for (let i = 0; i < n; ++i) {
if (left < nums[i] && right[i + 1] < nums[i]) {
ans = Math.min(ans, left + nums[i] + right[i + 1]);
}
left = Math.min(left, nums[i]);
}
return ans === Infinity ? -1 : ans;
}
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
C++
|
class Solution {
public:
int minGroupsForValidAssignment(vector<int>& nums) {
unordered_map<int, int> cnt;
for (int x : nums) {
cnt[x]++;
}
int k = 1e9;
for (auto& [_, v] : cnt) {
ans = min(ans, v);
}
for (;; --k) {
int ans = 0;
for (auto& [_, v] : cnt) {
if (v / k < v % k) {
ans = 0;
break;
}
ans += (v + k) / (k + 1);
}
if (ans) {
return ans;
}
}
}
};
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Go
|
func minGroupsForValidAssignment(nums []int) int {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
k := len(nums)
for _, v := range cnt {
k = min(k, v)
}
for ; ; k-- {
ans := 0
for _, v := range cnt {
if v/k < v%k {
ans = 0
break
}
ans += (v + k) / (k + 1)
}
if ans > 0 {
return ans
}
}
}
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Java
|
class Solution {
public int minGroupsForValidAssignment(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int k = nums.length;
for (int v : cnt.values()) {
k = Math.min(k, v);
}
for (;; --k) {
int ans = 0;
for (int v : cnt.values()) {
if (v / k < v % k) {
ans = 0;
break;
}
ans += (v + k) / (k + 1);
}
if (ans > 0) {
return ans;
}
}
}
}
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Python
|
class Solution:
def minGroupsForValidAssignment(self, nums: List[int]) -> int:
cnt = Counter(nums)
for k in range(min(cnt.values()), 0, -1):
ans = 0
for v in cnt.values():
if v // k < v % k:
ans = 0
break
ans += (v + k) // (k + 1)
if ans:
return ans
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn min_groups_for_valid_assignment(nums: Vec<i32>) -> i32 {
let mut cnt: HashMap<i32, i32> = HashMap::new();
for x in nums.iter() {
let count = cnt.entry(*x).or_insert(0);
*count += 1;
}
let mut k = i32::MAX;
for &v in cnt.values() {
k = k.min(v);
}
for k in (1..=k).rev() {
let mut ans = 0;
for &v in cnt.values() {
if v / k < v % k {
ans = 0;
break;
}
ans += (v + k) / (k + 1);
}
if ans > 0 {
return ans;
}
}
0
}
}
|
2,910
|
Minimum Number of Groups to Create a Valid Assignment
|
Medium
|
<p>You are given a collection of numbered <code>balls</code> and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:</p>
<ul>
<li>Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.</li>
<li>The biggest box can only have one more ball than the smallest box.</li>
</ul>
<p>Return the <em>fewest number of boxes</em> to sort these balls following these rules.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [3,2,3,2,3] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
<li><code>[3,3,3]</code></li>
<li><code>[2,2]</code></li>
</ul>
<p>The size difference between the two boxes doesn't exceed one.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> balls = [10,10,10,3,1,1] </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p>
<p><strong>Explanation:</strong></p>
<p>We can sort <code>balls</code> into boxes as follows:</p>
<ul>
</ul>
<ul>
<li><code>[10]</code></li>
<li><code>[10,10]</code></li>
<li><code>[3]</code></li>
<li><code>[1,1]</code></li>
</ul>
<p>You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table
|
TypeScript
|
function minGroupsForValidAssignment(nums: number[]): number {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
for (let k = Math.min(...cnt.values()); ; --k) {
let ans = 0;
for (const [_, v] of cnt) {
if (((v / k) | 0) < v % k) {
ans = 0;
break;
}
ans += Math.ceil(v / (k + 1));
}
if (ans) {
return ans;
}
}
}
|
2,911
|
Minimum Changes to Make K Semi-palindromes
|
Hard
|
<p>Given a string <code>s</code> and an integer <code>k</code>, partition <code>s</code> into <code>k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong> such that the letter changes needed to make each substring a <strong>semi-palindrome</strong> are minimized.</p>
<p>Return the <em><strong>minimum</strong> number of letter changes</em> required<em>.</em></p>
<p>A <strong>semi-palindrome</strong> is a special type of string that can be divided into <strong><span data-keyword="palindrome">palindromes</span></strong> based on a repeating pattern. To check if a string is a semi-palindrome:</p>
<ol>
<li>Choose a positive divisor <code>d</code> of the string's length. <code>d</code> can range from <code>1</code> up to, but not including, the string's length. For a string of length <code>1</code>, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.</li>
<li>For a given divisor <code>d</code>, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length <code>d</code>. Specifically, the first group consists of characters at positions <code>1</code>, <code>1 + d</code>, <code>1 + 2d</code>, and so on; the second group includes characters at positions <code>2</code>, <code>2 + d</code>, <code>2 + 2d</code>, etc.</li>
<li>The string is considered a semi-palindrome if each of these groups forms a palindrome.</li>
</ol>
<p>Consider the string <code>"abcabc"</code>:</p>
<ul>
<li>The length of <code>"abcabc"</code> is <code>6</code>. Valid divisors are <code>1</code>, <code>2</code>, and <code>3</code>.</li>
<li>For <code>d = 1</code>: The entire string <code>"abcabc"</code> forms one group. Not a palindrome.</li>
<li>For <code>d = 2</code>:
<ul>
<li>Group 1 (positions <code>1, 3, 5</code>): <code>"acb"</code></li>
<li>Group 2 (positions <code>2, 4, 6</code>): <code>"bac"</code></li>
<li>Neither group forms a palindrome.</li>
</ul>
</li>
<li>For <code>d = 3</code>:
<ul>
<li>Group 1 (positions <code>1, 4</code>): <code>"aa"</code></li>
<li>Group 2 (positions <code>2, 5</code>): <code>"bb"</code></li>
<li>Group 3 (positions <code>3, 6</code>): <code>"cc"</code></li>
<li>All groups form palindromes. Therefore, <code>"abcabc"</code> is a semi-palindrome.</li>
</ul>
</li>
</ul>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcac", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 1 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into <code>"ab"</code> and <code>"cac"</code>. <code>"cac"</code> is already semi-palindrome. Change <code>"ab"</code> to <code>"aa"</code>, it becomes semi-palindrome with <code>d = 1</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcdef", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"abc"</code> and <code>"def"</code>. Each needs one change to become semi-palindrome.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "aabbaa", k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"aa"</code>, <code>"bb"</code> and <code>"aa"</code>. All are already semi-palindromes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>1 <= k <= s.length / 2</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
C++
|
class Solution {
public:
int minimumChanges(string s, int k) {
int n = s.size();
int g[n + 1][n + 1];
int f[n + 1][k + 1];
memset(g, 0x3f, sizeof(g));
memset(f, 0x3f, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = i; j <= n; ++j) {
int m = j - i + 1;
for (int d = 1; d < m; ++d) {
if (m % d == 0) {
int cnt = 0;
for (int l = 0; l < m; ++l) {
int r = (m / d - 1 - l / d) * d + l % d;
if (l >= r) {
break;
}
if (s[i - 1 + l] != s[i - 1 + r]) {
++cnt;
}
}
g[i][j] = min(g[i][j], cnt);
}
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
for (int h = 0; h < i - 1; ++h) {
f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i]);
}
}
}
return f[n][k];
}
};
|
2,911
|
Minimum Changes to Make K Semi-palindromes
|
Hard
|
<p>Given a string <code>s</code> and an integer <code>k</code>, partition <code>s</code> into <code>k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong> such that the letter changes needed to make each substring a <strong>semi-palindrome</strong> are minimized.</p>
<p>Return the <em><strong>minimum</strong> number of letter changes</em> required<em>.</em></p>
<p>A <strong>semi-palindrome</strong> is a special type of string that can be divided into <strong><span data-keyword="palindrome">palindromes</span></strong> based on a repeating pattern. To check if a string is a semi-palindrome:</p>
<ol>
<li>Choose a positive divisor <code>d</code> of the string's length. <code>d</code> can range from <code>1</code> up to, but not including, the string's length. For a string of length <code>1</code>, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.</li>
<li>For a given divisor <code>d</code>, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length <code>d</code>. Specifically, the first group consists of characters at positions <code>1</code>, <code>1 + d</code>, <code>1 + 2d</code>, and so on; the second group includes characters at positions <code>2</code>, <code>2 + d</code>, <code>2 + 2d</code>, etc.</li>
<li>The string is considered a semi-palindrome if each of these groups forms a palindrome.</li>
</ol>
<p>Consider the string <code>"abcabc"</code>:</p>
<ul>
<li>The length of <code>"abcabc"</code> is <code>6</code>. Valid divisors are <code>1</code>, <code>2</code>, and <code>3</code>.</li>
<li>For <code>d = 1</code>: The entire string <code>"abcabc"</code> forms one group. Not a palindrome.</li>
<li>For <code>d = 2</code>:
<ul>
<li>Group 1 (positions <code>1, 3, 5</code>): <code>"acb"</code></li>
<li>Group 2 (positions <code>2, 4, 6</code>): <code>"bac"</code></li>
<li>Neither group forms a palindrome.</li>
</ul>
</li>
<li>For <code>d = 3</code>:
<ul>
<li>Group 1 (positions <code>1, 4</code>): <code>"aa"</code></li>
<li>Group 2 (positions <code>2, 5</code>): <code>"bb"</code></li>
<li>Group 3 (positions <code>3, 6</code>): <code>"cc"</code></li>
<li>All groups form palindromes. Therefore, <code>"abcabc"</code> is a semi-palindrome.</li>
</ul>
</li>
</ul>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcac", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 1 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into <code>"ab"</code> and <code>"cac"</code>. <code>"cac"</code> is already semi-palindrome. Change <code>"ab"</code> to <code>"aa"</code>, it becomes semi-palindrome with <code>d = 1</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcdef", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"abc"</code> and <code>"def"</code>. Each needs one change to become semi-palindrome.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "aabbaa", k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"aa"</code>, <code>"bb"</code> and <code>"aa"</code>. All are already semi-palindromes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>1 <= k <= s.length / 2</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Go
|
func minimumChanges(s string, k int) int {
n := len(s)
g := make([][]int, n+1)
f := make([][]int, n+1)
const inf int = 1 << 30
for i := range g {
g[i] = make([]int, n+1)
f[i] = make([]int, k+1)
for j := range g[i] {
g[i][j] = inf
}
for j := range f[i] {
f[i][j] = inf
}
}
f[0][0] = 0
for i := 1; i <= n; i++ {
for j := i; j <= n; j++ {
m := j - i + 1
for d := 1; d < m; d++ {
if m%d == 0 {
cnt := 0
for l := 0; l < m; l++ {
r := (m/d-1-l/d)*d + l%d
if l >= r {
break
}
if s[i-1+l] != s[i-1+r] {
cnt++
}
}
g[i][j] = min(g[i][j], cnt)
}
}
}
}
for i := 1; i <= n; i++ {
for j := 1; j <= k; j++ {
for h := 0; h < i-1; h++ {
f[i][j] = min(f[i][j], f[h][j-1]+g[h+1][i])
}
}
}
return f[n][k]
}
|
2,911
|
Minimum Changes to Make K Semi-palindromes
|
Hard
|
<p>Given a string <code>s</code> and an integer <code>k</code>, partition <code>s</code> into <code>k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong> such that the letter changes needed to make each substring a <strong>semi-palindrome</strong> are minimized.</p>
<p>Return the <em><strong>minimum</strong> number of letter changes</em> required<em>.</em></p>
<p>A <strong>semi-palindrome</strong> is a special type of string that can be divided into <strong><span data-keyword="palindrome">palindromes</span></strong> based on a repeating pattern. To check if a string is a semi-palindrome:</p>
<ol>
<li>Choose a positive divisor <code>d</code> of the string's length. <code>d</code> can range from <code>1</code> up to, but not including, the string's length. For a string of length <code>1</code>, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.</li>
<li>For a given divisor <code>d</code>, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length <code>d</code>. Specifically, the first group consists of characters at positions <code>1</code>, <code>1 + d</code>, <code>1 + 2d</code>, and so on; the second group includes characters at positions <code>2</code>, <code>2 + d</code>, <code>2 + 2d</code>, etc.</li>
<li>The string is considered a semi-palindrome if each of these groups forms a palindrome.</li>
</ol>
<p>Consider the string <code>"abcabc"</code>:</p>
<ul>
<li>The length of <code>"abcabc"</code> is <code>6</code>. Valid divisors are <code>1</code>, <code>2</code>, and <code>3</code>.</li>
<li>For <code>d = 1</code>: The entire string <code>"abcabc"</code> forms one group. Not a palindrome.</li>
<li>For <code>d = 2</code>:
<ul>
<li>Group 1 (positions <code>1, 3, 5</code>): <code>"acb"</code></li>
<li>Group 2 (positions <code>2, 4, 6</code>): <code>"bac"</code></li>
<li>Neither group forms a palindrome.</li>
</ul>
</li>
<li>For <code>d = 3</code>:
<ul>
<li>Group 1 (positions <code>1, 4</code>): <code>"aa"</code></li>
<li>Group 2 (positions <code>2, 5</code>): <code>"bb"</code></li>
<li>Group 3 (positions <code>3, 6</code>): <code>"cc"</code></li>
<li>All groups form palindromes. Therefore, <code>"abcabc"</code> is a semi-palindrome.</li>
</ul>
</li>
</ul>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcac", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 1 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into <code>"ab"</code> and <code>"cac"</code>. <code>"cac"</code> is already semi-palindrome. Change <code>"ab"</code> to <code>"aa"</code>, it becomes semi-palindrome with <code>d = 1</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcdef", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"abc"</code> and <code>"def"</code>. Each needs one change to become semi-palindrome.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "aabbaa", k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"aa"</code>, <code>"bb"</code> and <code>"aa"</code>. All are already semi-palindromes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>1 <= k <= s.length / 2</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Java
|
class Solution {
public int minimumChanges(String s, int k) {
int n = s.length();
int[][] g = new int[n + 1][n + 1];
int[][] f = new int[n + 1][k + 1];
final int inf = 1 << 30;
for (int i = 0; i <= n; ++i) {
Arrays.fill(g[i], inf);
Arrays.fill(f[i], inf);
}
for (int i = 1; i <= n; ++i) {
for (int j = i; j <= n; ++j) {
int m = j - i + 1;
for (int d = 1; d < m; ++d) {
if (m % d == 0) {
int cnt = 0;
for (int l = 0; l < m; ++l) {
int r = (m / d - 1 - l / d) * d + l % d;
if (l >= r) {
break;
}
if (s.charAt(i - 1 + l) != s.charAt(i - 1 + r)) {
++cnt;
}
}
g[i][j] = Math.min(g[i][j], cnt);
}
}
}
}
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
for (int h = 0; h < i - 1; ++h) {
f[i][j] = Math.min(f[i][j], f[h][j - 1] + g[h + 1][i]);
}
}
}
return f[n][k];
}
}
|
2,911
|
Minimum Changes to Make K Semi-palindromes
|
Hard
|
<p>Given a string <code>s</code> and an integer <code>k</code>, partition <code>s</code> into <code>k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong> such that the letter changes needed to make each substring a <strong>semi-palindrome</strong> are minimized.</p>
<p>Return the <em><strong>minimum</strong> number of letter changes</em> required<em>.</em></p>
<p>A <strong>semi-palindrome</strong> is a special type of string that can be divided into <strong><span data-keyword="palindrome">palindromes</span></strong> based on a repeating pattern. To check if a string is a semi-palindrome:</p>
<ol>
<li>Choose a positive divisor <code>d</code> of the string's length. <code>d</code> can range from <code>1</code> up to, but not including, the string's length. For a string of length <code>1</code>, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.</li>
<li>For a given divisor <code>d</code>, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length <code>d</code>. Specifically, the first group consists of characters at positions <code>1</code>, <code>1 + d</code>, <code>1 + 2d</code>, and so on; the second group includes characters at positions <code>2</code>, <code>2 + d</code>, <code>2 + 2d</code>, etc.</li>
<li>The string is considered a semi-palindrome if each of these groups forms a palindrome.</li>
</ol>
<p>Consider the string <code>"abcabc"</code>:</p>
<ul>
<li>The length of <code>"abcabc"</code> is <code>6</code>. Valid divisors are <code>1</code>, <code>2</code>, and <code>3</code>.</li>
<li>For <code>d = 1</code>: The entire string <code>"abcabc"</code> forms one group. Not a palindrome.</li>
<li>For <code>d = 2</code>:
<ul>
<li>Group 1 (positions <code>1, 3, 5</code>): <code>"acb"</code></li>
<li>Group 2 (positions <code>2, 4, 6</code>): <code>"bac"</code></li>
<li>Neither group forms a palindrome.</li>
</ul>
</li>
<li>For <code>d = 3</code>:
<ul>
<li>Group 1 (positions <code>1, 4</code>): <code>"aa"</code></li>
<li>Group 2 (positions <code>2, 5</code>): <code>"bb"</code></li>
<li>Group 3 (positions <code>3, 6</code>): <code>"cc"</code></li>
<li>All groups form palindromes. Therefore, <code>"abcabc"</code> is a semi-palindrome.</li>
</ul>
</li>
</ul>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcac", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 1 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into <code>"ab"</code> and <code>"cac"</code>. <code>"cac"</code> is already semi-palindrome. Change <code>"ab"</code> to <code>"aa"</code>, it becomes semi-palindrome with <code>d = 1</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcdef", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"abc"</code> and <code>"def"</code>. Each needs one change to become semi-palindrome.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "aabbaa", k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"aa"</code>, <code>"bb"</code> and <code>"aa"</code>. All are already semi-palindromes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>1 <= k <= s.length / 2</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
Python
|
class Solution:
def minimumChanges(self, s: str, k: int) -> int:
n = len(s)
g = [[inf] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1):
m = j - i + 1
for d in range(1, m):
if m % d == 0:
cnt = 0
for l in range(m):
r = (m // d - 1 - l // d) * d + l % d
if l >= r:
break
if s[i - 1 + l] != s[i - 1 + r]:
cnt += 1
g[i][j] = min(g[i][j], cnt)
f = [[inf] * (k + 1) for _ in range(n + 1)]
f[0][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
for h in range(i - 1):
f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i])
return f[n][k]
|
2,911
|
Minimum Changes to Make K Semi-palindromes
|
Hard
|
<p>Given a string <code>s</code> and an integer <code>k</code>, partition <code>s</code> into <code>k</code> <strong><span data-keyword="substring-nonempty">substrings</span></strong> such that the letter changes needed to make each substring a <strong>semi-palindrome</strong> are minimized.</p>
<p>Return the <em><strong>minimum</strong> number of letter changes</em> required<em>.</em></p>
<p>A <strong>semi-palindrome</strong> is a special type of string that can be divided into <strong><span data-keyword="palindrome">palindromes</span></strong> based on a repeating pattern. To check if a string is a semi-palindrome:</p>
<ol>
<li>Choose a positive divisor <code>d</code> of the string's length. <code>d</code> can range from <code>1</code> up to, but not including, the string's length. For a string of length <code>1</code>, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.</li>
<li>For a given divisor <code>d</code>, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length <code>d</code>. Specifically, the first group consists of characters at positions <code>1</code>, <code>1 + d</code>, <code>1 + 2d</code>, and so on; the second group includes characters at positions <code>2</code>, <code>2 + d</code>, <code>2 + 2d</code>, etc.</li>
<li>The string is considered a semi-palindrome if each of these groups forms a palindrome.</li>
</ol>
<p>Consider the string <code>"abcabc"</code>:</p>
<ul>
<li>The length of <code>"abcabc"</code> is <code>6</code>. Valid divisors are <code>1</code>, <code>2</code>, and <code>3</code>.</li>
<li>For <code>d = 1</code>: The entire string <code>"abcabc"</code> forms one group. Not a palindrome.</li>
<li>For <code>d = 2</code>:
<ul>
<li>Group 1 (positions <code>1, 3, 5</code>): <code>"acb"</code></li>
<li>Group 2 (positions <code>2, 4, 6</code>): <code>"bac"</code></li>
<li>Neither group forms a palindrome.</li>
</ul>
</li>
<li>For <code>d = 3</code>:
<ul>
<li>Group 1 (positions <code>1, 4</code>): <code>"aa"</code></li>
<li>Group 2 (positions <code>2, 5</code>): <code>"bb"</code></li>
<li>Group 3 (positions <code>3, 6</code>): <code>"cc"</code></li>
<li>All groups form palindromes. Therefore, <code>"abcabc"</code> is a semi-palindrome.</li>
</ul>
</li>
</ul>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcac", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 1 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into <code>"ab"</code> and <code>"cac"</code>. <code>"cac"</code> is already semi-palindrome. Change <code>"ab"</code> to <code>"aa"</code>, it becomes semi-palindrome with <code>d = 1</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "abcdef", k = 2 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 2 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"abc"</code> and <code>"def"</code>. Each needs one change to become semi-palindrome.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = "aabbaa", k = 3 </span></p>
<p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong> Divide <code>s</code> into substrings <code>"aa"</code>, <code>"bb"</code> and <code>"aa"</code>. All are already semi-palindromes.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 200</code></li>
<li><code>1 <= k <= s.length / 2</code></li>
<li><code>s</code> contains only lowercase English letters.</li>
</ul>
|
Two Pointers; String; Dynamic Programming
|
TypeScript
|
function minimumChanges(s: string, k: number): number {
const n = s.length;
const g = Array.from({ length: n + 1 }, () => Array.from({ length: n + 1 }, () => Infinity));
const f = Array.from({ length: n + 1 }, () => Array.from({ length: k + 1 }, () => Infinity));
f[0][0] = 0;
for (let i = 1; i <= n; ++i) {
for (let j = 1; j <= n; ++j) {
const m = j - i + 1;
for (let d = 1; d < m; ++d) {
if (m % d === 0) {
let cnt = 0;
for (let l = 0; l < m; ++l) {
const r = (((m / d) | 0) - 1 - ((l / d) | 0)) * d + (l % d);
if (l >= r) {
break;
}
if (s[i - 1 + l] !== s[i - 1 + r]) {
++cnt;
}
}
g[i][j] = Math.min(g[i][j], cnt);
}
}
}
}
for (let i = 1; i <= n; ++i) {
for (let j = 1; j <= k; ++j) {
for (let h = 0; h < i - 1; ++h) {
f[i][j] = Math.min(f[i][j], f[h][j - 1] + g[h + 1][i]);
}
}
}
return f[n][k];
}
|
2,912
|
Number of Ways to Reach Destination in the Grid
|
Hard
|
<p>You are given two integers <code>n</code> and <code>m</code> which represent the size of a <strong>1-indexed </strong>grid. You are also given an integer <code>k</code>, a <strong>1-indexed</strong> integer array <code>source</code> and a <strong>1-indexed</strong> integer array <code>dest</code>, where <code>source</code> and <code>dest</code> are in the form <code>[x, y]</code> representing a cell on the given grid.</p>
<p>You can move through the grid in the following way:</p>
<ul>
<li>You can go from cell <code>[x<sub>1</sub>, y<sub>1</sub>]</code> to cell <code>[x<sub>2</sub>, y<sub>2</sub>]</code> if either <code>x<sub>1</sub> == x<sub>2</sub></code> or <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
<li>Note that you <strong>can't</strong> move to the cell you are already in e.g. <code>x<sub>1</sub> == x<sub>2</sub></code> and <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
</ul>
<p>Return <em>the number of ways you can reach</em> <code>dest</code> <em>from</em> <code>source</code> <em>by moving through the grid</em> <strong>exactly</strong> <code>k</code> <em>times.</em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2, k = 2, source = [1,1], dest = [2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 possible sequences of reaching [2,2] from [1,1]:
- [1,1] -> [1,2] -> [2,2]
- [1,1] -> [2,1] -> [2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 4, k = 3, source = [1,2], dest = [2,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> There are 9 possible sequences of reaching [2,3] from [1,2]:
- [1,2] -> [1,1] -> [1,3] -> [2,3]
- [1,2] -> [1,1] -> [2,1] -> [2,3]
- [1,2] -> [1,3] -> [3,3] -> [2,3]
- [1,2] -> [1,4] -> [1,3] -> [2,3]
- [1,2] -> [1,4] -> [2,4] -> [2,3]
- [1,2] -> [2,2] -> [2,1] -> [2,3]
- [1,2] -> [2,2] -> [2,4] -> [2,3]
- [1,2] -> [3,2] -> [2,2] -> [2,3]
- [1,2] -> [3,2] -> [3,3] -> [2,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>source.length == dest.length == 2</code></li>
<li><code>1 <= source[1], dest[1] <= n</code></li>
<li><code>1 <= source[2], dest[2] <= m</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
C++
|
class Solution {
public:
int numberOfWays(int n, int m, int k, vector<int>& source, vector<int>& dest) {
const int mod = 1e9 + 7;
vector<long long> f(4);
f[0] = 1;
while (k--) {
vector<long long> g(4);
g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod;
g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod;
g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod;
g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod;
f = move(g);
}
if (source[0] == dest[0]) {
return source[1] == dest[1] ? f[0] : f[2];
}
return source[1] == dest[1] ? f[1] : f[3];
}
};
|
2,912
|
Number of Ways to Reach Destination in the Grid
|
Hard
|
<p>You are given two integers <code>n</code> and <code>m</code> which represent the size of a <strong>1-indexed </strong>grid. You are also given an integer <code>k</code>, a <strong>1-indexed</strong> integer array <code>source</code> and a <strong>1-indexed</strong> integer array <code>dest</code>, where <code>source</code> and <code>dest</code> are in the form <code>[x, y]</code> representing a cell on the given grid.</p>
<p>You can move through the grid in the following way:</p>
<ul>
<li>You can go from cell <code>[x<sub>1</sub>, y<sub>1</sub>]</code> to cell <code>[x<sub>2</sub>, y<sub>2</sub>]</code> if either <code>x<sub>1</sub> == x<sub>2</sub></code> or <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
<li>Note that you <strong>can't</strong> move to the cell you are already in e.g. <code>x<sub>1</sub> == x<sub>2</sub></code> and <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
</ul>
<p>Return <em>the number of ways you can reach</em> <code>dest</code> <em>from</em> <code>source</code> <em>by moving through the grid</em> <strong>exactly</strong> <code>k</code> <em>times.</em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2, k = 2, source = [1,1], dest = [2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 possible sequences of reaching [2,2] from [1,1]:
- [1,1] -> [1,2] -> [2,2]
- [1,1] -> [2,1] -> [2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 4, k = 3, source = [1,2], dest = [2,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> There are 9 possible sequences of reaching [2,3] from [1,2]:
- [1,2] -> [1,1] -> [1,3] -> [2,3]
- [1,2] -> [1,1] -> [2,1] -> [2,3]
- [1,2] -> [1,3] -> [3,3] -> [2,3]
- [1,2] -> [1,4] -> [1,3] -> [2,3]
- [1,2] -> [1,4] -> [2,4] -> [2,3]
- [1,2] -> [2,2] -> [2,1] -> [2,3]
- [1,2] -> [2,2] -> [2,4] -> [2,3]
- [1,2] -> [3,2] -> [2,2] -> [2,3]
- [1,2] -> [3,2] -> [3,3] -> [2,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>source.length == dest.length == 2</code></li>
<li><code>1 <= source[1], dest[1] <= n</code></li>
<li><code>1 <= source[2], dest[2] <= m</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Go
|
func numberOfWays(n int, m int, k int, source []int, dest []int) int {
const mod int = 1e9 + 7
f := []int{1, 0, 0, 0}
for i := 0; i < k; i++ {
g := make([]int, 4)
g[0] = ((n-1)*f[1] + (m-1)*f[2]) % mod
g[1] = (f[0] + (n-2)*f[1] + (m-1)*f[3]) % mod
g[2] = (f[0] + (m-2)*f[2] + (n-1)*f[3]) % mod
g[3] = (f[1] + f[2] + (n-2)*f[3] + (m-2)*f[3]) % mod
f = g
}
if source[0] == dest[0] {
if source[1] == dest[1] {
return f[0]
}
return f[2]
}
if source[1] == dest[1] {
return f[1]
}
return f[3]
}
|
2,912
|
Number of Ways to Reach Destination in the Grid
|
Hard
|
<p>You are given two integers <code>n</code> and <code>m</code> which represent the size of a <strong>1-indexed </strong>grid. You are also given an integer <code>k</code>, a <strong>1-indexed</strong> integer array <code>source</code> and a <strong>1-indexed</strong> integer array <code>dest</code>, where <code>source</code> and <code>dest</code> are in the form <code>[x, y]</code> representing a cell on the given grid.</p>
<p>You can move through the grid in the following way:</p>
<ul>
<li>You can go from cell <code>[x<sub>1</sub>, y<sub>1</sub>]</code> to cell <code>[x<sub>2</sub>, y<sub>2</sub>]</code> if either <code>x<sub>1</sub> == x<sub>2</sub></code> or <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
<li>Note that you <strong>can't</strong> move to the cell you are already in e.g. <code>x<sub>1</sub> == x<sub>2</sub></code> and <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
</ul>
<p>Return <em>the number of ways you can reach</em> <code>dest</code> <em>from</em> <code>source</code> <em>by moving through the grid</em> <strong>exactly</strong> <code>k</code> <em>times.</em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2, k = 2, source = [1,1], dest = [2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 possible sequences of reaching [2,2] from [1,1]:
- [1,1] -> [1,2] -> [2,2]
- [1,1] -> [2,1] -> [2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 4, k = 3, source = [1,2], dest = [2,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> There are 9 possible sequences of reaching [2,3] from [1,2]:
- [1,2] -> [1,1] -> [1,3] -> [2,3]
- [1,2] -> [1,1] -> [2,1] -> [2,3]
- [1,2] -> [1,3] -> [3,3] -> [2,3]
- [1,2] -> [1,4] -> [1,3] -> [2,3]
- [1,2] -> [1,4] -> [2,4] -> [2,3]
- [1,2] -> [2,2] -> [2,1] -> [2,3]
- [1,2] -> [2,2] -> [2,4] -> [2,3]
- [1,2] -> [3,2] -> [2,2] -> [2,3]
- [1,2] -> [3,2] -> [3,3] -> [2,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>source.length == dest.length == 2</code></li>
<li><code>1 <= source[1], dest[1] <= n</code></li>
<li><code>1 <= source[2], dest[2] <= m</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Java
|
class Solution {
public int numberOfWays(int n, int m, int k, int[] source, int[] dest) {
final int mod = 1000000007;
long[] f = new long[4];
f[0] = 1;
while (k-- > 0) {
long[] g = new long[4];
g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod;
g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod;
g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod;
g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod;
f = g;
}
if (source[0] == dest[0]) {
return source[1] == dest[1] ? (int) f[0] : (int) f[2];
}
return source[1] == dest[1] ? (int) f[1] : (int) f[3];
}
}
|
2,912
|
Number of Ways to Reach Destination in the Grid
|
Hard
|
<p>You are given two integers <code>n</code> and <code>m</code> which represent the size of a <strong>1-indexed </strong>grid. You are also given an integer <code>k</code>, a <strong>1-indexed</strong> integer array <code>source</code> and a <strong>1-indexed</strong> integer array <code>dest</code>, where <code>source</code> and <code>dest</code> are in the form <code>[x, y]</code> representing a cell on the given grid.</p>
<p>You can move through the grid in the following way:</p>
<ul>
<li>You can go from cell <code>[x<sub>1</sub>, y<sub>1</sub>]</code> to cell <code>[x<sub>2</sub>, y<sub>2</sub>]</code> if either <code>x<sub>1</sub> == x<sub>2</sub></code> or <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
<li>Note that you <strong>can't</strong> move to the cell you are already in e.g. <code>x<sub>1</sub> == x<sub>2</sub></code> and <code>y<sub>1</sub> == y<sub>2</sub></code>.</li>
</ul>
<p>Return <em>the number of ways you can reach</em> <code>dest</code> <em>from</em> <code>source</code> <em>by moving through the grid</em> <strong>exactly</strong> <code>k</code> <em>times.</em></p>
<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2, k = 2, source = [1,1], dest = [2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 possible sequences of reaching [2,2] from [1,1]:
- [1,1] -> [1,2] -> [2,2]
- [1,1] -> [2,1] -> [2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 4, k = 3, source = [1,2], dest = [2,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong> There are 9 possible sequences of reaching [2,3] from [1,2]:
- [1,2] -> [1,1] -> [1,3] -> [2,3]
- [1,2] -> [1,1] -> [2,1] -> [2,3]
- [1,2] -> [1,3] -> [3,3] -> [2,3]
- [1,2] -> [1,4] -> [1,3] -> [2,3]
- [1,2] -> [1,4] -> [2,4] -> [2,3]
- [1,2] -> [2,2] -> [2,1] -> [2,3]
- [1,2] -> [2,2] -> [2,4] -> [2,3]
- [1,2] -> [3,2] -> [2,2] -> [2,3]
- [1,2] -> [3,2] -> [3,3] -> [2,3]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li><code>source.length == dest.length == 2</code></li>
<li><code>1 <= source[1], dest[1] <= n</code></li>
<li><code>1 <= source[2], dest[2] <= m</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def numberOfWays(
self, n: int, m: int, k: int, source: List[int], dest: List[int]
) -> int:
mod = 10**9 + 7
a, b, c, d = 1, 0, 0, 0
for _ in range(k):
aa = ((n - 1) * b + (m - 1) * c) % mod
bb = (a + (n - 2) * b + (m - 1) * d) % mod
cc = (a + (m - 2) * c + (n - 1) * d) % mod
dd = (b + c + (n - 2) * d + (m - 2) * d) % mod
a, b, c, d = aa, bb, cc, dd
if source[0] == dest[0]:
return a if source[1] == dest[1] else c
return b if source[1] == dest[1] else d
|
2,913
|
Subarrays Distinct Element Sum of Squares I
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>.</p>
<p>The <strong>distinct count</strong> of a subarray of <code>nums</code> is defined as:</p>
<ul>
<li>Let <code>nums[i..j]</code> be a subarray of <code>nums</code> consisting of all the indices from <code>i</code> to <code>j</code> such that <code>0 <= i <= j < nums.length</code>. Then the number of distinct values in <code>nums[i..j]</code> is called the distinct count of <code>nums[i..j]</code>.</li>
</ul>
<p>Return <em>the sum of the <strong>squares</strong> of <strong>distinct counts</strong> of all subarrays of </em><code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> 15
<strong>Explanation:</strong> Six possible subarrays are:
[1]: 1 distinct value
[2]: 1 distinct value
[1]: 1 distinct value
[1,2]: 2 distinct values
[2,1]: 2 distinct values
[1,2,1]: 2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> = 15.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three possible subarrays are:
[1]: 1 distinct value
[1]: 1 distinct value
[1,1]: 1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> = 3.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int sumCounts(vector<int>& nums) {
int ans = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
int s[101]{};
int cnt = 0;
for (int j = i; j < n; ++j) {
if (++s[nums[j]] == 1) {
++cnt;
}
ans += cnt * cnt;
}
}
return ans;
}
};
|
2,913
|
Subarrays Distinct Element Sum of Squares I
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>.</p>
<p>The <strong>distinct count</strong> of a subarray of <code>nums</code> is defined as:</p>
<ul>
<li>Let <code>nums[i..j]</code> be a subarray of <code>nums</code> consisting of all the indices from <code>i</code> to <code>j</code> such that <code>0 <= i <= j < nums.length</code>. Then the number of distinct values in <code>nums[i..j]</code> is called the distinct count of <code>nums[i..j]</code>.</li>
</ul>
<p>Return <em>the sum of the <strong>squares</strong> of <strong>distinct counts</strong> of all subarrays of </em><code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> 15
<strong>Explanation:</strong> Six possible subarrays are:
[1]: 1 distinct value
[2]: 1 distinct value
[1]: 1 distinct value
[1,2]: 2 distinct values
[2,1]: 2 distinct values
[1,2,1]: 2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> = 15.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three possible subarrays are:
[1]: 1 distinct value
[1]: 1 distinct value
[1,1]: 1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> = 3.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func sumCounts(nums []int) (ans int) {
for i := range nums {
s := [101]int{}
cnt := 0
for _, x := range nums[i:] {
s[x]++
if s[x] == 1 {
cnt++
}
ans += cnt * cnt
}
}
return
}
|
2,913
|
Subarrays Distinct Element Sum of Squares I
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>.</p>
<p>The <strong>distinct count</strong> of a subarray of <code>nums</code> is defined as:</p>
<ul>
<li>Let <code>nums[i..j]</code> be a subarray of <code>nums</code> consisting of all the indices from <code>i</code> to <code>j</code> such that <code>0 <= i <= j < nums.length</code>. Then the number of distinct values in <code>nums[i..j]</code> is called the distinct count of <code>nums[i..j]</code>.</li>
</ul>
<p>Return <em>the sum of the <strong>squares</strong> of <strong>distinct counts</strong> of all subarrays of </em><code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> 15
<strong>Explanation:</strong> Six possible subarrays are:
[1]: 1 distinct value
[2]: 1 distinct value
[1]: 1 distinct value
[1,2]: 2 distinct values
[2,1]: 2 distinct values
[1,2,1]: 2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> = 15.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three possible subarrays are:
[1]: 1 distinct value
[1]: 1 distinct value
[1,1]: 1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> = 3.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int sumCounts(List<Integer> nums) {
int ans = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
int[] s = new int[101];
int cnt = 0;
for (int j = i; j < n; ++j) {
if (++s[nums.get(j)] == 1) {
++cnt;
}
ans += cnt * cnt;
}
}
return ans;
}
}
|
2,913
|
Subarrays Distinct Element Sum of Squares I
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>.</p>
<p>The <strong>distinct count</strong> of a subarray of <code>nums</code> is defined as:</p>
<ul>
<li>Let <code>nums[i..j]</code> be a subarray of <code>nums</code> consisting of all the indices from <code>i</code> to <code>j</code> such that <code>0 <= i <= j < nums.length</code>. Then the number of distinct values in <code>nums[i..j]</code> is called the distinct count of <code>nums[i..j]</code>.</li>
</ul>
<p>Return <em>the sum of the <strong>squares</strong> of <strong>distinct counts</strong> of all subarrays of </em><code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> 15
<strong>Explanation:</strong> Six possible subarrays are:
[1]: 1 distinct value
[2]: 1 distinct value
[1]: 1 distinct value
[1,2]: 2 distinct values
[2,1]: 2 distinct values
[1,2,1]: 2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> = 15.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three possible subarrays are:
[1]: 1 distinct value
[1]: 1 distinct value
[1,1]: 1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> = 3.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def sumCounts(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(n):
s = set()
for j in range(i, n):
s.add(nums[j])
ans += len(s) * len(s)
return ans
|
2,913
|
Subarrays Distinct Element Sum of Squares I
|
Easy
|
<p>You are given a <strong>0-indexed </strong>integer array <code>nums</code>.</p>
<p>The <strong>distinct count</strong> of a subarray of <code>nums</code> is defined as:</p>
<ul>
<li>Let <code>nums[i..j]</code> be a subarray of <code>nums</code> consisting of all the indices from <code>i</code> to <code>j</code> such that <code>0 <= i <= j < nums.length</code>. Then the number of distinct values in <code>nums[i..j]</code> is called the distinct count of <code>nums[i..j]</code>.</li>
</ul>
<p>Return <em>the sum of the <strong>squares</strong> of <strong>distinct counts</strong> of all subarrays of </em><code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> 15
<strong>Explanation:</strong> Six possible subarrays are:
[1]: 1 distinct value
[2]: 1 distinct value
[1]: 1 distinct value
[1,2]: 2 distinct values
[2,1]: 2 distinct values
[1,2,1]: 2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> + 2<sup>2</sup> = 15.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Three possible subarrays are:
[1]: 1 distinct value
[1]: 1 distinct value
[1,1]: 1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> = 3.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function sumCounts(nums: number[]): number {
let ans = 0;
const n = nums.length;
for (let i = 0; i < n; ++i) {
const s: number[] = Array(101).fill(0);
let cnt = 0;
for (const x of nums.slice(i)) {
if (++s[x] === 1) {
++cnt;
}
ans += cnt * cnt;
}
}
return ans;
}
|
2,914
|
Minimum Number of Changes to Make Binary String Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> having an even length.</p>
<p>A string is <strong>beautiful</strong> if it's possible to partition it into one or more substrings such that:</p>
<ul>
<li>Each substring has an <strong>even length</strong>.</li>
<li>Each substring contains <strong>only</strong> <code>1</code>'s or <strong>only</strong> <code>0</code>'s.</li>
</ul>
<p>You can change any character in <code>s</code> to <code>0</code> or <code>1</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of changes required to make the string </em><code>s</code> <em>beautiful</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1001"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to make any changes as the string "0000" is beautiful already.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> has an even length.</li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
int minChanges(string s) {
int ans = 0;
int n = s.size();
for (int i = 1; i < n; i += 2) {
ans += s[i] != s[i - 1];
}
return ans;
}
};
|
2,914
|
Minimum Number of Changes to Make Binary String Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> having an even length.</p>
<p>A string is <strong>beautiful</strong> if it's possible to partition it into one or more substrings such that:</p>
<ul>
<li>Each substring has an <strong>even length</strong>.</li>
<li>Each substring contains <strong>only</strong> <code>1</code>'s or <strong>only</strong> <code>0</code>'s.</li>
</ul>
<p>You can change any character in <code>s</code> to <code>0</code> or <code>1</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of changes required to make the string </em><code>s</code> <em>beautiful</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1001"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to make any changes as the string "0000" is beautiful already.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> has an even length.</li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String
|
Go
|
func minChanges(s string) (ans int) {
for i := 1; i < len(s); i += 2 {
if s[i] != s[i-1] {
ans++
}
}
return
}
|
2,914
|
Minimum Number of Changes to Make Binary String Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> having an even length.</p>
<p>A string is <strong>beautiful</strong> if it's possible to partition it into one or more substrings such that:</p>
<ul>
<li>Each substring has an <strong>even length</strong>.</li>
<li>Each substring contains <strong>only</strong> <code>1</code>'s or <strong>only</strong> <code>0</code>'s.</li>
</ul>
<p>You can change any character in <code>s</code> to <code>0</code> or <code>1</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of changes required to make the string </em><code>s</code> <em>beautiful</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1001"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to make any changes as the string "0000" is beautiful already.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> has an even length.</li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String
|
Java
|
class Solution {
public int minChanges(String s) {
int ans = 0;
for (int i = 1; i < s.length(); i += 2) {
if (s.charAt(i) != s.charAt(i - 1)) {
++ans;
}
}
return ans;
}
}
|
2,914
|
Minimum Number of Changes to Make Binary String Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> having an even length.</p>
<p>A string is <strong>beautiful</strong> if it's possible to partition it into one or more substrings such that:</p>
<ul>
<li>Each substring has an <strong>even length</strong>.</li>
<li>Each substring contains <strong>only</strong> <code>1</code>'s or <strong>only</strong> <code>0</code>'s.</li>
</ul>
<p>You can change any character in <code>s</code> to <code>0</code> or <code>1</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of changes required to make the string </em><code>s</code> <em>beautiful</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1001"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to make any changes as the string "0000" is beautiful already.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> has an even length.</li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String
|
Python
|
class Solution:
def minChanges(self, s: str) -> int:
return sum(s[i] != s[i - 1] for i in range(1, len(s), 2))
|
2,914
|
Minimum Number of Changes to Make Binary String Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> binary string <code>s</code> having an even length.</p>
<p>A string is <strong>beautiful</strong> if it's possible to partition it into one or more substrings such that:</p>
<ul>
<li>Each substring has an <strong>even length</strong>.</li>
<li>Each substring contains <strong>only</strong> <code>1</code>'s or <strong>only</strong> <code>0</code>'s.</li>
</ul>
<p>You can change any character in <code>s</code> to <code>0</code> or <code>1</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of changes required to make the string </em><code>s</code> <em>beautiful</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "1001"
<strong>Output:</strong> 2
<strong>Explanation:</strong> We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "10"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "0000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to make any changes as the string "0000" is beautiful already.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> has an even length.</li>
<li><code>s[i]</code> is either <code>'0'</code> or <code>'1'</code>.</li>
</ul>
|
String
|
TypeScript
|
function minChanges(s: string): number {
let ans = 0;
for (let i = 1; i < s.length; i += 2) {
if (s[i] !== s[i - 1]) {
++ans;
}
}
return ans;
}
|
2,915
|
Length of the Longest Subsequence That Sums to Target
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>, and an integer <code>target</code>.</p>
<p>Return <em>the <strong>length of the longest subsequence</strong> of</em> <code>nums</code> <em>that sums up to</em> <code>target</code>. <em>If no such subsequence exists, return</em> <code>-1</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], target = 9
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,1,3,2,1,5], target = 7
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,5,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that nums has no subsequence that sums up to 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int lengthOfLongestSubsequence(vector<int>& nums, int target) {
int n = nums.size();
int f[n + 1][target + 1];
memset(f, -0x3f, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums[i - 1];
for (int j = 0; j <= target; ++j) {
f[i][j] = f[i - 1][j];
if (j >= x) {
f[i][j] = max(f[i][j], f[i - 1][j - x] + 1);
}
}
}
return f[n][target] <= 0 ? -1 : f[n][target];
}
};
|
2,915
|
Length of the Longest Subsequence That Sums to Target
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>, and an integer <code>target</code>.</p>
<p>Return <em>the <strong>length of the longest subsequence</strong> of</em> <code>nums</code> <em>that sums up to</em> <code>target</code>. <em>If no such subsequence exists, return</em> <code>-1</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], target = 9
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,1,3,2,1,5], target = 7
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,5,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that nums has no subsequence that sums up to 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func lengthOfLongestSubsequence(nums []int, target int) int {
n := len(nums)
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, target+1)
for j := range f[i] {
f[i][j] = -(1 << 30)
}
}
f[0][0] = 0
for i := 1; i <= n; i++ {
x := nums[i-1]
for j := 0; j <= target; j++ {
f[i][j] = f[i-1][j]
if j >= x {
f[i][j] = max(f[i][j], f[i-1][j-x]+1)
}
}
}
if f[n][target] <= 0 {
return -1
}
return f[n][target]
}
|
2,915
|
Length of the Longest Subsequence That Sums to Target
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>, and an integer <code>target</code>.</p>
<p>Return <em>the <strong>length of the longest subsequence</strong> of</em> <code>nums</code> <em>that sums up to</em> <code>target</code>. <em>If no such subsequence exists, return</em> <code>-1</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], target = 9
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,1,3,2,1,5], target = 7
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,5,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that nums has no subsequence that sums up to 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int lengthOfLongestSubsequence(List<Integer> nums, int target) {
int n = nums.size();
int[][] f = new int[n + 1][target + 1];
final int inf = 1 << 30;
for (int[] g : f) {
Arrays.fill(g, -inf);
}
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
int x = nums.get(i - 1);
for (int j = 0; j <= target; ++j) {
f[i][j] = f[i - 1][j];
if (j >= x) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1);
}
}
}
return f[n][target] <= 0 ? -1 : f[n][target];
}
}
|
2,915
|
Length of the Longest Subsequence That Sums to Target
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>, and an integer <code>target</code>.</p>
<p>Return <em>the <strong>length of the longest subsequence</strong> of</em> <code>nums</code> <em>that sums up to</em> <code>target</code>. <em>If no such subsequence exists, return</em> <code>-1</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], target = 9
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,1,3,2,1,5], target = 7
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,5,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that nums has no subsequence that sums up to 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int:
n = len(nums)
f = [[-inf] * (target + 1) for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(target + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = max(f[i][j], f[i - 1][j - x] + 1)
return -1 if f[n][target] <= 0 else f[n][target]
|
2,915
|
Length of the Longest Subsequence That Sums to Target
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code>, and an integer <code>target</code>.</p>
<p>Return <em>the <strong>length of the longest subsequence</strong> of</em> <code>nums</code> <em>that sums up to</em> <code>target</code>. <em>If no such subsequence exists, return</em> <code>-1</code>.</p>
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], target = 9
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,1,3,2,1,5], target = 7
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,5,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that nums has no subsequence that sums up to 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
<li><code>1 <= target <= 1000</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function lengthOfLongestSubsequence(nums: number[], target: number): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity));
f[0][0] = 0;
for (let i = 1; i <= n; ++i) {
const x = nums[i - 1];
for (let j = 0; j <= target; ++j) {
f[i][j] = f[i - 1][j];
if (j >= x) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1);
}
}
}
return f[n][target] <= 0 ? -1 : f[n][target];
}
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
int findKOr(vector<int>& nums, int k) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
int cnt = 0;
for (int x : nums) {
cnt += (x >> i & 1);
}
if (cnt >= k) {
ans |= 1 << i;
}
}
return ans;
}
};
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
C#
|
public class Solution {
public int FindKOr(int[] nums, int k) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
int cnt = 0;
foreach (int x in nums) {
cnt += (x >> i & 1);
}
if (cnt >= k) {
ans |= 1 << i;
}
}
return ans;
}
}
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func findKOr(nums []int, k int) (ans int) {
for i := 0; i < 32; i++ {
cnt := 0
for _, x := range nums {
cnt += (x >> i & 1)
}
if cnt >= k {
ans |= 1 << i
}
}
return
}
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public int findKOr(int[] nums, int k) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
int cnt = 0;
for (int x : nums) {
cnt += (x >> i & 1);
}
if (cnt >= k) {
ans |= 1 << i;
}
}
return ans;
}
}
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def findKOr(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(32):
cnt = sum(x >> i & 1 for x in nums)
if cnt >= k:
ans |= 1 << i
return ans
|
2,917
|
Find the K-or of an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>, and an integer <code>k</code>. Let's introduce <strong>K-or</strong> operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to <code>1</code> if at least <code>k</code> numbers in <code>nums</code> have a <code>1</code> in that position.</p>
<p>Return <em>the K-or of</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [7,12,9,8,9,15], k = 4 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 9 </span></p>
<p><strong>Explanation: </strong></p>
<p>Represent numbers in binary:</p>
<table style="text-indent:10px; margin-bottom=20px;">
<tbody>
<tr>
<th><b>Number</b></th>
<th>Bit 3</th>
<th>Bit 2</th>
<th>Bit 1</th>
<th>Bit 0</th>
</tr>
<tr>
<td><b>7</b></td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>12</b></td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>8</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><b>9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td><b>15</b></td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td><b>Result = 9</b></td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.<br />
Only bits 0 and 3 qualify. The result is <code>(1001)<sub>2</sub> = 9</code>.</p>
</div>
<p><strong class="example">Example 2: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,12,1,11,4,5], k = 6 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p>
<p><strong>Explanation: </strong>No bit appears as 1 in all six array numbers, as required for K-or with <code>k = 6</code>. Thus, the result is 0.</p>
</div>
<p><strong class="example">Example 3: </strong></p>
<div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;">
<p><strong>Input:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [10,8,5,9,11,6,8], k = 1 </span></p>
<p><strong>Output:</strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 15 </span></p>
<p><strong>Explanation: </strong> Since <code>k == 1</code>, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is <code>10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>0 <= nums[i] < 2<sup>31</sup></code></li>
<li><code>1 <= k <= nums.length</code></li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function findKOr(nums: number[], k: number): number {
let ans = 0;
for (let i = 0; i < 32; ++i) {
let cnt = 0;
for (const x of nums) {
cnt += (x >> i) & 1;
}
if (cnt >= k) {
ans |= 1 << i;
}
}
return ans;
}
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
long long minSum(vector<int>& nums1, vector<int>& nums2) {
long long s1 = 0, s2 = 0;
bool hasZero = false;
for (int x : nums1) {
hasZero |= x == 0;
s1 += max(x, 1);
}
for (int x : nums2) {
s2 += max(x, 1);
}
if (s1 > s2) {
return minSum(nums2, nums1);
}
if (s1 == s2) {
return s1;
}
return hasZero ? s2 : -1;
}
};
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
C#
|
public class Solution {
public long MinSum(int[] nums1, int[] nums2) {
long s1 = 0, s2 = 0;
bool hasZero = false;
foreach (int x in nums1) {
hasZero |= x == 0;
s1 += Math.Max(x, 1);
}
foreach (int x in nums2) {
s2 += Math.Max(x, 1);
}
if (s1 > s2) {
return MinSum(nums2, nums1);
}
if (s1 == s2) {
return s1;
}
return hasZero ? s2 : -1;
}
}
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Go
|
func minSum(nums1 []int, nums2 []int) int64 {
s1, s2 := 0, 0
hasZero := false
for _, x := range nums1 {
if x == 0 {
hasZero = true
}
s1 += max(x, 1)
}
for _, x := range nums2 {
s2 += max(x, 1)
}
if s1 > s2 {
return minSum(nums2, nums1)
}
if s1 == s2 {
return int64(s1)
}
if hasZero {
return int64(s2)
}
return -1
}
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public long minSum(int[] nums1, int[] nums2) {
long s1 = 0, s2 = 0;
boolean hasZero = false;
for (int x : nums1) {
hasZero |= x == 0;
s1 += Math.max(x, 1);
}
for (int x : nums2) {
s2 += Math.max(x, 1);
}
if (s1 > s2) {
return minSum(nums2, nums1);
}
if (s1 == s2) {
return s1;
}
return hasZero ? s2 : -1;
}
}
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def minSum(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1) + nums1.count(0)
s2 = sum(nums2) + nums2.count(0)
if s1 > s2:
return self.minSum(nums2, nums1)
if s1 == s2:
return s1
return -1 if nums1.count(0) == 0 else s2
|
2,918
|
Minimum Equal Sum of Two Arrays After Replacing Zeros
|
Medium
|
<p>You are given two arrays <code>nums1</code> and <code>nums2</code> consisting of positive integers.</p>
<p>You have to replace <strong>all</strong> the <code>0</code>'s in both arrays with <strong>strictly</strong> positive integers such that the sum of elements of both arrays becomes <strong>equal</strong>.</p>
<p>Return <em>the <strong>minimum</strong> equal sum you can obtain, or </em><code>-1</code><em> if it is impossible</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,2,0,1,0], nums2 = [6,5,0]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [2,0,2,0], nums2 = [1,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make the sum of both arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array
|
TypeScript
|
function minSum(nums1: number[], nums2: number[]): number {
let [s1, s2] = [0, 0];
let hasZero = false;
for (const x of nums1) {
if (x === 0) {
hasZero = true;
}
s1 += Math.max(x, 1);
}
for (const x of nums2) {
s2 += Math.max(x, 1);
}
if (s1 > s2) {
return minSum(nums2, nums1);
}
if (s1 === s2) {
return s1;
}
return hasZero ? s2 : -1;
}
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
long long minIncrementOperations(vector<int>& nums, int k) {
long long f = 0, g = 0, h = 0;
for (int x : nums) {
long long hh = min({f, g, h}) + max(k - x, 0);
f = g;
g = h;
h = hh;
}
return min({f, g, h});
}
};
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
C#
|
public class Solution {
public long MinIncrementOperations(int[] nums, int k) {
long f = 0, g = 0, h = 0;
foreach (int x in nums) {
long hh = Math.Min(Math.Min(f, g), h) + Math.Max(k - x, 0);
f = g;
g = h;
h = hh;
}
return Math.Min(Math.Min(f, g), h);
}
}
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func minIncrementOperations(nums []int, k int) int64 {
var f, g, h int
for _, x := range nums {
f, g, h = g, h, min(f, g, h)+max(k-x, 0)
}
return int64(min(f, g, h))
}
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public long minIncrementOperations(int[] nums, int k) {
long f = 0, g = 0, h = 0;
for (int x : nums) {
long hh = Math.min(Math.min(f, g), h) + Math.max(k - x, 0);
f = g;
g = h;
h = hh;
}
return Math.min(Math.min(f, g), h);
}
}
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def minIncrementOperations(self, nums: List[int], k: int) -> int:
f = g = h = 0
for x in nums:
f, g, h = g, h, min(f, g, h) + max(k - x, 0)
return min(f, g, h)
|
2,919
|
Minimum Increment Operations to Make Array Beautiful
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> having length <code>n</code>, and an integer <code>k</code>.</p>
<p>You can perform the following <strong>increment</strong> operation <strong>any</strong> number of times (<strong>including zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, n - 1]</code>, and increase <code>nums[i]</code> by <code>1</code>.</li>
</ul>
<p>An array is considered <strong>beautiful</strong> if, for any <strong>subarray</strong> with a size of <code>3</code> or <strong>more</strong>, its <strong>maximum</strong> element is <strong>greater than or equal</strong> to <code>k</code>.</p>
<p>Return <em>an integer denoting the <strong>minimum</strong> number of increment operations needed to make </em><code>nums</code><em> <strong>beautiful</strong>.</em></p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,0,0,2], k = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
Hence, the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [0,1,3,3], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can perform the following increment operations to make nums beautiful:
Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
Hence, the answer is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,2], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only subarray with a size of 3 or more in this example is [1,1,2].
The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
Hence, the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function minIncrementOperations(nums: number[], k: number): number {
let [f, g, h] = [0, 0, 0];
for (const x of nums) {
[f, g, h] = [g, h, Math.min(f, g, h) + Math.max(k - x, 0)];
}
return Math.min(f, g, h);
}
|
2,920
|
Maximum Points After Collecting Coins From All Nodes
|
Hard
|
<p>There exists an undirected tree rooted at node <code>0</code> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given a 2D <strong>integer</strong> array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given a <strong>0-indexed</strong> array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> indicates the number of coins in the vertex <code>i</code>, and an integer <code>k</code>.</p>
<p>Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.</p>
<p>Coins at <code>node<sub>i</sub></code> can be collected in one of the following ways:</p>
<ul>
<li>Collect all the coins, but you will get <code>coins[i] - k</code> points. If <code>coins[i] - k</code> is negative then you will lose <code>abs(coins[i] - k)</code> points.</li>
<li>Collect all the coins, but you will get <code>floor(coins[i] / 2)</code> points. If this way is used, then for all the <code>node<sub>j</sub></code> present in the subtree of <code>node<sub>i</sub></code>, <code>coins[j]</code> will get reduced to <code>floor(coins[j] / 2)</code>.</li>
</ul>
<p>Return <em>the <strong>maximum points</strong> you can get after collecting the coins from <strong>all</strong> the tree nodes.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex1-copy.png" style="width: 60px; height: 316px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
<strong>Output:</strong> 11
<strong>Explanation:</strong>
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.
Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.
Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.
Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.
It can be shown that the maximum points we can get after collecting coins from all the nodes is 11.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong class="example"> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex2.png" style="width: 140px; height: 147px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], coins = [8,4,4], k = 0
<strong>Output:</strong> 16
<strong>Explanation:</strong>
Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == coins.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">0 <= coins[i] <= 10<sup>4</sup></font></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code><font face="monospace">0 <= edges[i][0], edges[i][1] < n</font></code></li>
<li><code><font face="monospace">0 <= k <= 10<sup>4</sup></font></code></li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Memoization; Array; Dynamic Programming
|
C++
|
class Solution {
public:
int maximumPoints(vector<vector<int>>& edges, vector<int>& coins, int k) {
int n = coins.size();
int f[n][15];
memset(f, -1, sizeof(f));
vector<int> g[n];
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].emplace_back(b);
g[b].emplace_back(a);
}
auto dfs = [&](this auto&& dfs, int i, int fa, int j) -> int {
if (f[i][j] != -1) {
return f[i][j];
}
int a = (coins[i] >> j) - k;
int b = coins[i] >> (j + 1);
for (int c : g[i]) {
if (c != fa) {
a += dfs(c, i, j);
if (j < 14) {
b += dfs(c, i, j + 1);
}
}
}
return f[i][j] = max(a, b);
};
return dfs(0, -1, 0);
}
};
|
2,920
|
Maximum Points After Collecting Coins From All Nodes
|
Hard
|
<p>There exists an undirected tree rooted at node <code>0</code> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given a 2D <strong>integer</strong> array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given a <strong>0-indexed</strong> array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> indicates the number of coins in the vertex <code>i</code>, and an integer <code>k</code>.</p>
<p>Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.</p>
<p>Coins at <code>node<sub>i</sub></code> can be collected in one of the following ways:</p>
<ul>
<li>Collect all the coins, but you will get <code>coins[i] - k</code> points. If <code>coins[i] - k</code> is negative then you will lose <code>abs(coins[i] - k)</code> points.</li>
<li>Collect all the coins, but you will get <code>floor(coins[i] / 2)</code> points. If this way is used, then for all the <code>node<sub>j</sub></code> present in the subtree of <code>node<sub>i</sub></code>, <code>coins[j]</code> will get reduced to <code>floor(coins[j] / 2)</code>.</li>
</ul>
<p>Return <em>the <strong>maximum points</strong> you can get after collecting the coins from <strong>all</strong> the tree nodes.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex1-copy.png" style="width: 60px; height: 316px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
<strong>Output:</strong> 11
<strong>Explanation:</strong>
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.
Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.
Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.
Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.
It can be shown that the maximum points we can get after collecting coins from all the nodes is 11.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong class="example"> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex2.png" style="width: 140px; height: 147px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], coins = [8,4,4], k = 0
<strong>Output:</strong> 16
<strong>Explanation:</strong>
Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == coins.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">0 <= coins[i] <= 10<sup>4</sup></font></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code><font face="monospace">0 <= edges[i][0], edges[i][1] < n</font></code></li>
<li><code><font face="monospace">0 <= k <= 10<sup>4</sup></font></code></li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Memoization; Array; Dynamic Programming
|
Go
|
func maximumPoints(edges [][]int, coins []int, k int) int {
n := len(coins)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, 15)
for j := range f[i] {
f[i][j] = -1
}
}
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
var dfs func(int, int, int) int
dfs = func(i, fa, j int) int {
if f[i][j] != -1 {
return f[i][j]
}
a := (coins[i] >> j) - k
b := coins[i] >> (j + 1)
for _, c := range g[i] {
if c != fa {
a += dfs(c, i, j)
if j < 14 {
b += dfs(c, i, j+1)
}
}
}
f[i][j] = max(a, b)
return f[i][j]
}
return dfs(0, -1, 0)
}
|
2,920
|
Maximum Points After Collecting Coins From All Nodes
|
Hard
|
<p>There exists an undirected tree rooted at node <code>0</code> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given a 2D <strong>integer</strong> array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given a <strong>0-indexed</strong> array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> indicates the number of coins in the vertex <code>i</code>, and an integer <code>k</code>.</p>
<p>Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.</p>
<p>Coins at <code>node<sub>i</sub></code> can be collected in one of the following ways:</p>
<ul>
<li>Collect all the coins, but you will get <code>coins[i] - k</code> points. If <code>coins[i] - k</code> is negative then you will lose <code>abs(coins[i] - k)</code> points.</li>
<li>Collect all the coins, but you will get <code>floor(coins[i] / 2)</code> points. If this way is used, then for all the <code>node<sub>j</sub></code> present in the subtree of <code>node<sub>i</sub></code>, <code>coins[j]</code> will get reduced to <code>floor(coins[j] / 2)</code>.</li>
</ul>
<p>Return <em>the <strong>maximum points</strong> you can get after collecting the coins from <strong>all</strong> the tree nodes.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex1-copy.png" style="width: 60px; height: 316px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
<strong>Output:</strong> 11
<strong>Explanation:</strong>
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.
Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.
Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.
Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.
It can be shown that the maximum points we can get after collecting coins from all the nodes is 11.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong class="example"> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex2.png" style="width: 140px; height: 147px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], coins = [8,4,4], k = 0
<strong>Output:</strong> 16
<strong>Explanation:</strong>
Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == coins.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">0 <= coins[i] <= 10<sup>4</sup></font></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code><font face="monospace">0 <= edges[i][0], edges[i][1] < n</font></code></li>
<li><code><font face="monospace">0 <= k <= 10<sup>4</sup></font></code></li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Memoization; Array; Dynamic Programming
|
Java
|
class Solution {
private int k;
private int[] coins;
private Integer[][] f;
private List<Integer>[] g;
public int maximumPoints(int[][] edges, int[] coins, int k) {
this.k = k;
this.coins = coins;
int n = coins.length;
f = new Integer[n][15];
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
return dfs(0, -1, 0);
}
private int dfs(int i, int fa, int j) {
if (f[i][j] != null) {
return f[i][j];
}
int a = (coins[i] >> j) - k;
int b = coins[i] >> (j + 1);
for (int c : g[i]) {
if (c != fa) {
a += dfs(c, i, j);
if (j < 14) {
b += dfs(c, i, j + 1);
}
}
}
return f[i][j] = Math.max(a, b);
}
}
|
2,920
|
Maximum Points After Collecting Coins From All Nodes
|
Hard
|
<p>There exists an undirected tree rooted at node <code>0</code> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given a 2D <strong>integer</strong> array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given a <strong>0-indexed</strong> array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> indicates the number of coins in the vertex <code>i</code>, and an integer <code>k</code>.</p>
<p>Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.</p>
<p>Coins at <code>node<sub>i</sub></code> can be collected in one of the following ways:</p>
<ul>
<li>Collect all the coins, but you will get <code>coins[i] - k</code> points. If <code>coins[i] - k</code> is negative then you will lose <code>abs(coins[i] - k)</code> points.</li>
<li>Collect all the coins, but you will get <code>floor(coins[i] / 2)</code> points. If this way is used, then for all the <code>node<sub>j</sub></code> present in the subtree of <code>node<sub>i</sub></code>, <code>coins[j]</code> will get reduced to <code>floor(coins[j] / 2)</code>.</li>
</ul>
<p>Return <em>the <strong>maximum points</strong> you can get after collecting the coins from <strong>all</strong> the tree nodes.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex1-copy.png" style="width: 60px; height: 316px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
<strong>Output:</strong> 11
<strong>Explanation:</strong>
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.
Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.
Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.
Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.
It can be shown that the maximum points we can get after collecting coins from all the nodes is 11.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong class="example"> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex2.png" style="width: 140px; height: 147px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], coins = [8,4,4], k = 0
<strong>Output:</strong> 16
<strong>Explanation:</strong>
Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == coins.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">0 <= coins[i] <= 10<sup>4</sup></font></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code><font face="monospace">0 <= edges[i][0], edges[i][1] < n</font></code></li>
<li><code><font face="monospace">0 <= k <= 10<sup>4</sup></font></code></li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Memoization; Array; Dynamic Programming
|
Python
|
class Solution:
def maximumPoints(self, edges: List[List[int]], coins: List[int], k: int) -> int:
@cache
def dfs(i: int, fa: int, j: int) -> int:
a = (coins[i] >> j) - k
b = coins[i] >> (j + 1)
for c in g[i]:
if c != fa:
a += dfs(c, i, j)
if j < 14:
b += dfs(c, i, j + 1)
return max(a, b)
n = len(coins)
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = dfs(0, -1, 0)
dfs.cache_clear()
return ans
|
2,920
|
Maximum Points After Collecting Coins From All Nodes
|
Hard
|
<p>There exists an undirected tree rooted at node <code>0</code> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given a 2D <strong>integer</strong> array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given a <strong>0-indexed</strong> array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> indicates the number of coins in the vertex <code>i</code>, and an integer <code>k</code>.</p>
<p>Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.</p>
<p>Coins at <code>node<sub>i</sub></code> can be collected in one of the following ways:</p>
<ul>
<li>Collect all the coins, but you will get <code>coins[i] - k</code> points. If <code>coins[i] - k</code> is negative then you will lose <code>abs(coins[i] - k)</code> points.</li>
<li>Collect all the coins, but you will get <code>floor(coins[i] / 2)</code> points. If this way is used, then for all the <code>node<sub>j</sub></code> present in the subtree of <code>node<sub>i</sub></code>, <code>coins[j]</code> will get reduced to <code>floor(coins[j] / 2)</code>.</li>
</ul>
<p>Return <em>the <strong>maximum points</strong> you can get after collecting the coins from <strong>all</strong> the tree nodes.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex1-copy.png" style="width: 60px; height: 316px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
<strong>Output:</strong> 11
<strong>Explanation:</strong>
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.
Collect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.
Collect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.
Collect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.
It can be shown that the maximum points we can get after collecting coins from all the nodes is 11.
</pre>
<p><strong class="example">Example 2:</strong></p>
<strong class="example"> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2920.Maximum%20Points%20After%20Collecting%20Coins%20From%20All%20Nodes/images/ex2.png" style="width: 140px; height: 147px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong>
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], coins = [8,4,4], k = 0
<strong>Output:</strong> 16
<strong>Explanation:</strong>
Coins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == coins.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code><font face="monospace">0 <= coins[i] <= 10<sup>4</sup></font></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code><font face="monospace">0 <= edges[i][0], edges[i][1] < n</font></code></li>
<li><code><font face="monospace">0 <= k <= 10<sup>4</sup></font></code></li>
</ul>
|
Bit Manipulation; Tree; Depth-First Search; Memoization; Array; Dynamic Programming
|
TypeScript
|
function maximumPoints(edges: number[][], coins: number[], k: number): number {
const n = coins.length;
const f: number[][] = Array.from({ length: n }, () => Array(15).fill(-1));
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const dfs = (i: number, fa: number, j: number): number => {
if (f[i][j] !== -1) {
return f[i][j];
}
let a = (coins[i] >> j) - k;
let b = coins[i] >> (j + 1);
for (const c of g[i]) {
if (c !== fa) {
a += dfs(c, i, j);
if (j < 14) {
b += dfs(c, i, j + 1);
}
}
}
return (f[i][j] = Math.max(a, b));
};
return dfs(0, -1, 0);
}
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
C++
|
class BinaryIndexedTree {
private:
int n;
vector<int> c;
public:
BinaryIndexedTree(int n) {
this->n = n;
c.resize(n + 1, 0);
}
void update(int x, int v) {
while (x <= n) {
c[x] = max(c[x], v);
x += x & -x;
}
}
int query(int x) {
int mx = 0;
while (x > 0) {
mx = max(mx, c[x]);
x -= x & -x;
}
return mx;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices, vector<int>& profits) {
int n = prices.size();
vector<int> left(n, 0);
vector<int> right(n, 0);
int m = *max_element(prices.begin(), prices.end());
BinaryIndexedTree tree1(m + 1);
BinaryIndexedTree tree2(m + 1);
for (int i = 0; i < n; ++i) {
int x = prices[i];
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (int i = n - 1; i >= 0; --i) {
int x = m + 1 - prices[i];
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
int ans = -1;
for (int i = 0; i < n; ++i) {
if (left[i] > 0 && right[i] > 0) {
ans = max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
};
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
c := make([]int, n+1)
return BinaryIndexedTree{n: n, c: c}
}
func (bit *BinaryIndexedTree) update(x, v int) {
for x <= bit.n {
bit.c[x] = max(bit.c[x], v)
x += x & -x
}
}
func (bit *BinaryIndexedTree) query(x int) int {
mx := 0
for x > 0 {
mx = max(mx, bit.c[x])
x -= x & -x
}
return mx
}
func maxProfit(prices []int, profits []int) int {
n := len(prices)
left := make([]int, n)
right := make([]int, n)
m := slices.Max(prices)
tree1 := NewBinaryIndexedTree(m + 1)
tree2 := NewBinaryIndexedTree(m + 1)
for i, x := range prices {
left[i] = tree1.query(x - 1)
tree1.update(x, profits[i])
}
for i := n - 1; i >= 0; i-- {
x := m + 1 - prices[i]
right[i] = tree2.query(x - 1)
tree2.update(x, profits[i])
}
ans := -1
for i := 0; i < n; i++ {
if left[i] > 0 && right[i] > 0 {
ans = max(ans, left[i]+profits[i]+right[i])
}
}
return ans
}
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int v) {
while (x <= n) {
c[x] = Math.max(c[x], v);
x += x & -x;
}
}
public int query(int x) {
int mx = 0;
while (x > 0) {
mx = Math.max(mx, c[x]);
x -= x & -x;
}
return mx;
}
}
class Solution {
public int maxProfit(int[] prices, int[] profits) {
int n = prices.length;
int[] left = new int[n];
int[] right = new int[n];
int m = 0;
for (int x : prices) {
m = Math.max(m, x);
}
BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1);
BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1);
for (int i = 0; i < n; ++i) {
int x = prices[i];
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (int i = n - 1; i >= 0; --i) {
int x = m + 1 - prices[i];
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
int ans = -1;
for (int i = 0; i < n; ++i) {
if (left[i] > 0 && right[i] > 0) {
ans = Math.max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
}
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Python
|
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = 0
while x:
mx = max(mx, self.c[x])
x -= x & -x
return mx
class Solution:
def maxProfit(self, prices: List[int], profits: List[int]) -> int:
n = len(prices)
left = [0] * n
right = [0] * n
m = max(prices)
tree1 = BinaryIndexedTree(m + 1)
tree2 = BinaryIndexedTree(m + 1)
for i, x in enumerate(prices):
left[i] = tree1.query(x - 1)
tree1.update(x, profits[i])
for i in range(n - 1, -1, -1):
x = m + 1 - prices[i]
right[i] = tree2.query(x - 1)
tree2.update(x, profits[i])
return max(
(l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1
)
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
Rust
|
struct BinaryIndexedTree {
n: usize,
c: Vec<i32>,
}
impl BinaryIndexedTree {
fn new(n: usize) -> BinaryIndexedTree {
BinaryIndexedTree {
n,
c: vec![0; n + 1],
}
}
fn update(&mut self, x: usize, v: i32) {
let mut x = x;
while x <= self.n {
self.c[x] = self.c[x].max(v);
x += x & x.wrapping_neg();
}
}
fn query(&self, x: usize) -> i32 {
let mut x = x;
let mut mx = 0;
while x > 0 {
mx = mx.max(self.c[x]);
x -= x & x.wrapping_neg();
}
mx
}
}
impl Solution {
pub fn max_profit(prices: Vec<i32>, profits: Vec<i32>) -> i32 {
let n = prices.len();
let mut left = vec![0; n];
let mut right = vec![0; n];
let m = prices.iter().cloned().max().unwrap_or(0);
let mut tree1 = BinaryIndexedTree::new((m as usize) + 1);
let mut tree2 = BinaryIndexedTree::new((m as usize) + 1);
for i in 0..n {
let x = prices[i] as usize;
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for i in (0..n).rev() {
let x = (m + 1 - prices[i]) as usize;
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
let mut ans = -1;
for i in 0..n {
if left[i] > 0 && right[i] > 0 {
ans = ans.max(left[i] + profits[i] + right[i]);
}
}
ans
}
}
|
2,921
|
Maximum Profitable Triplets With Increasing Prices II
|
Hard
|
<p>Given the <strong>0-indexed</strong> arrays <code>prices</code> and <code>profits</code> of length <code>n</code>. There are <code>n</code> items in an store where the <code>i<sup>th</sup></code> item has a price of <code>prices[i]</code> and a profit of <code>profits[i]</code>.</p>
<p>We have to pick three items with the following condition:</p>
<ul>
<li><code>prices[i] < prices[j] < prices[k]</code> where <code>i < j < k</code>.</li>
</ul>
<p>If we pick items with indices <code>i</code>, <code>j</code> and <code>k</code> satisfying the above condition, the profit would be <code>profits[i] + profits[j] + profits[k]</code>.</p>
<p>Return<em> the <strong>maximum profit</strong> we can get, and </em><code>-1</code><em> if it's not possible to pick three items with the given condition.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [10,2,3,4], profits = [100,2,7,10]
<strong>Output:</strong> 19
<strong>Explanation:</strong> We can't pick the item with index i=0 since there are no indices j and k such that the condition holds.
So the only triplet we can pick, are the items with indices 1, 2 and 3 and it's a valid pick since prices[1] < prices[2] < prices[3].
The answer would be sum of their profits which is 2 + 7 + 10 = 19.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,2,3,4,5], profits = [1,5,3,4,6]
<strong>Output:</strong> 15
<strong>Explanation:</strong> We can select any triplet of items since for each triplet of indices i, j and k such that i < j < k, the condition holds.
Therefore the maximum profit we can get would be the 3 most profitable items which are indices 1, 3 and 4.
The answer would be sum of their profits which is 5 + 4 + 6 = 15.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [4,3,2,1], profits = [33,20,19,87]
<strong>Output:</strong> -1
<strong>Explanation:</strong> We can't select any triplet of indices such that the condition holds, so we return -1.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= prices.length == profits.length <= 50000</code></li>
<li><code>1 <= prices[i] <= 5000</code></li>
<li><code>1 <= profits[i] <= 10<sup>6</sup></code></li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array
|
TypeScript
|
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] = Math.max(this.c[x], v);
x += x & -x;
}
}
query(x: number): number {
let mx = 0;
while (x > 0) {
mx = Math.max(mx, this.c[x]);
x -= x & -x;
}
return mx;
}
}
function maxProfit(prices: number[], profits: number[]): number {
const n: number = prices.length;
const left: number[] = Array(n).fill(0);
const right: number[] = Array(n).fill(0);
const m = Math.max(...prices);
const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1);
const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1);
for (let i = 0; i < n; i++) {
const x: number = prices[i];
left[i] = tree1.query(x - 1);
tree1.update(x, profits[i]);
}
for (let i = n - 1; i >= 0; i--) {
const x: number = m + 1 - prices[i];
right[i] = tree2.query(x - 1);
tree2.update(x, profits[i]);
}
let ans: number = -1;
for (let i = 0; i < n; i++) {
if (left[i] > 0 && right[i] > 0) {
ans = Math.max(ans, left[i] + profits[i] + right[i]);
}
}
return ans;
}
|
2,922
|
Market Analysis III
|
Medium
|
<p>Table: <code>Users</code></p>
<pre>
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| seller_id | int |
| join_date | date |
| favorite_brand | varchar |
+----------------+---------+
seller_id is column of unique values for this table.
This table contains seller id, join date, and favorite brand of sellers.
</pre>
<p>Table: <code>Items</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| item_id | int |
| item_brand | varchar |
+---------------+---------+
item_id is the column of unique values for this table.
This table contains item id and item brand.</pre>
<p>Table: <code>Orders</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| order_id | int |
| order_date | date |
| item_id | int |
| seller_id | int |
+---------------+---------+
order_id is the column of unique values for this table.
item_id is a foreign key to the Items table.
seller_id is a foreign key to the Users table.
This table contains order id, order date, item id and seller id.</pre>
<p>Write a solution to find the <strong>top seller</strong> who has sold the highest number of<strong> unique</strong> items with a <strong>different</strong> brand than their favorite brand. If there are multiple sellers with the same highest count, return all of them.</p>
<p>Return <em>the result table ordered by</em> <code>seller_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 1:</strong></p>
<pre>
<strong>Input:</strong>
Users table:
+-----------+------------+----------------+
| seller_id | join_date | favorite_brand |
+-----------+------------+----------------+
| 1 | 2019-01-01 | Lenovo |
| 2 | 2019-02-09 | Samsung |
| 3 | 2019-01-19 | LG |
+-----------+------------+----------------+
Orders table:
+----------+------------+---------+-----------+
| order_id | order_date | item_id | seller_id |
+----------+------------+---------+-----------+
| 1 | 2019-08-01 | 4 | 2 |
| 2 | 2019-08-02 | 2 | 3 |
| 3 | 2019-08-03 | 3 | 3 |
| 4 | 2019-08-04 | 1 | 2 |
| 5 | 2019-08-04 | 4 | 2 |
+----------+------------+---------+-----------+
Items table:
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1 | Samsung |
| 2 | Lenovo |
| 3 | LG |
| 4 | HP |
+---------+------------+
<strong>Output:</strong>
+-----------+-----------+
| seller_id | num_items |
+-----------+-----------+
| 2 | 1 |
| 3 | 1 |
+-----------+-----------+
<strong>Explanation:</strong>
- The user with seller_id 2 has sold three items, but only two of them are not marked as a favorite. We will include a unique count of 1 because both of these items are identical.
- The user with seller_id 3 has sold two items, but only one of them is not marked as a favorite. We will include just that non-favorite item in our count.
Since seller_ids 2 and 3 have the same count of one item each, they both will be displayed in the output.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT seller_id, COUNT(DISTINCT item_id) AS num_items
FROM
Orders
JOIN Users USING (seller_id)
JOIN Items USING (item_id)
WHERE item_brand != favorite_brand
GROUP BY 1
)
SELECT seller_id, num_items
FROM T
WHERE num_items = (SELECT MAX(num_items) FROM T)
ORDER BY 1;
|
2,923
|
Find Champion I
|
Easy
|
<p>There are <code>n</code> teams numbered from <code>0</code> to <code>n - 1</code> in a tournament.</p>
<p>Given a <strong>0-indexed</strong> 2D boolean matrix <code>grid</code> of size <code>n * n</code>. For all <code>i, j</code> that <code>0 <= i, j <= n - 1</code> and <code>i != j</code> team <code>i</code> is <strong>stronger</strong> than team <code>j</code> if <code>grid[i][j] == 1</code>, otherwise, team <code>j</code> is <strong>stronger</strong> than team <code>i</code>.</p>
<p>Team <code>a</code> will be the <strong>champion</strong> of the tournament if there is no team <code>b</code> that is stronger than team <code>a</code>.</p>
<p>Return <em>the team that will be the champion of the tournament.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,1],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are two teams in this tournament.
grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[0,0,1],[1,0,1],[0,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are three teams in this tournament.
grid[1][0] == 1 means that team 1 is stronger than team 0.
grid[1][2] == 1 means that team 1 is stronger than team 2.
So team 1 will be the champion.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>2 <= n <= 100</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>For all <code>i grid[i][i]</code> is <code>0.</code></li>
<li>For all <code>i, j</code> that <code>i != j</code>, <code>grid[i][j] != grid[j][i]</code>.</li>
<li>The input is generated such that if team <code>a</code> is stronger than team <code>b</code> and team <code>b</code> is stronger than team <code>c</code>, then team <code>a</code> is stronger than team <code>c</code>.</li>
</ul>
|
Array; Matrix
|
C++
|
class Solution {
public:
int findChampion(vector<vector<int>>& grid) {
int n = grid.size();
for (int i = 0;; ++i) {
int cnt = 0;
for (int j = 0; j < n; ++j) {
if (i != j && grid[i][j] == 1) {
++cnt;
}
}
if (cnt == n - 1) {
return i;
}
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.