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
|
|---|---|---|---|---|---|---|
3,099
|
Harshad Number
|
Easy
|
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 18</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x <= 100</code></li>
</ul>
|
Math
|
Java
|
class Solution {
public int sumOfTheDigitsOfHarshadNumber(int x) {
int s = 0;
for (int y = x; y > 0; y /= 10) {
s += y % 10;
}
return x % s == 0 ? s : -1;
}
}
|
3,099
|
Harshad Number
|
Easy
|
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 18</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x <= 100</code></li>
</ul>
|
Math
|
Python
|
class Solution:
def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
s, y = 0, x
while y:
s += y % 10
y //= 10
return s if x % s == 0 else -1
|
3,099
|
Harshad Number
|
Easy
|
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 18</span></p>
<p><strong>Output:</strong> <span class="example-io">9</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 23</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x <= 100</code></li>
</ul>
|
Math
|
TypeScript
|
function sumOfTheDigitsOfHarshadNumber(x: number): number {
let s = 0;
for (let y = x; y; y = Math.floor(y / 10)) {
s += y % 10;
}
return x % s === 0 ? s : -1;
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
C++
|
class Solution {
public:
int maxBottlesDrunk(int numBottles, int numExchange) {
int ans = numBottles;
while (numBottles >= numExchange) {
numBottles -= numExchange;
++numExchange;
++ans;
++numBottles;
}
return ans;
}
};
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
C#
|
public class Solution {
public int MaxBottlesDrunk(int numBottles, int numExchange) {
int ans = numBottles;
while (numBottles >= numExchange) {
numBottles -= numExchange;
++numExchange;
++ans;
++numBottles;
}
return ans;
}
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
Go
|
func maxBottlesDrunk(numBottles int, numExchange int) int {
ans := numBottles
for numBottles >= numExchange {
numBottles -= numExchange
numExchange++
ans++
numBottles++
}
return ans
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
Java
|
class Solution {
public int maxBottlesDrunk(int numBottles, int numExchange) {
int ans = numBottles;
while (numBottles >= numExchange) {
numBottles -= numExchange;
++numExchange;
++ans;
++numBottles;
}
return ans;
}
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
PHP
|
class Solution {
/**
* @param Integer $numBottles
* @param Integer $numExchange
* @return Integer
*/
function maxBottlesDrunk($numBottles, $numExchange) {
$ans = $numBottles;
while ($numBottles >= $numExchange) {
$numBottles -= $numExchange;
$numExchange++;
$ans++;
$numBottles++;
}
return $ans;
}
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
Python
|
class Solution:
def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
numBottles -= numExchange
numExchange += 1
ans += 1
numBottles += 1
return ans
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
Rust
|
impl Solution {
pub fn max_bottles_drunk(mut num_bottles: i32, mut num_exchange: i32) -> i32 {
let mut ans = num_bottles;
while num_bottles >= num_exchange {
num_bottles -= num_exchange;
num_exchange += 1;
ans += 1;
num_bottles += 1;
}
ans
}
}
|
3,100
|
Water Bottles II
|
Medium
|
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p>
<p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p>
<ul>
<li>Drink any number of full water bottles turning them into empty bottles.</li>
<li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li>
</ul>
<p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p>
<p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 13, numExchange = 6
<strong>Output:</strong> 15
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" />
<pre>
<strong>Input:</strong> numBottles = 10, numExchange = 3
<strong>Output:</strong> 13
<strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= numBottles <= 100 </code></li>
<li><code>1 <= numExchange <= 100</code></li>
</ul>
|
Math; Simulation
|
TypeScript
|
function maxBottlesDrunk(numBottles: number, numExchange: number): number {
let ans = numBottles;
while (numBottles >= numExchange) {
numBottles -= numExchange;
++numExchange;
++ans;
++numBottles;
}
return ans;
}
|
3,101
|
Count Alternating Subarrays
|
Medium
|
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
long long countAlternatingSubarrays(vector<int>& nums) {
long long ans = 1, s = 1;
for (int i = 1; i < nums.size(); ++i) {
s = nums[i] != nums[i - 1] ? s + 1 : 1;
ans += s;
}
return ans;
}
};
|
3,101
|
Count Alternating Subarrays
|
Medium
|
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Math
|
Go
|
func countAlternatingSubarrays(nums []int) int64 {
ans, s := int64(1), int64(1)
for i, x := range nums[1:] {
if x != nums[i] {
s++
} else {
s = 1
}
ans += s
}
return ans
}
|
3,101
|
Count Alternating Subarrays
|
Medium
|
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public long countAlternatingSubarrays(int[] nums) {
long ans = 1, s = 1;
for (int i = 1; i < nums.length; ++i) {
s = nums[i] != nums[i - 1] ? s + 1 : 1;
ans += s;
}
return ans;
}
}
|
3,101
|
Count Alternating Subarrays
|
Medium
|
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def countAlternatingSubarrays(self, nums: List[int]) -> int:
ans = s = 1
for a, b in pairwise(nums):
s = s + 1 if a != b else 1
ans += s
return ans
|
3,101
|
Count Alternating Subarrays
|
Medium
|
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p>
<p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p>
<p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong></p>
<p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Array; Math
|
TypeScript
|
function countAlternatingSubarrays(nums: number[]): number {
let [ans, s] = [1, 1];
for (let i = 1; i < nums.length; ++i) {
s = nums[i] !== nums[i - 1] ? s + 1 : 1;
ans += s;
}
return ans;
}
|
3,102
|
Minimize Manhattan Distances
|
Hard
|
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum distance after removing each point is the following:</p>
<ul>
<li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
<li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li>
<li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li>
<li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
</ul>
<p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing any of the points results in the maximum distance between any two points of 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>1 <= points[i][0], points[i][1] <= 10<sup>8</sup></code></li>
</ul>
|
Geometry; Array; Math; Ordered Set; Sorting
|
C++
|
class Solution {
public:
int minimumDistance(vector<vector<int>>& points) {
multiset<int> st1;
multiset<int> st2;
for (auto& p : points) {
int x = p[0], y = p[1];
st1.insert(x + y);
st2.insert(x - y);
}
int ans = INT_MAX;
for (auto& p : points) {
int x = p[0], y = p[1];
st1.erase(st1.find(x + y));
st2.erase(st2.find(x - y));
ans = min(ans, max(*st1.rbegin() - *st1.begin(), *st2.rbegin() - *st2.begin()));
st1.insert(x + y);
st2.insert(x - y);
}
return ans;
}
};
|
3,102
|
Minimize Manhattan Distances
|
Hard
|
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum distance after removing each point is the following:</p>
<ul>
<li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
<li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li>
<li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li>
<li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
</ul>
<p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing any of the points results in the maximum distance between any two points of 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>1 <= points[i][0], points[i][1] <= 10<sup>8</sup></code></li>
</ul>
|
Geometry; Array; Math; Ordered Set; Sorting
|
Go
|
func minimumDistance(points [][]int) int {
st1 := redblacktree.New[int, int]()
st2 := redblacktree.New[int, int]()
merge := func(st *redblacktree.Tree[int, int], x, v int) {
c, _ := st.Get(x)
if c+v == 0 {
st.Remove(x)
} else {
st.Put(x, c+v)
}
}
for _, p := range points {
x, y := p[0], p[1]
merge(st1, x+y, 1)
merge(st2, x-y, 1)
}
ans := math.MaxInt
for _, p := range points {
x, y := p[0], p[1]
merge(st1, x+y, -1)
merge(st2, x-y, -1)
ans = min(ans, max(st1.Right().Key-st1.Left().Key, st2.Right().Key-st2.Left().Key))
merge(st1, x+y, 1)
merge(st2, x-y, 1)
}
return ans
}
|
3,102
|
Minimize Manhattan Distances
|
Hard
|
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum distance after removing each point is the following:</p>
<ul>
<li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
<li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li>
<li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li>
<li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
</ul>
<p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing any of the points results in the maximum distance between any two points of 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>1 <= points[i][0], points[i][1] <= 10<sup>8</sup></code></li>
</ul>
|
Geometry; Array; Math; Ordered Set; Sorting
|
Java
|
class Solution {
public int minimumDistance(int[][] points) {
TreeMap<Integer, Integer> tm1 = new TreeMap<>();
TreeMap<Integer, Integer> tm2 = new TreeMap<>();
for (int[] p : points) {
int x = p[0], y = p[1];
tm1.merge(x + y, 1, Integer::sum);
tm2.merge(x - y, 1, Integer::sum);
}
int ans = Integer.MAX_VALUE;
for (int[] p : points) {
int x = p[0], y = p[1];
if (tm1.merge(x + y, -1, Integer::sum) == 0) {
tm1.remove(x + y);
}
if (tm2.merge(x - y, -1, Integer::sum) == 0) {
tm2.remove(x - y);
}
ans = Math.min(
ans, Math.max(tm1.lastKey() - tm1.firstKey(), tm2.lastKey() - tm2.firstKey()));
tm1.merge(x + y, 1, Integer::sum);
tm2.merge(x - y, 1, Integer::sum);
}
return ans;
}
}
|
3,102
|
Minimize Manhattan Distances
|
Hard
|
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum distance after removing each point is the following:</p>
<ul>
<li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
<li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li>
<li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li>
<li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
</ul>
<p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing any of the points results in the maximum distance between any two points of 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>1 <= points[i][0], points[i][1] <= 10<sup>8</sup></code></li>
</ul>
|
Geometry; Array; Math; Ordered Set; Sorting
|
Python
|
class Solution:
def minimumDistance(self, points: List[List[int]]) -> int:
sl1 = SortedList()
sl2 = SortedList()
for x, y in points:
sl1.add(x + y)
sl2.add(x - y)
ans = inf
for x, y in points:
sl1.remove(x + y)
sl2.remove(x - y)
ans = min(ans, max(sl1[-1] - sl1[0], sl2[-1] - sl2[0]))
sl1.add(x + y)
sl2.add(x - y)
return ans
|
3,102
|
Minimize Manhattan Distances
|
Hard
|
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p>
<p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The maximum distance after removing each point is the following:</p>
<ul>
<li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
<li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li>
<li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li>
<li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li>
</ul>
<p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>Removing any of the points results in the maximum distance between any two points of 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>1 <= points[i][0], points[i][1] <= 10<sup>8</sup></code></li>
</ul>
|
Geometry; Array; Math; Ordered Set; Sorting
|
TypeScript
|
function minimumDistance(points: number[][]): number {
const st1 = new TreapMultiSet<number>();
const st2 = new TreapMultiSet<number>();
for (const [x, y] of points) {
st1.add(x + y);
st2.add(x - y);
}
let ans = Infinity;
for (const [x, y] of points) {
st1.delete(x + y);
st2.delete(x - y);
ans = Math.min(ans, Math.max(st1.last() - st1.first(), st2.last() - st2.first()));
st1.add(x + y);
st2.add(x - y);
}
return ans;
}
type CompareFunction<T, R extends 'number' | 'boolean'> = (
a: T,
b: T,
) => R extends 'number' ? number : boolean;
interface ITreapMultiSet<T> extends Iterable<T> {
add: (...value: T[]) => this;
has: (value: T) => boolean;
delete: (value: T) => void;
bisectLeft: (value: T) => number;
bisectRight: (value: T) => number;
indexOf: (value: T) => number;
lastIndexOf: (value: T) => number;
at: (index: number) => T | undefined;
first: () => T | undefined;
last: () => T | undefined;
lower: (value: T) => T | undefined;
higher: (value: T) => T | undefined;
floor: (value: T) => T | undefined;
ceil: (value: T) => T | undefined;
shift: () => T | undefined;
pop: (index?: number) => T | undefined;
count: (value: T) => number;
keys: () => IterableIterator<T>;
values: () => IterableIterator<T>;
rvalues: () => IterableIterator<T>;
entries: () => IterableIterator<[number, T]>;
readonly size: number;
}
class TreapNode<T = number> {
value: T;
count: number;
size: number;
priority: number;
left: TreapNode<T> | null;
right: TreapNode<T> | null;
constructor(value: T) {
this.value = value;
this.count = 1;
this.size = 1;
this.priority = Math.random();
this.left = null;
this.right = null;
}
static getSize(node: TreapNode<any> | null): number {
return node?.size ?? 0;
}
static getFac(node: TreapNode<any> | null): number {
return node?.priority ?? 0;
}
pushUp(): void {
let tmp = this.count;
tmp += TreapNode.getSize(this.left);
tmp += TreapNode.getSize(this.right);
this.size = tmp;
}
rotateRight(): TreapNode<T> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let node: TreapNode<T> = this;
const left = node.left;
node.left = left?.right ?? null;
left && (left.right = node);
left && (node = left);
node.right?.pushUp();
node.pushUp();
return node;
}
rotateLeft(): TreapNode<T> {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let node: TreapNode<T> = this;
const right = node.right;
node.right = right?.left ?? null;
right && (right.left = node);
right && (node = right);
node.left?.pushUp();
node.pushUp();
return node;
}
}
class TreapMultiSet<T = number> implements ITreapMultiSet<T> {
private readonly root: TreapNode<T>;
private readonly compareFn: CompareFunction<T, 'number'>;
private readonly leftBound: T;
private readonly rightBound: T;
constructor(compareFn?: CompareFunction<T, 'number'>);
constructor(compareFn: CompareFunction<T, 'number'>, leftBound: T, rightBound: T);
constructor(
compareFn: CompareFunction<T, any> = (a: any, b: any) => a - b,
leftBound: any = -Infinity,
rightBound: any = Infinity,
) {
this.root = new TreapNode<T>(rightBound);
this.root.priority = Infinity;
this.root.left = new TreapNode<T>(leftBound);
this.root.left.priority = -Infinity;
this.root.pushUp();
this.leftBound = leftBound;
this.rightBound = rightBound;
this.compareFn = compareFn;
}
get size(): number {
return this.root.size - 2;
}
get height(): number {
const getHeight = (node: TreapNode<T> | null): number => {
if (node == null) return 0;
return 1 + Math.max(getHeight(node.left), getHeight(node.right));
};
return getHeight(this.root);
}
/**
*
* @complexity `O(logn)`
* @description Returns true if value is a member.
*/
has(value: T): boolean {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): boolean => {
if (node == null) return false;
if (compare(node.value, value) === 0) return true;
if (compare(node.value, value) < 0) return dfs(node.right, value);
return dfs(node.left, value);
};
return dfs(this.root, value);
}
/**
*
* @complexity `O(logn)`
* @description Add value to sorted set.
*/
add(...values: T[]): this {
const compare = this.compareFn;
const dfs = (
node: TreapNode<T> | null,
value: T,
parent: TreapNode<T>,
direction: 'left' | 'right',
): void => {
if (node == null) return;
if (compare(node.value, value) === 0) {
node.count++;
node.pushUp();
} else if (compare(node.value, value) > 0) {
if (node.left) {
dfs(node.left, value, node, 'left');
} else {
node.left = new TreapNode(value);
node.pushUp();
}
if (TreapNode.getFac(node.left) > node.priority) {
parent[direction] = node.rotateRight();
}
} else if (compare(node.value, value) < 0) {
if (node.right) {
dfs(node.right, value, node, 'right');
} else {
node.right = new TreapNode(value);
node.pushUp();
}
if (TreapNode.getFac(node.right) > node.priority) {
parent[direction] = node.rotateLeft();
}
}
parent.pushUp();
};
values.forEach(value => dfs(this.root.left, value, this.root, 'left'));
return this;
}
/**
*
* @complexity `O(logn)`
* @description Remove value from sorted set if it is a member.
* If value is not a member, do nothing.
*/
delete(value: T): void {
const compare = this.compareFn;
const dfs = (
node: TreapNode<T> | null,
value: T,
parent: TreapNode<T>,
direction: 'left' | 'right',
): void => {
if (node == null) return;
if (compare(node.value, value) === 0) {
if (node.count > 1) {
node.count--;
node?.pushUp();
} else if (node.left == null && node.right == null) {
parent[direction] = null;
} else {
// 旋到根节点
if (
node.right == null ||
TreapNode.getFac(node.left) > TreapNode.getFac(node.right)
) {
parent[direction] = node.rotateRight();
dfs(parent[direction]?.right ?? null, value, parent[direction]!, 'right');
} else {
parent[direction] = node.rotateLeft();
dfs(parent[direction]?.left ?? null, value, parent[direction]!, 'left');
}
}
} else if (compare(node.value, value) > 0) {
dfs(node.left, value, node, 'left');
} else if (compare(node.value, value) < 0) {
dfs(node.right, value, node, 'right');
}
parent?.pushUp();
};
dfs(this.root.left, value, this.root, 'left');
}
/**
*
* @complexity `O(logn)`
* @description Returns an index to insert value in the sorted set.
* If the value is already present, the insertion point will be before (to the left of) any existing values.
*/
bisectLeft(value: T): number {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): number => {
if (node == null) return 0;
if (compare(node.value, value) === 0) {
return TreapNode.getSize(node.left);
} else if (compare(node.value, value) > 0) {
return dfs(node.left, value);
} else if (compare(node.value, value) < 0) {
return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count;
}
return 0;
};
return dfs(this.root, value) - 1;
}
/**
*
* @complexity `O(logn)`
* @description Returns an index to insert value in the sorted set.
* If the value is already present, the insertion point will be before (to the right of) any existing values.
*/
bisectRight(value: T): number {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): number => {
if (node == null) return 0;
if (compare(node.value, value) === 0) {
return TreapNode.getSize(node.left) + node.count;
} else if (compare(node.value, value) > 0) {
return dfs(node.left, value);
} else if (compare(node.value, value) < 0) {
return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count;
}
return 0;
};
return dfs(this.root, value) - 1;
}
/**
*
* @complexity `O(logn)`
* @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present.
*/
indexOf(value: T): number {
const compare = this.compareFn;
let isExist = false;
const dfs = (node: TreapNode<T> | null, value: T): number => {
if (node == null) return 0;
if (compare(node.value, value) === 0) {
isExist = true;
return TreapNode.getSize(node.left);
} else if (compare(node.value, value) > 0) {
return dfs(node.left, value);
} else if (compare(node.value, value) < 0) {
return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count;
}
return 0;
};
const res = dfs(this.root, value) - 1;
return isExist ? res : -1;
}
/**
*
* @complexity `O(logn)`
* @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present.
*/
lastIndexOf(value: T): number {
const compare = this.compareFn;
let isExist = false;
const dfs = (node: TreapNode<T> | null, value: T): number => {
if (node == null) return 0;
if (compare(node.value, value) === 0) {
isExist = true;
return TreapNode.getSize(node.left) + node.count - 1;
} else if (compare(node.value, value) > 0) {
return dfs(node.left, value);
} else if (compare(node.value, value) < 0) {
return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count;
}
return 0;
};
const res = dfs(this.root, value) - 1;
return isExist ? res : -1;
}
/**
*
* @complexity `O(logn)`
* @description Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined {
if (index < 0) index += this.size;
if (index < 0 || index >= this.size) return undefined;
const dfs = (node: TreapNode<T> | null, rank: number): T | undefined => {
if (node == null) return undefined;
if (TreapNode.getSize(node.left) >= rank) {
return dfs(node.left, rank);
} else if (TreapNode.getSize(node.left) + node.count >= rank) {
return node.value;
} else {
return dfs(node.right, rank - TreapNode.getSize(node.left) - node.count);
}
};
const res = dfs(this.root, index + 2);
return ([this.leftBound, this.rightBound] as any[]).includes(res) ? undefined : res;
}
/**
*
* @complexity `O(logn)`
* @description Find and return the element less than `val`, return `undefined` if no such element found.
*/
lower(value: T): T | undefined {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): T | undefined => {
if (node == null) return undefined;
if (compare(node.value, value) >= 0) return dfs(node.left, value);
const tmp = dfs(node.right, value);
if (tmp == null || compare(node.value, tmp) > 0) {
return node.value;
} else {
return tmp;
}
};
const res = dfs(this.root, value) as any;
return res === this.leftBound ? undefined : res;
}
/**
*
* @complexity `O(logn)`
* @description Find and return the element greater than `val`, return `undefined` if no such element found.
*/
higher(value: T): T | undefined {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): T | undefined => {
if (node == null) return undefined;
if (compare(node.value, value) <= 0) return dfs(node.right, value);
const tmp = dfs(node.left, value);
if (tmp == null || compare(node.value, tmp) < 0) {
return node.value;
} else {
return tmp;
}
};
const res = dfs(this.root, value) as any;
return res === this.rightBound ? undefined : res;
}
/**
*
* @complexity `O(logn)`
* @description Find and return the element less than or equal to `val`, return `undefined` if no such element found.
*/
floor(value: T): T | undefined {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): T | undefined => {
if (node == null) return undefined;
if (compare(node.value, value) === 0) return node.value;
if (compare(node.value, value) >= 0) return dfs(node.left, value);
const tmp = dfs(node.right, value);
if (tmp == null || compare(node.value, tmp) > 0) {
return node.value;
} else {
return tmp;
}
};
const res = dfs(this.root, value) as any;
return res === this.leftBound ? undefined : res;
}
/**
*
* @complexity `O(logn)`
* @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found.
*/
ceil(value: T): T | undefined {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): T | undefined => {
if (node == null) return undefined;
if (compare(node.value, value) === 0) return node.value;
if (compare(node.value, value) <= 0) return dfs(node.right, value);
const tmp = dfs(node.left, value);
if (tmp == null || compare(node.value, tmp) < 0) {
return node.value;
} else {
return tmp;
}
};
const res = dfs(this.root, value) as any;
return res === this.rightBound ? undefined : res;
}
/**
* @complexity `O(logn)`
* @description
* Returns the last element from set.
* If the set is empty, undefined is returned.
*/
first(): T | undefined {
const iter = this.inOrder();
iter.next();
const res = iter.next().value;
return res === this.rightBound ? undefined : res;
}
/**
* @complexity `O(logn)`
* @description
* Returns the last element from set.
* If the set is empty, undefined is returned .
*/
last(): T | undefined {
const iter = this.reverseInOrder();
iter.next();
const res = iter.next().value;
return res === this.leftBound ? undefined : res;
}
/**
* @complexity `O(logn)`
* @description
* Removes the first element from an set and returns it.
* If the set is empty, undefined is returned and the set is not modified.
*/
shift(): T | undefined {
const first = this.first();
if (first === undefined) return undefined;
this.delete(first);
return first;
}
/**
* @complexity `O(logn)`
* @description
* Removes the last element from an set and returns it.
* If the set is empty, undefined is returned and the set is not modified.
*/
pop(index?: number): T | undefined {
if (index == null) {
const last = this.last();
if (last === undefined) return undefined;
this.delete(last);
return last;
}
const toDelete = this.at(index);
if (toDelete == null) return;
this.delete(toDelete);
return toDelete;
}
/**
*
* @complexity `O(logn)`
* @description
* Returns number of occurrences of value in the sorted set.
*/
count(value: T): number {
const compare = this.compareFn;
const dfs = (node: TreapNode<T> | null, value: T): number => {
if (node == null) return 0;
if (compare(node.value, value) === 0) return node.count;
if (compare(node.value, value) < 0) return dfs(node.right, value);
return dfs(node.left, value);
};
return dfs(this.root, value);
}
*[Symbol.iterator](): Generator<T, any, any> {
yield* this.values();
}
/**
* @description
* Returns an iterable of keys in the set.
*/
*keys(): Generator<T, any, any> {
yield* this.values();
}
/**
* @description
* Returns an iterable of values in the set.
*/
*values(): Generator<T, any, any> {
const iter = this.inOrder();
iter.next();
const steps = this.size;
for (let _ = 0; _ < steps; _++) {
yield iter.next().value;
}
}
/**
* @description
* Returns a generator for reversed order traversing the set.
*/
*rvalues(): Generator<T, any, any> {
const iter = this.reverseInOrder();
iter.next();
const steps = this.size;
for (let _ = 0; _ < steps; _++) {
yield iter.next().value;
}
}
/**
* @description
* Returns an iterable of key, value pairs for every entry in the set.
*/
*entries(): IterableIterator<[number, T]> {
const iter = this.inOrder();
iter.next();
const steps = this.size;
for (let i = 0; i < steps; i++) {
yield [i, iter.next().value];
}
}
private *inOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> {
if (root == null) return;
yield* this.inOrder(root.left);
const count = root.count;
for (let _ = 0; _ < count; _++) {
yield root.value;
}
yield* this.inOrder(root.right);
}
private *reverseInOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> {
if (root == null) return;
yield* this.reverseInOrder(root.right);
const count = root.count;
for (let _ = 0; _ < count; _++) {
yield root.value;
}
yield* this.reverseInOrder(root.left);
}
}
|
3,103
|
Find Trending Hashtags II
|
Hard
|
<p>Table: <code>Tweets</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| tweet_id | int |
| tweet_date | date |
| tweet | varchar |
+-------------+---------+
tweet_id is the primary key (column with unique values) for this table.
Each row of this table contains user_id, tweet_id, tweet_date and tweet.
It is guaranteed that all tweet_date are valid dates in February 2024.
</pre>
<p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong> in <strong>February</strong> <code>2024</code>. Every tweet may contain <strong>several</strong> <strong>hashtags</strong>.</p>
<p>Return <em>the result table ordered by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Tweets table:</p>
<pre class="example-io">
+---------+----------+------------------------------------------------------------+------------+
| user_id | tweet_id | tweet | tweet_date |
+---------+----------+------------------------------------------------------------+------------+
| 135 | 13 | Enjoying a great start to the day. #HappyDay #MorningVibes | 2024-02-01 |
| 136 | 14 | Another #HappyDay with good vibes! #FeelGood | 2024-02-03 |
| 137 | 15 | Productivity peaks! #WorkLife #ProductiveDay | 2024-02-04 |
| 138 | 16 | Exploring new tech frontiers. #TechLife #Innovation | 2024-02-04 |
| 139 | 17 | Gratitude for today's moments. #HappyDay #Thankful | 2024-02-05 |
| 140 | 18 | Innovation drives us. #TechLife #FutureTech | 2024-02-07 |
| 141 | 19 | Connecting with nature's serenity. #Nature #Peaceful | 2024-02-09 |
+---------+----------+------------------------------------------------------------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-------+
| hashtag | count |
+-----------+-------+
| #HappyDay | 3 |
| #TechLife | 2 |
| #WorkLife | 1 |
+-----------+-------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li>
<li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li>
<li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li>
</ul>
<p><b>Note:</b> Output table is sorted in descending order by count and hashtag respectively.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def find_trending_hashtags(tweets: pd.DataFrame) -> pd.DataFrame:
# Filter tweets for February 2024
tweets_feb_2024 = tweets[tweets["tweet_date"].between("2024-02-01", "2024-02-29")]
# Extract hashtags from tweets
hashtags = tweets_feb_2024["tweet"].str.findall(r"#\w+")
# Flatten list of hashtags
all_hashtags = [tag for sublist in hashtags for tag in sublist]
# Count occurrences of each hashtag
hashtag_counts = pd.Series(all_hashtags).value_counts().reset_index()
hashtag_counts.columns = ["hashtag", "count"]
# Sort by count of hashtag in descending order
hashtag_counts = hashtag_counts.sort_values(
by=["count", "hashtag"], ascending=[False, False]
)
# Get top 3 trending hashtags
top_3_hashtags = hashtag_counts.head(3)
return top_3_hashtags
|
3,104
|
Find Longest Self-Contained Substring
|
Hard
|
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p>
<p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn't exist in the <em>rest</em> of <code>s</code>.</p>
<p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"bb"</code>. You can see that no other <code>"b"</code> is outside of this substring. Hence the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abab"</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abacd"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"<span class="example-io">abac</span>"</code>. There is only one character outside of this substring and that is <code>"d"</code>. There is no <code>"d"</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Prefix Sum
|
C++
|
class Solution {
public:
int maxSubstringLength(string s) {
vector<int> first(26, -1);
vector<int> last(26);
int n = s.length();
for (int i = 0; i < n; ++i) {
int j = s[i] - 'a';
if (first[j] == -1) {
first[j] = i;
}
last[j] = i;
}
int ans = -1;
for (int k = 0; k < 26; ++k) {
int i = first[k];
if (i == -1) {
continue;
}
int mx = last[k];
for (int j = i; j < n; ++j) {
int a = first[s[j] - 'a'];
int b = last[s[j] - 'a'];
if (a < i) {
break;
}
mx = max(mx, b);
if (mx == j && j - i + 1 < n) {
ans = max(ans, j - i + 1);
}
}
}
return ans;
}
};
|
3,104
|
Find Longest Self-Contained Substring
|
Hard
|
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p>
<p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn't exist in the <em>rest</em> of <code>s</code>.</p>
<p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"bb"</code>. You can see that no other <code>"b"</code> is outside of this substring. Hence the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abab"</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abacd"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"<span class="example-io">abac</span>"</code>. There is only one character outside of this substring and that is <code>"d"</code>. There is no <code>"d"</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Prefix Sum
|
Go
|
func maxSubstringLength(s string) int {
first := [26]int{}
last := [26]int{}
for i := range first {
first[i] = -1
}
n := len(s)
for i, c := range s {
j := int(c - 'a')
if first[j] == -1 {
first[j] = i
}
last[j] = i
}
ans := -1
for k := 0; k < 26; k++ {
i := first[k]
if i == -1 {
continue
}
mx := last[k]
for j := i; j < n; j++ {
a, b := first[s[j]-'a'], last[s[j]-'a']
if a < i {
break
}
mx = max(mx, b)
if mx == j && j-i+1 < n {
ans = max(ans, j-i+1)
}
}
}
return ans
}
|
3,104
|
Find Longest Self-Contained Substring
|
Hard
|
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p>
<p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn't exist in the <em>rest</em> of <code>s</code>.</p>
<p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"bb"</code>. You can see that no other <code>"b"</code> is outside of this substring. Hence the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abab"</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abacd"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"<span class="example-io">abac</span>"</code>. There is only one character outside of this substring and that is <code>"d"</code>. There is no <code>"d"</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Prefix Sum
|
Java
|
class Solution {
public int maxSubstringLength(String s) {
int[] first = new int[26];
int[] last = new int[26];
Arrays.fill(first, -1);
int n = s.length();
for (int i = 0; i < n; ++i) {
int j = s.charAt(i) - 'a';
if (first[j] == -1) {
first[j] = i;
}
last[j] = i;
}
int ans = -1;
for (int k = 0; k < 26; ++k) {
int i = first[k];
if (i == -1) {
continue;
}
int mx = last[k];
for (int j = i; j < n; ++j) {
int a = first[s.charAt(j) - 'a'];
int b = last[s.charAt(j) - 'a'];
if (a < i) {
break;
}
mx = Math.max(mx, b);
if (mx == j && j - i + 1 < n) {
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
}
|
3,104
|
Find Longest Self-Contained Substring
|
Hard
|
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p>
<p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn't exist in the <em>rest</em> of <code>s</code>.</p>
<p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"bb"</code>. You can see that no other <code>"b"</code> is outside of this substring. Hence the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abab"</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abacd"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"<span class="example-io">abac</span>"</code>. There is only one character outside of this substring and that is <code>"d"</code>. There is no <code>"d"</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Prefix Sum
|
Python
|
class Solution:
def maxSubstringLength(self, s: str) -> int:
first, last = {}, {}
for i, c in enumerate(s):
if c not in first:
first[c] = i
last[c] = i
ans, n = -1, len(s)
for c, i in first.items():
mx = last[c]
for j in range(i, n):
a, b = first[s[j]], last[s[j]]
if a < i:
break
mx = max(mx, b)
if mx == j and j - i + 1 < n:
ans = max(ans, j - i + 1)
return ans
|
3,104
|
Find Longest Self-Contained Substring
|
Hard
|
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p>
<p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn't exist in the <em>rest</em> of <code>s</code>.</p>
<p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abba"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"bb"</code>. You can see that no other <code>"b"</code> is outside of this substring. Hence the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abab"</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abacd"</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong><br />
Let's check the substring <code>"<span class="example-io">abac</span>"</code>. There is only one character outside of this substring and that is <code>"d"</code>. There is no <code>"d"</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Binary Search; Prefix Sum
|
TypeScript
|
function maxSubstringLength(s: string): number {
const first: number[] = Array(26).fill(-1);
const last: number[] = Array(26).fill(0);
const n = s.length;
for (let i = 0; i < n; ++i) {
const j = s.charCodeAt(i) - 97;
if (first[j] === -1) {
first[j] = i;
}
last[j] = i;
}
let ans = -1;
for (let k = 0; k < 26; ++k) {
const i = first[k];
if (i === -1) {
continue;
}
let mx = last[k];
for (let j = i; j < n; ++j) {
const a = first[s.charCodeAt(j) - 97];
if (a < i) {
break;
}
const b = last[s.charCodeAt(j) - 97];
mx = Math.max(mx, b);
if (mx === j && j - i + 1 < n) {
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int longestMonotonicSubarray(vector<int>& nums) {
int ans = 1;
for (int i = 1, t = 1; i < nums.size(); ++i) {
if (nums[i - 1] < nums[i]) {
ans = max(ans, ++t);
} else {
t = 1;
}
}
for (int i = 1, t = 1; i < nums.size(); ++i) {
if (nums[i - 1] > nums[i]) {
ans = max(ans, ++t);
} else {
t = 1;
}
}
return ans;
}
};
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Go
|
func longestMonotonicSubarray(nums []int) int {
ans := 1
t := 1
for i, x := range nums[1:] {
if nums[i] < x {
t++
ans = max(ans, t)
} else {
t = 1
}
}
t = 1
for i, x := range nums[1:] {
if nums[i] > x {
t++
ans = max(ans, t)
} else {
t = 1
}
}
return ans
}
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int longestMonotonicSubarray(int[] nums) {
int ans = 1;
for (int i = 1, t = 1; i < nums.length; ++i) {
if (nums[i - 1] < nums[i]) {
ans = Math.max(ans, ++t);
} else {
t = 1;
}
}
for (int i = 1, t = 1; i < nums.length; ++i) {
if (nums[i - 1] > nums[i]) {
ans = Math.max(ans, ++t);
} else {
t = 1;
}
}
return ans;
}
}
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
JavaScript
|
function longestMonotonicSubarray(nums) {
const n = nums.length;
let ans = 1;
for (let i = 1, t1 = 1, t2 = 1; i < n; i++) {
t1 = nums[i] > nums[i - 1] ? t1 + 1 : 1;
t2 = nums[i] < nums[i - 1] ? t2 + 1 : 1;
ans = Math.max(ans, t1, t2);
}
return ans;
}
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
Python
|
class Solution:
def longestMonotonicSubarray(self, nums: List[int]) -> int:
ans = t = 1
for i, x in enumerate(nums[1:]):
if nums[i] < x:
t += 1
ans = max(ans, t)
else:
t = 1
t = 1
for i, x in enumerate(nums[1:]):
if nums[i] > x:
t += 1
ans = max(ans, t)
else:
t = 1
return ans
|
3,105
|
Longest Strictly Increasing or Strictly Decreasing Subarray
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p>
<p>Hence, we return <code>2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p>
<p>Hence, we return <code>1</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p>
<p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p>
<p>Hence, we return <code>3</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 50</code></li>
<li><code>1 <= nums[i] <= 50</code></li>
</ul>
|
Array
|
TypeScript
|
function longestMonotonicSubarray(nums: number[]): number {
const n = nums.length;
let ans = 1;
for (let i = 1, t1 = 1, t2 = 1; i < n; i++) {
t1 = nums[i] > nums[i - 1] ? t1 + 1 : 1;
t2 = nums[i] < nums[i - 1] ? t2 + 1 : 1;
ans = Math.max(ans, t1, t2);
}
return ans;
}
|
3,106
|
Lexicographically Smallest String After Operations With Constraint
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p>
<ul>
<li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>'a'</code> to <code>'z'</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li>
</ul>
<p>For example, <code>distance("ab", "cd") == 4</code>, and <code>distance("a", "z") == 1</code>.</p>
<p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p>
<p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) <= k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zbbz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaaz"</span></p>
<p><strong>Explanation:</strong></p>
<p>Change <code>s</code> to <code>"aaaz"</code>. The distance between <code>"zbbz"</code> and <code>"aaaz"</code> is equal to <code>k = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xaxcd", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"aawcd"</span></p>
<p><strong>Explanation:</strong></p>
<p>The distance between "xaxcd" and "aawcd" is equal to k = 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "lol", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">"lol"</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to change any character as <code>k = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>0 <= k <= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String
|
C++
|
class Solution {
public:
string getSmallestString(string s, int k) {
for (int i = 0; i < s.size(); ++i) {
char c1 = s[i];
for (char c2 = 'a'; c2 < c1; ++c2) {
int d = min(c1 - c2, 26 - c1 + c2);
if (d <= k) {
s[i] = c2;
k -= d;
break;
}
}
}
return s;
}
};
|
3,106
|
Lexicographically Smallest String After Operations With Constraint
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p>
<ul>
<li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>'a'</code> to <code>'z'</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li>
</ul>
<p>For example, <code>distance("ab", "cd") == 4</code>, and <code>distance("a", "z") == 1</code>.</p>
<p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p>
<p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) <= k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zbbz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaaz"</span></p>
<p><strong>Explanation:</strong></p>
<p>Change <code>s</code> to <code>"aaaz"</code>. The distance between <code>"zbbz"</code> and <code>"aaaz"</code> is equal to <code>k = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xaxcd", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"aawcd"</span></p>
<p><strong>Explanation:</strong></p>
<p>The distance between "xaxcd" and "aawcd" is equal to k = 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "lol", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">"lol"</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to change any character as <code>k = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>0 <= k <= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String
|
Go
|
func getSmallestString(s string, k int) string {
cs := []byte(s)
for i, c1 := range cs {
for c2 := byte('a'); c2 < c1; c2++ {
d := int(min(c1-c2, 26-c1+c2))
if d <= k {
cs[i] = c2
k -= d
break
}
}
}
return string(cs)
}
|
3,106
|
Lexicographically Smallest String After Operations With Constraint
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p>
<ul>
<li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>'a'</code> to <code>'z'</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li>
</ul>
<p>For example, <code>distance("ab", "cd") == 4</code>, and <code>distance("a", "z") == 1</code>.</p>
<p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p>
<p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) <= k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zbbz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaaz"</span></p>
<p><strong>Explanation:</strong></p>
<p>Change <code>s</code> to <code>"aaaz"</code>. The distance between <code>"zbbz"</code> and <code>"aaaz"</code> is equal to <code>k = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xaxcd", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"aawcd"</span></p>
<p><strong>Explanation:</strong></p>
<p>The distance between "xaxcd" and "aawcd" is equal to k = 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "lol", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">"lol"</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to change any character as <code>k = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>0 <= k <= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String
|
Java
|
class Solution {
public String getSmallestString(String s, int k) {
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; ++i) {
char c1 = cs[i];
for (char c2 = 'a'; c2 < c1; ++c2) {
int d = Math.min(c1 - c2, 26 - c1 + c2);
if (d <= k) {
cs[i] = c2;
k -= d;
break;
}
}
}
return new String(cs);
}
}
|
3,106
|
Lexicographically Smallest String After Operations With Constraint
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p>
<ul>
<li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>'a'</code> to <code>'z'</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li>
</ul>
<p>For example, <code>distance("ab", "cd") == 4</code>, and <code>distance("a", "z") == 1</code>.</p>
<p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p>
<p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) <= k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zbbz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaaz"</span></p>
<p><strong>Explanation:</strong></p>
<p>Change <code>s</code> to <code>"aaaz"</code>. The distance between <code>"zbbz"</code> and <code>"aaaz"</code> is equal to <code>k = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xaxcd", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"aawcd"</span></p>
<p><strong>Explanation:</strong></p>
<p>The distance between "xaxcd" and "aawcd" is equal to k = 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "lol", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">"lol"</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to change any character as <code>k = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>0 <= k <= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String
|
Python
|
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
cs = list(s)
for i, c1 in enumerate(s):
for c2 in ascii_lowercase:
if c2 >= c1:
break
d = min(ord(c1) - ord(c2), 26 - ord(c1) + ord(c2))
if d <= k:
cs[i] = c2
k -= d
break
return "".join(cs)
|
3,106
|
Lexicographically Smallest String After Operations With Constraint
|
Medium
|
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p>
<p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p>
<ul>
<li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>'a'</code> to <code>'z'</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li>
</ul>
<p>For example, <code>distance("ab", "cd") == 4</code>, and <code>distance("a", "z") == 1</code>.</p>
<p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p>
<p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) <= k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zbbz", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaaz"</span></p>
<p><strong>Explanation:</strong></p>
<p>Change <code>s</code> to <code>"aaaz"</code>. The distance between <code>"zbbz"</code> and <code>"aaaz"</code> is equal to <code>k = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "xaxcd", k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"aawcd"</span></p>
<p><strong>Explanation:</strong></p>
<p>The distance between "xaxcd" and "aawcd" is equal to k = 4.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "lol", k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">"lol"</span></p>
<p><strong>Explanation:</strong></p>
<p>It's impossible to change any character as <code>k = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>0 <= k <= 2000</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; String
|
TypeScript
|
function getSmallestString(s: string, k: number): string {
const cs: string[] = s.split('');
for (let i = 0; i < s.length; ++i) {
for (let j = 97; j < s[i].charCodeAt(0); ++j) {
const d = Math.min(s[i].charCodeAt(0) - j, 26 - s[i].charCodeAt(0) + j);
if (d <= k) {
cs[i] = String.fromCharCode(j);
k -= d;
break;
}
}
}
return cs.join('');
}
|
3,107
|
Minimum Operations to Make Median of Array Equal to K
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p>
<p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The median of the array is already equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
long long minOperationsToMakeMedianK(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
int m = n >> 1;
long long ans = abs(nums[m] - k);
if (nums[m] > k) {
for (int i = m - 1; i >= 0 && nums[i] > k; --i) {
ans += nums[i] - k;
}
} else {
for (int i = m + 1; i < n && nums[i] < k; ++i) {
ans += k - nums[i];
}
}
return ans;
}
};
|
3,107
|
Minimum Operations to Make Median of Array Equal to K
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p>
<p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The median of the array is already equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func minOperationsToMakeMedianK(nums []int, k int) (ans int64) {
sort.Ints(nums)
n := len(nums)
m := n >> 1
ans = int64(abs(nums[m] - k))
if nums[m] > k {
for i := m - 1; i >= 0 && nums[i] > k; i-- {
ans += int64(nums[i] - k)
}
} else {
for i := m + 1; i < n && nums[i] < k; i++ {
ans += int64(k - nums[i])
}
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,107
|
Minimum Operations to Make Median of Array Equal to K
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p>
<p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The median of the array is already equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public long minOperationsToMakeMedianK(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
int m = n >> 1;
long ans = Math.abs(nums[m] - k);
if (nums[m] > k) {
for (int i = m - 1; i >= 0 && nums[i] > k; --i) {
ans += nums[i] - k;
}
} else {
for (int i = m + 1; i < n && nums[i] < k; ++i) {
ans += k - nums[i];
}
}
return ans;
}
}
|
3,107
|
Minimum Operations to Make Median of Array Equal to K
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p>
<p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The median of the array is already equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int:
nums.sort()
n = len(nums)
m = n >> 1
ans = abs(nums[m] - k)
if nums[m] > k:
for i in range(m - 1, -1, -1):
if nums[i] <= k:
break
ans += nums[i] - k
else:
for i in range(m + 1, n):
if nums[i] >= k:
break
ans += k - nums[i]
return ans
|
3,107
|
Minimum Operations to Make Median of Array Equal to K
|
Medium
|
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p>
<p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The median of the array is already equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function minOperationsToMakeMedianK(nums: number[], k: number): number {
nums.sort((a, b) => a - b);
const n = nums.length;
const m = n >> 1;
let ans = Math.abs(nums[m] - k);
if (nums[m] > k) {
for (let i = m - 1; i >= 0 && nums[i] > k; --i) {
ans += nums[i] - k;
}
} else {
for (let i = m + 1; i < n && nums[i] < k; ++i) {
ans += k - nums[i];
}
}
return ans;
}
|
3,108
|
Minimum Cost Walk in Weighted Graph
|
Hard
|
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p>
<p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.</p>
<p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> & w<sub>1</sub> & w<sub>2</sub> & ... & w<sub>k</sub></code>, where <code>&</code> denotes the bitwise <code>AND</code> operator.</p>
<p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p>
<p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" />
<p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0->1</code> (weight 7), <code>1->2</code> (weight 1), <code>2->1</code> (weight 1), <code>1->3</code> (weight 7).</p>
<p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p>
<p><strong class="example">Example 2:</strong></p>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" />
<p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1->2</code> (weight 1), <code>2->1</code> (weight 6), <code>1->2</code> (weight 1).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>
<li><code>0 <= w<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>1 <= query.length <= 10<sup>5</sup></code></li>
<li><code>query[i].length == 2</code></li>
<li><code>0 <= s<sub>i</sub>, t<sub>i</sub> <= n - 1</code></li>
<li><code>s<sub>i</sub> != t<sub>i</sub></code></li>
</ul>
|
Bit Manipulation; Union Find; Graph; Array
|
C++
|
class UnionFind {
public:
UnionFind(int n) {
p = vector<int>(n);
size = vector<int>(n, 1);
iota(p.begin(), p.end(), 0);
}
bool unite(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
int getSize(int x) {
return size[find(x)];
}
private:
vector<int> p, size;
};
class Solution {
public:
vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
g = vector<int>(n, -1);
uf = new UnionFind(n);
for (auto& e : edges) {
uf->unite(e[0], e[1]);
}
for (auto& e : edges) {
int root = uf->find(e[0]);
g[root] &= e[2];
}
vector<int> ans;
for (auto& q : query) {
ans.push_back(f(q[0], q[1]));
}
return ans;
}
private:
UnionFind* uf;
vector<int> g;
int f(int u, int v) {
if (u == v) {
return 0;
}
int a = uf->find(u), b = uf->find(v);
return a == b ? g[a] : -1;
}
};
|
3,108
|
Minimum Cost Walk in Weighted Graph
|
Hard
|
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p>
<p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.</p>
<p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> & w<sub>1</sub> & w<sub>2</sub> & ... & w<sub>k</sub></code>, where <code>&</code> denotes the bitwise <code>AND</code> operator.</p>
<p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p>
<p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" />
<p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0->1</code> (weight 7), <code>1->2</code> (weight 1), <code>2->1</code> (weight 1), <code>1->3</code> (weight 7).</p>
<p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p>
<p><strong class="example">Example 2:</strong></p>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" />
<p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1->2</code> (weight 1), <code>2->1</code> (weight 6), <code>1->2</code> (weight 1).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>
<li><code>0 <= w<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>1 <= query.length <= 10<sup>5</sup></code></li>
<li><code>query[i].length == 2</code></li>
<li><code>0 <= s<sub>i</sub>, t<sub>i</sub> <= n - 1</code></li>
<li><code>s<sub>i</sub> != t<sub>i</sub></code></li>
</ul>
|
Bit Manipulation; Union Find; Graph; Array
|
Go
|
type unionFind struct {
p, size []int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a), uf.find(b)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
return true
}
func (uf *unionFind) getSize(x int) int {
return uf.size[uf.find(x)]
}
func minimumCost(n int, edges [][]int, query [][]int) (ans []int) {
uf := newUnionFind(n)
g := make([]int, n)
for i := range g {
g[i] = -1
}
for _, e := range edges {
uf.union(e[0], e[1])
}
for _, e := range edges {
root := uf.find(e[0])
g[root] &= e[2]
}
f := func(u, v int) int {
if u == v {
return 0
}
a, b := uf.find(u), uf.find(v)
if a == b {
return g[a]
}
return -1
}
for _, q := range query {
ans = append(ans, f(q[0], q[1]))
}
return
}
|
3,108
|
Minimum Cost Walk in Weighted Graph
|
Hard
|
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p>
<p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.</p>
<p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> & w<sub>1</sub> & w<sub>2</sub> & ... & w<sub>k</sub></code>, where <code>&</code> denotes the bitwise <code>AND</code> operator.</p>
<p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p>
<p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" />
<p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0->1</code> (weight 7), <code>1->2</code> (weight 1), <code>2->1</code> (weight 1), <code>1->3</code> (weight 7).</p>
<p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p>
<p><strong class="example">Example 2:</strong></p>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" />
<p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1->2</code> (weight 1), <code>2->1</code> (weight 6), <code>1->2</code> (weight 1).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>
<li><code>0 <= w<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>1 <= query.length <= 10<sup>5</sup></code></li>
<li><code>query[i].length == 2</code></li>
<li><code>0 <= s<sub>i</sub>, t<sub>i</sub> <= n - 1</code></li>
<li><code>s<sub>i</sub> != t<sub>i</sub></code></li>
</ul>
|
Bit Manipulation; Union Find; Graph; Array
|
Java
|
class UnionFind {
private final int[] p;
private final int[] size;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
public int size(int x) {
return size[find(x)];
}
}
class Solution {
private UnionFind uf;
private int[] g;
public int[] minimumCost(int n, int[][] edges, int[][] query) {
uf = new UnionFind(n);
for (var e : edges) {
uf.union(e[0], e[1]);
}
g = new int[n];
Arrays.fill(g, -1);
for (var e : edges) {
int root = uf.find(e[0]);
g[root] &= e[2];
}
int m = query.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int s = query[i][0], t = query[i][1];
ans[i] = f(s, t);
}
return ans;
}
private int f(int u, int v) {
if (u == v) {
return 0;
}
int a = uf.find(u), b = uf.find(v);
return a == b ? g[a] : -1;
}
}
|
3,108
|
Minimum Cost Walk in Weighted Graph
|
Hard
|
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p>
<p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.</p>
<p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> & w<sub>1</sub> & w<sub>2</sub> & ... & w<sub>k</sub></code>, where <code>&</code> denotes the bitwise <code>AND</code> operator.</p>
<p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p>
<p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" />
<p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0->1</code> (weight 7), <code>1->2</code> (weight 1), <code>2->1</code> (weight 1), <code>1->3</code> (weight 7).</p>
<p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p>
<p><strong class="example">Example 2:</strong></p>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" />
<p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1->2</code> (weight 1), <code>2->1</code> (weight 6), <code>1->2</code> (weight 1).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>
<li><code>0 <= w<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>1 <= query.length <= 10<sup>5</sup></code></li>
<li><code>query[i].length == 2</code></li>
<li><code>0 <= s<sub>i</sub>, t<sub>i</sub> <= n - 1</code></li>
<li><code>s<sub>i</sub> != t<sub>i</sub></code></li>
</ul>
|
Bit Manipulation; Union Find; Graph; Array
|
Python
|
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def minimumCost(
self, n: int, edges: List[List[int]], query: List[List[int]]
) -> List[int]:
g = [-1] * n
uf = UnionFind(n)
for u, v, _ in edges:
uf.union(u, v)
for u, _, w in edges:
root = uf.find(u)
g[root] &= w
def f(u: int, v: int) -> int:
if u == v:
return 0
a, b = uf.find(u), uf.find(v)
return g[a] if a == b else -1
return [f(s, t) for s, t in query]
|
3,108
|
Minimum Cost Walk in Weighted Graph
|
Hard
|
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p>
<p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p>
<p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.</p>
<p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> & w<sub>1</sub> & w<sub>2</sub> & ... & w<sub>k</sub></code>, where <code>&</code> denotes the bitwise <code>AND</code> operator.</p>
<p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p>
<p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" />
<p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0->1</code> (weight 7), <code>1->2</code> (weight 1), <code>2->1</code> (weight 1), <code>1->3</code> (weight 7).</p>
<p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p>
<p><strong class="example">Example 2:</strong></p>
</div>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0]</span></p>
<p><strong>Explanation:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" />
<p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1->2</code> (weight 1), <code>2->1</code> (weight 6), <code>1->2</code> (weight 1).</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i].length == 3</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>
<li><code>0 <= w<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>1 <= query.length <= 10<sup>5</sup></code></li>
<li><code>query[i].length == 2</code></li>
<li><code>0 <= s<sub>i</sub>, t<sub>i</sub> <= n - 1</code></li>
<li><code>s<sub>i</sub> != t<sub>i</sub></code></li>
</ul>
|
Bit Manipulation; Union Find; Graph; Array
|
TypeScript
|
class UnionFind {
p: number[];
size: number[];
constructor(n: number) {
this.p = Array(n)
.fill(0)
.map((_, i) => i);
this.size = Array(n).fill(1);
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
const [pa, pb] = [this.find(a), this.find(b)];
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
getSize(x: number): number {
return this.size[this.find(x)];
}
}
function minimumCost(n: number, edges: number[][], query: number[][]): number[] {
const uf = new UnionFind(n);
const g: number[] = Array(n).fill(-1);
for (const [u, v, _] of edges) {
uf.union(u, v);
}
for (const [u, _, w] of edges) {
const root = uf.find(u);
g[root] &= w;
}
const f = (u: number, v: number): number => {
if (u === v) {
return 0;
}
const [a, b] = [uf.find(u), uf.find(v)];
return a === b ? g[a] : -1;
};
return query.map(([u, v]) => f(u, v));
}
|
3,109
|
Find the Index of Permutation
|
Medium
|
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</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>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only two permutations in the following order:</p>
<p><code>[1,2]</code>, <code>[2,1]</code><br />
<br />
And <code>[1,2]</code> is at index 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only six permutations in the following order:</p>
<p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br />
<br />
And <code>[3,1,2]</code> is at index 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == perm.length <= 10<sup>5</sup></code></li>
<li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
C++
|
class BinaryIndexedTree {
private:
int n;
vector<int> c;
public:
BinaryIndexedTree(int n)
: n(n)
, c(n + 1) {}
void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
int query(int x) {
int s = 0;
for (; x > 0; x -= x & -x) {
s += c[x];
}
return s;
}
};
class Solution {
public:
int getPermutationIndex(vector<int>& perm) {
const int mod = 1e9 + 7;
using ll = long long;
ll ans = 0;
int n = perm.size();
BinaryIndexedTree tree(n + 1);
ll f[n];
f[0] = 1;
for (int i = 1; i < n; ++i) {
f[i] = f[i - 1] * i % mod;
}
for (int i = 0; i < n; ++i) {
int cnt = perm[i] - 1 - tree.query(perm[i]);
ans += cnt * f[n - i - 1] % mod;
tree.update(perm[i], 1);
}
return ans % mod;
}
};
|
3,109
|
Find the Index of Permutation
|
Medium
|
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</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>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only two permutations in the following order:</p>
<p><code>[1,2]</code>, <code>[2,1]</code><br />
<br />
And <code>[1,2]</code> is at index 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only six permutations in the following order:</p>
<p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br />
<br />
And <code>[3,1,2]</code> is at index 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == perm.length <= 10<sup>5</sup></code></li>
<li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Go
|
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) *BinaryIndexedTree {
return &BinaryIndexedTree{n: n, c: make([]int, n+1)}
}
func (bit *BinaryIndexedTree) update(x, delta int) {
for ; x <= bit.n; x += x & -x {
bit.c[x] += delta
}
}
func (bit *BinaryIndexedTree) query(x int) int {
s := 0
for ; x > 0; x -= x & -x {
s += bit.c[x]
}
return s
}
func getPermutationIndex(perm []int) (ans int) {
const mod int = 1e9 + 7
n := len(perm)
tree := NewBinaryIndexedTree(n + 1)
f := make([]int, n)
f[0] = 1
for i := 1; i < n; i++ {
f[i] = f[i-1] * i % mod
}
for i, x := range perm {
cnt := x - 1 - tree.query(x)
ans += cnt * f[n-1-i] % mod
tree.update(x, 1)
}
return ans % mod
}
|
3,109
|
Find the Index of Permutation
|
Medium
|
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</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>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only two permutations in the following order:</p>
<p><code>[1,2]</code>, <code>[2,1]</code><br />
<br />
And <code>[1,2]</code> is at index 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only six permutations in the following order:</p>
<p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br />
<br />
And <code>[3,1,2]</code> is at index 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == perm.length <= 10<sup>5</sup></code></li>
<li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Java
|
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
public int query(int x) {
int s = 0;
for (; x > 0; x -= x & -x) {
s += c[x];
}
return s;
}
}
class Solution {
public int getPermutationIndex(int[] perm) {
final int mod = (int) 1e9 + 7;
long ans = 0;
int n = perm.length;
BinaryIndexedTree tree = new BinaryIndexedTree(n + 1);
long[] f = new long[n];
f[0] = 1;
for (int i = 1; i < n; ++i) {
f[i] = f[i - 1] * i % mod;
}
for (int i = 0; i < n; ++i) {
int cnt = perm[i] - 1 - tree.query(perm[i]);
ans = (ans + cnt * f[n - i - 1] % mod) % mod;
tree.update(perm[i], 1);
}
return (int) ans;
}
}
|
3,109
|
Find the Index of Permutation
|
Medium
|
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</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>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only two permutations in the following order:</p>
<p><code>[1,2]</code>, <code>[2,1]</code><br />
<br />
And <code>[1,2]</code> is at index 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only six permutations in the following order:</p>
<p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br />
<br />
And <code>[3,1,2]</code> is at index 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == perm.length <= 10<sup>5</sup></code></li>
<li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
Python
|
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def getPermutationIndex(self, perm: List[int]) -> int:
mod = 10**9 + 7
ans, n = 0, len(perm)
tree = BinaryIndexedTree(n + 1)
f = [1] * n
for i in range(1, n):
f[i] = f[i - 1] * i % mod
for i, x in enumerate(perm):
cnt = x - 1 - tree.query(x)
ans += cnt * f[n - i - 1] % mod
tree.update(x, 1)
return ans % mod
|
3,109
|
Find the Index of Permutation
|
Medium
|
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</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>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only two permutations in the following order:</p>
<p><code>[1,2]</code>, <code>[2,1]</code><br />
<br />
And <code>[1,2]</code> is at index 0.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>There are only six permutations in the following order:</p>
<p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br />
<br />
And <code>[3,1,2]</code> is at index 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == perm.length <= 10<sup>5</sup></code></li>
<li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li>
</ul>
|
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
|
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, delta: number): void {
for (; x <= this.n; x += x & -x) {
this.c[x] += delta;
}
}
query(x: number): number {
let s = 0;
for (; x > 0; x -= x & -x) {
s += this.c[x];
}
return s;
}
}
function getPermutationIndex(perm: number[]): number {
const mod = 1e9 + 7;
const n = perm.length;
const tree = new BinaryIndexedTree(n + 1);
let ans = 0;
const f: number[] = Array(n).fill(1);
for (let i = 1; i < n; ++i) {
f[i] = (f[i - 1] * i) % mod;
}
for (let i = 0; i < n; ++i) {
const cnt = perm[i] - 1 - tree.query(perm[i]);
ans = (ans + cnt * f[n - i - 1]) % mod;
tree.update(perm[i], 1);
}
return ans % mod;
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
int scoreOfString(string s) {
int ans = 0;
for (int i = 1; i < s.size(); ++i) {
ans += abs(s[i] - s[i - 1]);
}
return ans;
}
};
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
C#
|
public class Solution {
public int ScoreOfString(string s) {
int ans = 0;
for (int i = 1; i < s.Length; ++i) {
ans += Math.Abs(s[i] - s[i - 1]);
}
return ans;
}
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Go
|
func scoreOfString(s string) (ans int) {
for i := 1; i < len(s); i++ {
ans += abs(int(s[i-1]) - int(s[i]))
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Java
|
class Solution {
public int scoreOfString(String s) {
int ans = 0;
for (int i = 1; i < s.length(); ++i) {
ans += Math.abs(s.charAt(i - 1) - s.charAt(i));
}
return ans;
}
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
PHP
|
class Solution {
/**
* @param String $s
* @return Integer
*/
function scoreOfString($s) {
$ans = 0;
$n = strlen($s);
for ($i = 1; $i < $n; ++$i) {
$ans += abs(ord($s[$i]) - ord($s[$i - 1]));
}
return $ans;
}
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Python
|
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(a - b) for a, b in pairwise(map(ord, s)))
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Rust
|
impl Solution {
pub fn score_of_string(s: String) -> i32 {
s.as_bytes()
.windows(2)
.map(|w| (w[0] as i32 - w[1] as i32).abs())
.sum()
}
}
|
3,110
|
Score of a String
|
Easy
|
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p>
<p>Return the <strong>score</strong> of<em> </em><code>s</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "hello"</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'h' = 104</code>, <code>'e' = 101</code>, <code>'l' = 108</code>, <code>'o' = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "zaz"</span></p>
<p><strong>Output:</strong> <span class="example-io">50</span></p>
<p><strong>Explanation:</strong></p>
<p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>'z' = 122</code>, <code>'a' = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
TypeScript
|
function scoreOfString(s: string): number {
let ans = 0;
for (let i = 1; i < s.length; ++i) {
ans += Math.abs(s.charCodeAt(i) - s.charCodeAt(i - 1));
}
return ans;
}
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
int minRectanglesToCoverPoints(vector<vector<int>>& points, int w) {
sort(points.begin(), points.end());
int ans = 0, x1 = -1;
for (const auto& p : points) {
int x = p[0];
if (x > x1) {
++ans;
x1 = x + w;
}
}
return ans;
}
};
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
C#
|
public class Solution {
public int MinRectanglesToCoverPoints(int[][] points, int w) {
Array.Sort(points, (a, b) => a[0] - b[0]);
int ans = 0, x1 = -1;
foreach (int[] p in points) {
int x = p[0];
if (x > x1) {
ans++;
x1 = x + w;
}
}
return ans;
}
}
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func minRectanglesToCoverPoints(points [][]int, w int) (ans int) {
sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] })
x1 := -1
for _, p := range points {
if x := p[0]; x > x1 {
ans++
x1 = x + w
}
}
return
}
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public int minRectanglesToCoverPoints(int[][] points, int w) {
Arrays.sort(points, (a, b) -> a[0] - b[0]);
int ans = 0, x1 = -1;
for (int[] p : points) {
int x = p[0];
if (x > x1) {
++ans;
x1 = x + w;
}
}
return ans;
}
}
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def minRectanglesToCoverPoints(self, points: List[List[int]], w: int) -> int:
points.sort()
ans, x1 = 0, -1
for x, _ in points:
if x > x1:
ans += 1
x1 = x + w
return ans
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
Rust
|
impl Solution {
pub fn min_rectangles_to_cover_points(mut points: Vec<Vec<i32>>, w: i32) -> i32 {
points.sort_by(|a, b| a[0].cmp(&b[0]));
let mut ans = 0;
let mut x1 = -1;
for p in points {
let x = p[0];
if x > x1 {
ans += 1;
x1 = x + w;
}
}
ans
}
}
|
3,111
|
Minimum Rectangles to Cover Points
|
Medium
|
<p>You are given a 2D integer array <code>points</code>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. You are also given an integer <code>w</code>. Your task is to <strong>cover</strong> <strong>all</strong> the given points with rectangles.</p>
<p>Each rectangle has its lower end at some point <code>(x<sub>1</sub>, 0)</code> and its upper end at some point <code>(x<sub>2</sub>, y<sub>2</sub>)</code>, where <code>x<sub>1</sub> <= x<sub>2</sub></code>, <code>y<sub>2</sub> >= 0</code>, and the condition <code>x<sub>2</sub> - x<sub>1</sub> <= w</code> <strong>must</strong> be satisfied for each rectangle.</p>
<p>A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.</p>
<p>Return an integer denoting the <strong>minimum</strong> number of rectangles needed so that each point is covered by <strong>at least one</strong> rectangle<em>.</em></p>
<p><strong>Note:</strong> A point may be covered by more than one rectangle.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-33-05.png" style="width: 205px; height: 300px;" /></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;
">points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(2, 8)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(4, 8)</code></li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-18-59-12.png" style="width: 260px; height: 250px;" /></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;
">points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2</span></p>
<p><strong>Output:</strong> <span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
">3</span></p>
<p><strong>Explanation: </strong></p>
<p>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(0, 0)</code> and its upper end at <code>(2, 2)</code></li>
<li>A rectangle with a lower end at <code>(3, 0)</code> and its upper end at <code>(5, 5)</code></li>
<li>A rectangle with a lower end at <code>(6, 0)</code> and its upper end at <code>(6, 6)</code></li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3111.Minimum%20Rectangles%20to%20Cover%20Points/images/screenshot-from-2024-03-04-20-24-03.png" style="height: 150px; width: 127px;" /></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;
">points = [[2,3],[1,2]], w = 0</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>The image above shows one possible placement of rectangles to cover the points:</p>
<ul>
<li>A rectangle with a lower end at <code>(1, 0)</code> and its upper end at <code>(1, 2)</code></li>
<li>A rectangle with a lower end at <code>(2, 0)</code> and its upper end at <code>(2, 3)</code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= points.length <= 10<sup>5</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= x<sub>i</sub> == points[i][0] <= 10<sup>9</sup></code></li>
<li><code>0 <= y<sub>i</sub> == points[i][1] <= 10<sup>9</sup></code></li>
<li><code>0 <= w <= 10<sup>9</sup></code></li>
<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function minRectanglesToCoverPoints(points: number[][], w: number): number {
points.sort((a, b) => a[0] - b[0]);
let [ans, x1] = [0, -1];
for (const [x, _] of points) {
if (x > x1) {
++ans;
x1 = x + w;
}
}
return ans;
}
|
3,112
|
Minimum Time to Visit Disappearing Nodes
|
Medium
|
<p>There is an undirected graph of <code>n</code> nodes. You are given a 2D array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> describes an edge between node <code>u<sub>i</sub></code> and node <code>v<sub>i</sub></code> with a traversal time of <code>length<sub>i</sub></code> units.</p>
<p>Additionally, you are given an array <code>disappear</code>, where <code>disappear[i]</code> denotes the time when the node <code>i</code> disappears from the graph and you won't be able to visit it.</p>
<p><strong>Note</strong> that the graph might be <em>disconnected</em> and might contain <em>multiple edges</em>.</p>
<p>Return the array <code>answer</code>, with <code>answer[i]</code> denoting the <strong>minimum</strong> units of time required to reach node <code>i</code> from node 0. If node <code>i</code> is <strong>unreachable</strong> from node 0 then <code>answer[i]</code> is <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is our starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>. Unfortunately, it disappears at that moment, so we won't be able to visit it.</li>
<li>For node 2, we need at least 4 units of time to traverse <code>edges[2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools-1.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is the starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>.</li>
<li>For node 2, we need at least 3 units of time to traverse <code>edges[0]</code> and <code>edges[1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, edges = [[0,1,1]], disappear = [1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Exactly when we reach node 1, it disappears.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>1 <= length<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>disappear.length == n</code></li>
<li><code>1 <= disappear[i] <= 10<sup>5</sup></code></li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
C++
|
class Solution {
public:
vector<int> minimumTime(int n, vector<vector<int>>& edges, vector<int>& disappear) {
vector<vector<pair<int, int>>> g(n);
for (const auto& e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].push_back({v, w});
g[v].push_back({u, w});
}
vector<int> dist(n, 1 << 30);
dist[0] = 0;
using pii = pair<int, int>;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, 0});
while (!pq.empty()) {
auto [du, u] = pq.top();
pq.pop();
if (du > dist[u]) {
continue;
}
for (auto [v, w] : g[u]) {
if (dist[v] > dist[u] + w && dist[u] + w < disappear[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ans[i] = dist[i] < disappear[i] ? dist[i] : -1;
}
return ans;
}
};
|
3,112
|
Minimum Time to Visit Disappearing Nodes
|
Medium
|
<p>There is an undirected graph of <code>n</code> nodes. You are given a 2D array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> describes an edge between node <code>u<sub>i</sub></code> and node <code>v<sub>i</sub></code> with a traversal time of <code>length<sub>i</sub></code> units.</p>
<p>Additionally, you are given an array <code>disappear</code>, where <code>disappear[i]</code> denotes the time when the node <code>i</code> disappears from the graph and you won't be able to visit it.</p>
<p><strong>Note</strong> that the graph might be <em>disconnected</em> and might contain <em>multiple edges</em>.</p>
<p>Return the array <code>answer</code>, with <code>answer[i]</code> denoting the <strong>minimum</strong> units of time required to reach node <code>i</code> from node 0. If node <code>i</code> is <strong>unreachable</strong> from node 0 then <code>answer[i]</code> is <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is our starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>. Unfortunately, it disappears at that moment, so we won't be able to visit it.</li>
<li>For node 2, we need at least 4 units of time to traverse <code>edges[2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools-1.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is the starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>.</li>
<li>For node 2, we need at least 3 units of time to traverse <code>edges[0]</code> and <code>edges[1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, edges = [[0,1,1]], disappear = [1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Exactly when we reach node 1, it disappears.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>1 <= length<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>disappear.length == n</code></li>
<li><code>1 <= disappear[i] <= 10<sup>5</sup></code></li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Go
|
func minimumTime(n int, edges [][]int, disappear []int) []int {
g := make([][]pair, n)
for _, e := range edges {
u, v, w := e[0], e[1], e[2]
g[u] = append(g[u], pair{v, w})
g[v] = append(g[v], pair{u, w})
}
dist := make([]int, n)
for i := range dist {
dist[i] = 1 << 30
}
dist[0] = 0
pq := hp{{0, 0}}
for len(pq) > 0 {
du, u := pq[0].dis, pq[0].u
heap.Pop(&pq)
if du > dist[u] {
continue
}
for _, nxt := range g[u] {
v, w := nxt.dis, nxt.u
if dist[v] > dist[u]+w && dist[u]+w < disappear[v] {
dist[v] = dist[u] + w
heap.Push(&pq, pair{dist[v], v})
}
}
}
ans := make([]int, n)
for i := 0; i < n; i++ {
if dist[i] < disappear[i] {
ans[i] = dist[i]
} else {
ans[i] = -1
}
}
return ans
}
type pair struct{ dis, u int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].dis < h[j].dis }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
3,112
|
Minimum Time to Visit Disappearing Nodes
|
Medium
|
<p>There is an undirected graph of <code>n</code> nodes. You are given a 2D array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> describes an edge between node <code>u<sub>i</sub></code> and node <code>v<sub>i</sub></code> with a traversal time of <code>length<sub>i</sub></code> units.</p>
<p>Additionally, you are given an array <code>disappear</code>, where <code>disappear[i]</code> denotes the time when the node <code>i</code> disappears from the graph and you won't be able to visit it.</p>
<p><strong>Note</strong> that the graph might be <em>disconnected</em> and might contain <em>multiple edges</em>.</p>
<p>Return the array <code>answer</code>, with <code>answer[i]</code> denoting the <strong>minimum</strong> units of time required to reach node <code>i</code> from node 0. If node <code>i</code> is <strong>unreachable</strong> from node 0 then <code>answer[i]</code> is <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is our starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>. Unfortunately, it disappears at that moment, so we won't be able to visit it.</li>
<li>For node 2, we need at least 4 units of time to traverse <code>edges[2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools-1.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is the starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>.</li>
<li>For node 2, we need at least 3 units of time to traverse <code>edges[0]</code> and <code>edges[1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, edges = [[0,1,1]], disappear = [1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Exactly when we reach node 1, it disappears.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>1 <= length<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>disappear.length == n</code></li>
<li><code>1 <= disappear[i] <= 10<sup>5</sup></code></li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Java
|
class Solution {
public int[] minimumTime(int n, int[][] edges, int[] disappear) {
List<int[]>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].add(new int[] {v, w});
g[v].add(new int[] {u, w});
}
int[] dist = new int[n];
Arrays.fill(dist, 1 << 30);
dist[0] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[] {0, 0});
while (!pq.isEmpty()) {
var e = pq.poll();
int du = e[0], u = e[1];
if (du > dist[u]) {
continue;
}
for (var nxt : g[u]) {
int v = nxt[0], w = nxt[1];
if (dist[v] > dist[u] + w && dist[u] + w < disappear[v]) {
dist[v] = dist[u] + w;
pq.offer(new int[] {dist[v], v});
}
}
}
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = dist[i] < disappear[i] ? dist[i] : -1;
}
return ans;
}
}
|
3,112
|
Minimum Time to Visit Disappearing Nodes
|
Medium
|
<p>There is an undirected graph of <code>n</code> nodes. You are given a 2D array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> describes an edge between node <code>u<sub>i</sub></code> and node <code>v<sub>i</sub></code> with a traversal time of <code>length<sub>i</sub></code> units.</p>
<p>Additionally, you are given an array <code>disappear</code>, where <code>disappear[i]</code> denotes the time when the node <code>i</code> disappears from the graph and you won't be able to visit it.</p>
<p><strong>Note</strong> that the graph might be <em>disconnected</em> and might contain <em>multiple edges</em>.</p>
<p>Return the array <code>answer</code>, with <code>answer[i]</code> denoting the <strong>minimum</strong> units of time required to reach node <code>i</code> from node 0. If node <code>i</code> is <strong>unreachable</strong> from node 0 then <code>answer[i]</code> is <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is our starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>. Unfortunately, it disappears at that moment, so we won't be able to visit it.</li>
<li>For node 2, we need at least 4 units of time to traverse <code>edges[2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools-1.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is the starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>.</li>
<li>For node 2, we need at least 3 units of time to traverse <code>edges[0]</code> and <code>edges[1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, edges = [[0,1,1]], disappear = [1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Exactly when we reach node 1, it disappears.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>1 <= length<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>disappear.length == n</code></li>
<li><code>1 <= disappear[i] <= 10<sup>5</sup></code></li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
Python
|
class Solution:
def minimumTime(
self, n: int, edges: List[List[int]], disappear: List[int]
) -> List[int]:
g = defaultdict(list)
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
dist = [inf] * n
dist[0] = 0
pq = [(0, 0)]
while pq:
du, u = heappop(pq)
if du > dist[u]:
continue
for v, w in g[u]:
if dist[v] > dist[u] + w and dist[u] + w < disappear[v]:
dist[v] = dist[u] + w
heappush(pq, (dist[v], v))
return [a if a < b else -1 for a, b in zip(dist, disappear)]
|
3,112
|
Minimum Time to Visit Disappearing Nodes
|
Medium
|
<p>There is an undirected graph of <code>n</code> nodes. You are given a 2D array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code> describes an edge between node <code>u<sub>i</sub></code> and node <code>v<sub>i</sub></code> with a traversal time of <code>length<sub>i</sub></code> units.</p>
<p>Additionally, you are given an array <code>disappear</code>, where <code>disappear[i]</code> denotes the time when the node <code>i</code> disappears from the graph and you won't be able to visit it.</p>
<p><strong>Note</strong> that the graph might be <em>disconnected</em> and might contain <em>multiple edges</em>.</p>
<p>Return the array <code>answer</code>, with <code>answer[i]</code> denoting the <strong>minimum</strong> units of time required to reach node <code>i</code> from node 0. If node <code>i</code> is <strong>unreachable</strong> from node 0 then <code>answer[i]</code> is <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is our starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>. Unfortunately, it disappears at that moment, so we won't be able to visit it.</li>
<li>For node 2, we need at least 4 units of time to traverse <code>edges[2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,2,3]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3112.Minimum%20Time%20to%20Visit%20Disappearing%20Nodes/images/output-onlinepngtools-1.png" style="width: 350px; height: 210px;" /></p>
<p>We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.</p>
<ul>
<li>For node 0, we don't need any time as it is the starting point.</li>
<li>For node 1, we need at least 2 units of time to traverse <code>edges[0]</code>.</li>
<li>For node 2, we need at least 3 units of time to traverse <code>edges[0]</code> and <code>edges[1]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2, edges = [[0,1,1]], disappear = [1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,-1]</span></p>
<p><strong>Explanation:</strong></p>
<p>Exactly when we reach node 1, it disappears.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 5 * 10<sup>4</sup></code></li>
<li><code>0 <= edges.length <= 10<sup>5</sup></code></li>
<li><code>edges[i] == [u<sub>i</sub>, v<sub>i</sub>, length<sub>i</sub>]</code></li>
<li><code>0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1</code></li>
<li><code>1 <= length<sub>i</sub> <= 10<sup>5</sup></code></li>
<li><code>disappear.length == n</code></li>
<li><code>1 <= disappear[i] <= 10<sup>5</sup></code></li>
</ul>
|
Graph; Array; Shortest Path; Heap (Priority Queue)
|
TypeScript
|
function minimumTime(n: number, edges: number[][], disappear: number[]): number[] {
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (const [u, v, w] of edges) {
g[u].push([v, w]);
g[v].push([u, w]);
}
const dist = Array.from({ length: n }, () => Infinity);
dist[0] = 0;
const pq = new PriorityQueue({
compare: (a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]),
});
pq.enqueue([0, 0]);
while (pq.size() > 0) {
const [du, u] = pq.dequeue()!;
if (du > dist[u]) {
continue;
}
for (const [v, w] of g[u]) {
if (dist[v] > dist[u] + w && dist[u] + w < disappear[v]) {
dist[v] = dist[u] + w;
pq.enqueue([dist[v], v]);
}
}
}
return dist.map((a, i) => (a < disappear[i] ? a : -1));
}
|
3,113
|
Find the Number of Subarrays Where Boundary Elements Are Maximum
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>Return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>, where the <strong>first</strong> and the <strong>last</strong> elements of the subarray are <em>equal</em> to the <strong>largest</strong> element in the subarray.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<strong><u>1</u></strong>,4,3,3,2]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</li>
<li>subarray <code>[1,<u><strong>4</strong></u>,3,3,2]</code>, with its largest element 4. The first element is 4 and the last element is also 4.</li>
<li>subarray <code>[1,4,<u><strong>3</strong></u>,3,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,<u><strong>3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,3,<u><strong>2</strong></u>]</code>, with its largest element 2. The first element is 2 and the last element is also 2.</li>
<li>subarray <code>[1,4,<u><strong>3,3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<u><strong>3</strong></u>,3,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<strong><u>3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,3,<u><strong>3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<strong><u>3,3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<u><strong>3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<u><strong>3,3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray of <code>nums</code> which is <code>[<strong><u>1</u></strong>]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</p>
<p>Hence, we return 1.</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>
|
Stack; Array; Binary Search; Monotonic Stack
|
C++
|
class Solution {
public:
long long numberOfSubarrays(vector<int>& nums) {
vector<pair<int, int>> stk;
long long ans = 0;
for (int x : nums) {
while (!stk.empty() && stk.back().first < x) {
stk.pop_back();
}
if (stk.empty() || stk.back().first > x) {
stk.push_back(make_pair(x, 1));
} else {
stk.back().second++;
}
ans += stk.back().second;
}
return ans;
}
};
|
3,113
|
Find the Number of Subarrays Where Boundary Elements Are Maximum
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>Return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>, where the <strong>first</strong> and the <strong>last</strong> elements of the subarray are <em>equal</em> to the <strong>largest</strong> element in the subarray.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<strong><u>1</u></strong>,4,3,3,2]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</li>
<li>subarray <code>[1,<u><strong>4</strong></u>,3,3,2]</code>, with its largest element 4. The first element is 4 and the last element is also 4.</li>
<li>subarray <code>[1,4,<u><strong>3</strong></u>,3,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,<u><strong>3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,3,<u><strong>2</strong></u>]</code>, with its largest element 2. The first element is 2 and the last element is also 2.</li>
<li>subarray <code>[1,4,<u><strong>3,3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<u><strong>3</strong></u>,3,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<strong><u>3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,3,<u><strong>3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<strong><u>3,3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<u><strong>3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<u><strong>3,3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray of <code>nums</code> which is <code>[<strong><u>1</u></strong>]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</p>
<p>Hence, we return 1.</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>
|
Stack; Array; Binary Search; Monotonic Stack
|
Go
|
func numberOfSubarrays(nums []int) (ans int64) {
stk := [][2]int{}
for _, x := range nums {
for len(stk) > 0 && stk[len(stk)-1][0] < x {
stk = stk[:len(stk)-1]
}
if len(stk) == 0 || stk[len(stk)-1][0] > x {
stk = append(stk, [2]int{x, 1})
} else {
stk[len(stk)-1][1]++
}
ans += int64(stk[len(stk)-1][1])
}
return
}
|
3,113
|
Find the Number of Subarrays Where Boundary Elements Are Maximum
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>Return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>, where the <strong>first</strong> and the <strong>last</strong> elements of the subarray are <em>equal</em> to the <strong>largest</strong> element in the subarray.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<strong><u>1</u></strong>,4,3,3,2]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</li>
<li>subarray <code>[1,<u><strong>4</strong></u>,3,3,2]</code>, with its largest element 4. The first element is 4 and the last element is also 4.</li>
<li>subarray <code>[1,4,<u><strong>3</strong></u>,3,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,<u><strong>3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,3,<u><strong>2</strong></u>]</code>, with its largest element 2. The first element is 2 and the last element is also 2.</li>
<li>subarray <code>[1,4,<u><strong>3,3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<u><strong>3</strong></u>,3,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<strong><u>3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,3,<u><strong>3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<strong><u>3,3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<u><strong>3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<u><strong>3,3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray of <code>nums</code> which is <code>[<strong><u>1</u></strong>]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</p>
<p>Hence, we return 1.</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>
|
Stack; Array; Binary Search; Monotonic Stack
|
Java
|
class Solution {
public long numberOfSubarrays(int[] nums) {
Deque<int[]> stk = new ArrayDeque<>();
long ans = 0;
for (int x : nums) {
while (!stk.isEmpty() && stk.peek()[0] < x) {
stk.pop();
}
if (stk.isEmpty() || stk.peek()[0] > x) {
stk.push(new int[] {x, 1});
} else {
stk.peek()[1]++;
}
ans += stk.peek()[1];
}
return ans;
}
}
|
3,113
|
Find the Number of Subarrays Where Boundary Elements Are Maximum
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>Return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>, where the <strong>first</strong> and the <strong>last</strong> elements of the subarray are <em>equal</em> to the <strong>largest</strong> element in the subarray.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<strong><u>1</u></strong>,4,3,3,2]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</li>
<li>subarray <code>[1,<u><strong>4</strong></u>,3,3,2]</code>, with its largest element 4. The first element is 4 and the last element is also 4.</li>
<li>subarray <code>[1,4,<u><strong>3</strong></u>,3,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,<u><strong>3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,3,<u><strong>2</strong></u>]</code>, with its largest element 2. The first element is 2 and the last element is also 2.</li>
<li>subarray <code>[1,4,<u><strong>3,3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<u><strong>3</strong></u>,3,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<strong><u>3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,3,<u><strong>3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<strong><u>3,3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<u><strong>3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<u><strong>3,3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray of <code>nums</code> which is <code>[<strong><u>1</u></strong>]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</p>
<p>Hence, we return 1.</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>
|
Stack; Array; Binary Search; Monotonic Stack
|
Python
|
class Solution:
def numberOfSubarrays(self, nums: List[int]) -> int:
stk = []
ans = 0
for x in nums:
while stk and stk[-1][0] < x:
stk.pop()
if not stk or stk[-1][0] > x:
stk.append([x, 1])
else:
stk[-1][1] += 1
ans += stk[-1][1]
return ans
|
3,113
|
Find the Number of Subarrays Where Boundary Elements Are Maximum
|
Hard
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>Return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code>, where the <strong>first</strong> and the <strong>last</strong> elements of the subarray are <em>equal</em> to the <strong>largest</strong> element in the subarray.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<strong><u>1</u></strong>,4,3,3,2]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</li>
<li>subarray <code>[1,<u><strong>4</strong></u>,3,3,2]</code>, with its largest element 4. The first element is 4 and the last element is also 4.</li>
<li>subarray <code>[1,4,<u><strong>3</strong></u>,3,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,<u><strong>3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[1,4,3,3,<u><strong>2</strong></u>]</code>, with its largest element 2. The first element is 2 and the last element is also 2.</li>
<li>subarray <code>[1,4,<u><strong>3,3</strong></u>,2]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:</p>
<ul>
<li>subarray <code>[<u><strong>3</strong></u>,3,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<strong><u>3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,3,<u><strong>3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<strong><u>3,3</u></strong>,3]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[3,<u><strong>3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
<li>subarray <code>[<u><strong>3,3,3</strong></u>]</code>, with its largest element 3. The first element is 3 and the last element is also 3.</li>
</ul>
<p>Hence, we return 6.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is a single subarray of <code>nums</code> which is <code>[<strong><u>1</u></strong>]</code>, with its largest element 1. The first element is 1 and the last element is also 1.</p>
<p>Hence, we return 1.</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>
|
Stack; Array; Binary Search; Monotonic Stack
|
TypeScript
|
function numberOfSubarrays(nums: number[]): number {
const stk: number[][] = [];
let ans = 0;
for (const x of nums) {
while (stk.length > 0 && stk.at(-1)![0] < x) {
stk.pop();
}
if (stk.length === 0 || stk.at(-1)![0] > x) {
stk.push([x, 1]);
} else {
stk.at(-1)![1]++;
}
ans += stk.at(-1)![1];
}
return ans;
}
|
3,114
|
Latest Time You Can Obtain After Replacing Characters
|
Easy
|
<p>You are given a string <code>s</code> representing a 12-hour format time where some of the digits (possibly none) are replaced with a <code>"?"</code>.</p>
<p>12-hour times are formatted as <code>"HH:MM"</code>, where <code>HH</code> is between <code>00</code> and <code>11</code>, and <code>MM</code> is between <code>00</code> and <code>59</code>. The earliest 12-hour time is <code>00:00</code>, and the latest is <code>11:59</code>.</p>
<p>You have to replace <strong>all</strong> the <code>"?"</code> characters in <code>s</code> with digits such that the time we obtain by the resulting string is a <strong>valid</strong> 12-hour format time and is the <strong>latest</strong> possible.</p>
<p>Return <em>the resulting string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1?:?4"</span></p>
<p><strong>Output:</strong> <span class="example-io">"11:54"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"11:54"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0?:5?"</span></p>
<p><strong>Output:</strong> <span class="example-io">"09:59"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"09:59"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>s.length == 5</code></li>
<li><code>s[2]</code> is equal to the character <code>":"</code>.</li>
<li>All characters except <code>s[2]</code> are digits or <code>"?"</code> characters.</li>
<li>The input is generated such that there is <strong>at least</strong> one time between <code>"00:00"</code> and <code>"11:59"</code> that you can obtain after replacing the <code>"?"</code> characters.</li>
</ul>
|
String; Enumeration
|
C++
|
class Solution {
public:
string findLatestTime(string s) {
for (int h = 11;; h--) {
for (int m = 59; m >= 0; m--) {
char t[6];
sprintf(t, "%02d:%02d", h, m);
bool ok = true;
for (int i = 0; i < s.length(); i++) {
if (s[i] != '?' && s[i] != t[i]) {
ok = false;
break;
}
}
if (ok) {
return t;
}
}
}
}
};
|
3,114
|
Latest Time You Can Obtain After Replacing Characters
|
Easy
|
<p>You are given a string <code>s</code> representing a 12-hour format time where some of the digits (possibly none) are replaced with a <code>"?"</code>.</p>
<p>12-hour times are formatted as <code>"HH:MM"</code>, where <code>HH</code> is between <code>00</code> and <code>11</code>, and <code>MM</code> is between <code>00</code> and <code>59</code>. The earliest 12-hour time is <code>00:00</code>, and the latest is <code>11:59</code>.</p>
<p>You have to replace <strong>all</strong> the <code>"?"</code> characters in <code>s</code> with digits such that the time we obtain by the resulting string is a <strong>valid</strong> 12-hour format time and is the <strong>latest</strong> possible.</p>
<p>Return <em>the resulting string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1?:?4"</span></p>
<p><strong>Output:</strong> <span class="example-io">"11:54"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"11:54"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0?:5?"</span></p>
<p><strong>Output:</strong> <span class="example-io">"09:59"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"09:59"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>s.length == 5</code></li>
<li><code>s[2]</code> is equal to the character <code>":"</code>.</li>
<li>All characters except <code>s[2]</code> are digits or <code>"?"</code> characters.</li>
<li>The input is generated such that there is <strong>at least</strong> one time between <code>"00:00"</code> and <code>"11:59"</code> that you can obtain after replacing the <code>"?"</code> characters.</li>
</ul>
|
String; Enumeration
|
Go
|
func findLatestTime(s string) string {
for h := 11; ; h-- {
for m := 59; m >= 0; m-- {
t := fmt.Sprintf("%02d:%02d", h, m)
ok := true
for i := 0; i < len(s); i++ {
if s[i] != '?' && s[i] != t[i] {
ok = false
break
}
}
if ok {
return t
}
}
}
}
|
3,114
|
Latest Time You Can Obtain After Replacing Characters
|
Easy
|
<p>You are given a string <code>s</code> representing a 12-hour format time where some of the digits (possibly none) are replaced with a <code>"?"</code>.</p>
<p>12-hour times are formatted as <code>"HH:MM"</code>, where <code>HH</code> is between <code>00</code> and <code>11</code>, and <code>MM</code> is between <code>00</code> and <code>59</code>. The earliest 12-hour time is <code>00:00</code>, and the latest is <code>11:59</code>.</p>
<p>You have to replace <strong>all</strong> the <code>"?"</code> characters in <code>s</code> with digits such that the time we obtain by the resulting string is a <strong>valid</strong> 12-hour format time and is the <strong>latest</strong> possible.</p>
<p>Return <em>the resulting string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1?:?4"</span></p>
<p><strong>Output:</strong> <span class="example-io">"11:54"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"11:54"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0?:5?"</span></p>
<p><strong>Output:</strong> <span class="example-io">"09:59"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"09:59"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>s.length == 5</code></li>
<li><code>s[2]</code> is equal to the character <code>":"</code>.</li>
<li>All characters except <code>s[2]</code> are digits or <code>"?"</code> characters.</li>
<li>The input is generated such that there is <strong>at least</strong> one time between <code>"00:00"</code> and <code>"11:59"</code> that you can obtain after replacing the <code>"?"</code> characters.</li>
</ul>
|
String; Enumeration
|
Java
|
class Solution {
public String findLatestTime(String s) {
for (int h = 11;; h--) {
for (int m = 59; m >= 0; m--) {
String t = String.format("%02d:%02d", h, m);
boolean ok = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '?' && s.charAt(i) != t.charAt(i)) {
ok = false;
break;
}
}
if (ok) {
return t;
}
}
}
}
}
|
3,114
|
Latest Time You Can Obtain After Replacing Characters
|
Easy
|
<p>You are given a string <code>s</code> representing a 12-hour format time where some of the digits (possibly none) are replaced with a <code>"?"</code>.</p>
<p>12-hour times are formatted as <code>"HH:MM"</code>, where <code>HH</code> is between <code>00</code> and <code>11</code>, and <code>MM</code> is between <code>00</code> and <code>59</code>. The earliest 12-hour time is <code>00:00</code>, and the latest is <code>11:59</code>.</p>
<p>You have to replace <strong>all</strong> the <code>"?"</code> characters in <code>s</code> with digits such that the time we obtain by the resulting string is a <strong>valid</strong> 12-hour format time and is the <strong>latest</strong> possible.</p>
<p>Return <em>the resulting string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1?:?4"</span></p>
<p><strong>Output:</strong> <span class="example-io">"11:54"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"11:54"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0?:5?"</span></p>
<p><strong>Output:</strong> <span class="example-io">"09:59"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"09:59"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>s.length == 5</code></li>
<li><code>s[2]</code> is equal to the character <code>":"</code>.</li>
<li>All characters except <code>s[2]</code> are digits or <code>"?"</code> characters.</li>
<li>The input is generated such that there is <strong>at least</strong> one time between <code>"00:00"</code> and <code>"11:59"</code> that you can obtain after replacing the <code>"?"</code> characters.</li>
</ul>
|
String; Enumeration
|
Python
|
class Solution:
def findLatestTime(self, s: str) -> str:
for h in range(11, -1, -1):
for m in range(59, -1, -1):
t = f"{h:02d}:{m:02d}"
if all(a == b for a, b in zip(s, t) if a != "?"):
return t
|
3,114
|
Latest Time You Can Obtain After Replacing Characters
|
Easy
|
<p>You are given a string <code>s</code> representing a 12-hour format time where some of the digits (possibly none) are replaced with a <code>"?"</code>.</p>
<p>12-hour times are formatted as <code>"HH:MM"</code>, where <code>HH</code> is between <code>00</code> and <code>11</code>, and <code>MM</code> is between <code>00</code> and <code>59</code>. The earliest 12-hour time is <code>00:00</code>, and the latest is <code>11:59</code>.</p>
<p>You have to replace <strong>all</strong> the <code>"?"</code> characters in <code>s</code> with digits such that the time we obtain by the resulting string is a <strong>valid</strong> 12-hour format time and is the <strong>latest</strong> possible.</p>
<p>Return <em>the resulting string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "1?:?4"</span></p>
<p><strong>Output:</strong> <span class="example-io">"11:54"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"11:54"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0?:5?"</span></p>
<p><strong>Output:</strong> <span class="example-io">"09:59"</span></p>
<p><strong>Explanation:</strong> The latest 12-hour format time we can achieve by replacing <code>"?"</code> characters is <code>"09:59"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>s.length == 5</code></li>
<li><code>s[2]</code> is equal to the character <code>":"</code>.</li>
<li>All characters except <code>s[2]</code> are digits or <code>"?"</code> characters.</li>
<li>The input is generated such that there is <strong>at least</strong> one time between <code>"00:00"</code> and <code>"11:59"</code> that you can obtain after replacing the <code>"?"</code> characters.</li>
</ul>
|
String; Enumeration
|
TypeScript
|
function findLatestTime(s: string): string {
for (let h = 11; ; h--) {
for (let m = 59; m >= 0; m--) {
const t: string = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
let ok: boolean = true;
for (let i = 0; i < s.length; i++) {
if (s[i] !== '?' && s[i] !== t[i]) {
ok = false;
break;
}
}
if (ok) {
return t;
}
}
}
}
|
3,115
|
Maximum Prime Difference
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
</ul>
|
Array; Math; Number Theory
|
C++
|
class Solution {
public:
int maximumPrimeDifference(vector<int>& nums) {
for (int i = 0;; ++i) {
if (isPrime(nums[i])) {
for (int j = nums.size() - 1;; --j) {
if (isPrime(nums[j])) {
return j - i;
}
}
}
}
}
bool isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
};
|
3,115
|
Maximum Prime Difference
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
</ul>
|
Array; Math; Number Theory
|
Go
|
func maximumPrimeDifference(nums []int) int {
for i := 0; ; i++ {
if isPrime(nums[i]) {
for j := len(nums) - 1; ; j-- {
if isPrime(nums[j]) {
return j - i
}
}
}
}
}
func isPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i <= n/i; i++ {
if n%i == 0 {
return false
}
}
return true
}
|
3,115
|
Maximum Prime Difference
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
</ul>
|
Array; Math; Number Theory
|
Java
|
class Solution {
public int maximumPrimeDifference(int[] nums) {
for (int i = 0;; ++i) {
if (isPrime(nums[i])) {
for (int j = nums.length - 1;; --j) {
if (isPrime(nums[j])) {
return j - i;
}
}
}
}
}
private boolean isPrime(int x) {
if (x < 2) {
return false;
}
for (int v = 2; v * v <= x; ++v) {
if (x % v == 0) {
return false;
}
}
return true;
}
}
|
3,115
|
Maximum Prime Difference
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
</ul>
|
Array; Math; Number Theory
|
Python
|
class Solution:
def maximumPrimeDifference(self, nums: List[int]) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
for i, x in enumerate(nums):
if is_prime(x):
for j in range(len(nums) - 1, i - 1, -1):
if is_prime(nums[j]):
return j - i
|
3,115
|
Maximum Prime Difference
|
Medium
|
<p>You are given an integer array <code>nums</code>.</p>
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 3 * 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
</ul>
|
Array; Math; Number Theory
|
TypeScript
|
function maximumPrimeDifference(nums: number[]): number {
const isPrime = (x: number): boolean => {
if (x < 2) {
return false;
}
for (let i = 2; i <= x / i; i++) {
if (x % i === 0) {
return false;
}
}
return true;
};
for (let i = 0; ; ++i) {
if (isPrime(nums[i])) {
for (let j = nums.length - 1; ; --j) {
if (isPrime(nums[j])) {
return j - i;
}
}
}
}
}
|
3,116
|
Kth Smallest Amount With Single Denomination Combination
|
Hard
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>k</code>.</p>
<p>You have an infinite number of coins of each denomination. However, you are <strong>not allowed</strong> to combine coins of different denominations.</p>
<p>Return the <code>k<sup>th</sup></code> <strong>smallest</strong> amount that can be made using these coins.</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;
">coins = [3,6,9], k = 3</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> The given coins can make the following amounts:<br />
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.<br />
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.<br />
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.<br />
All of the coins combined produce: 3, 6, <u><strong>9</strong></u>, 12, 15, etc.</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;
"> coins = [5,2], k = 7</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 12 </span></p>
<p><strong>Explanation:</strong> The given coins can make the following amounts:<br />
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.<br />
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.<br />
All of the coins combined produce: 2, 4, 5, 6, 8, 10, <u><strong>12</strong></u>, 14, 15, etc.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 15</code></li>
<li><code>1 <= coins[i] <= 25</code></li>
<li><code>1 <= k <= 2 * 10<sup>9</sup></code></li>
<li><code>coins</code> contains pairwise distinct integers.</li>
</ul>
|
Bit Manipulation; Array; Math; Binary Search; Combinatorics; Number Theory
|
C++
|
class Solution {
public:
long long findKthSmallest(vector<int>& coins, int k) {
using ll = long long;
ll l = 1, r = 1e11;
int n = coins.size();
auto check = [&](ll mx) {
ll cnt = 0;
for (int i = 1; i < 1 << n; ++i) {
ll v = 1;
for (int j = 0; j < n; ++j) {
if (i >> j & 1) {
v = lcm(v, coins[j]);
if (v > mx) {
break;
}
}
}
int m = __builtin_popcount(i);
if (m & 1) {
cnt += mx / v;
} else {
cnt -= mx / v;
}
}
return cnt >= k;
};
while (l < r) {
ll mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
};
|
3,116
|
Kth Smallest Amount With Single Denomination Combination
|
Hard
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>k</code>.</p>
<p>You have an infinite number of coins of each denomination. However, you are <strong>not allowed</strong> to combine coins of different denominations.</p>
<p>Return the <code>k<sup>th</sup></code> <strong>smallest</strong> amount that can be made using these coins.</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;
">coins = [3,6,9], k = 3</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> The given coins can make the following amounts:<br />
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.<br />
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.<br />
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.<br />
All of the coins combined produce: 3, 6, <u><strong>9</strong></u>, 12, 15, etc.</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;
"> coins = [5,2], k = 7</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 12 </span></p>
<p><strong>Explanation:</strong> The given coins can make the following amounts:<br />
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.<br />
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.<br />
All of the coins combined produce: 2, 4, 5, 6, 8, 10, <u><strong>12</strong></u>, 14, 15, etc.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 15</code></li>
<li><code>1 <= coins[i] <= 25</code></li>
<li><code>1 <= k <= 2 * 10<sup>9</sup></code></li>
<li><code>coins</code> contains pairwise distinct integers.</li>
</ul>
|
Bit Manipulation; Array; Math; Binary Search; Combinatorics; Number Theory
|
Go
|
func findKthSmallest(coins []int, k int) int64 {
var r int = 1e11
n := len(coins)
ans := sort.Search(r, func(mx int) bool {
cnt := 0
for i := 1; i < 1<<n; i++ {
v := 1
for j, x := range coins {
if i>>j&1 == 1 {
v = lcm(v, x)
if v > mx {
break
}
}
}
m := bits.OnesCount(uint(i))
if m%2 == 1 {
cnt += mx / v
} else {
cnt -= mx / v
}
}
return cnt >= k
})
return int64(ans)
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func lcm(a, b int) int {
return a * b / gcd(a, b)
}
|
3,116
|
Kth Smallest Amount With Single Denomination Combination
|
Hard
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>k</code>.</p>
<p>You have an infinite number of coins of each denomination. However, you are <strong>not allowed</strong> to combine coins of different denominations.</p>
<p>Return the <code>k<sup>th</sup></code> <strong>smallest</strong> amount that can be made using these coins.</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;
">coins = [3,6,9], k = 3</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> The given coins can make the following amounts:<br />
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.<br />
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.<br />
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.<br />
All of the coins combined produce: 3, 6, <u><strong>9</strong></u>, 12, 15, etc.</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;
"> coins = [5,2], k = 7</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 12 </span></p>
<p><strong>Explanation:</strong> The given coins can make the following amounts:<br />
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.<br />
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.<br />
All of the coins combined produce: 2, 4, 5, 6, 8, 10, <u><strong>12</strong></u>, 14, 15, etc.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 15</code></li>
<li><code>1 <= coins[i] <= 25</code></li>
<li><code>1 <= k <= 2 * 10<sup>9</sup></code></li>
<li><code>coins</code> contains pairwise distinct integers.</li>
</ul>
|
Bit Manipulation; Array; Math; Binary Search; Combinatorics; Number Theory
|
Java
|
class Solution {
private int[] coins;
private int k;
public long findKthSmallest(int[] coins, int k) {
this.coins = coins;
this.k = k;
long l = 1, r = (long) 1e11;
while (l < r) {
long mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
private boolean check(long mx) {
long cnt = 0;
int n = coins.length;
for (int i = 1; i < 1 << n; ++i) {
long v = 1;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
v = lcm(v, coins[j]);
if (v > mx) {
break;
}
}
}
int m = Integer.bitCount(i);
if (m % 2 == 1) {
cnt += mx / v;
} else {
cnt -= mx / v;
}
}
return cnt >= k;
}
private long lcm(long a, long b) {
return a * b / gcd(a, b);
}
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
3,116
|
Kth Smallest Amount With Single Denomination Combination
|
Hard
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>k</code>.</p>
<p>You have an infinite number of coins of each denomination. However, you are <strong>not allowed</strong> to combine coins of different denominations.</p>
<p>Return the <code>k<sup>th</sup></code> <strong>smallest</strong> amount that can be made using these coins.</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;
">coins = [3,6,9], k = 3</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> The given coins can make the following amounts:<br />
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.<br />
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.<br />
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.<br />
All of the coins combined produce: 3, 6, <u><strong>9</strong></u>, 12, 15, etc.</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;
"> coins = [5,2], k = 7</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 12 </span></p>
<p><strong>Explanation:</strong> The given coins can make the following amounts:<br />
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.<br />
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.<br />
All of the coins combined produce: 2, 4, 5, 6, 8, 10, <u><strong>12</strong></u>, 14, 15, etc.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 15</code></li>
<li><code>1 <= coins[i] <= 25</code></li>
<li><code>1 <= k <= 2 * 10<sup>9</sup></code></li>
<li><code>coins</code> contains pairwise distinct integers.</li>
</ul>
|
Bit Manipulation; Array; Math; Binary Search; Combinatorics; Number Theory
|
Python
|
class Solution:
def findKthSmallest(self, coins: List[int], k: int) -> int:
def check(mx: int) -> bool:
cnt = 0
for i in range(1, 1 << len(coins)):
v = 1
for j, x in enumerate(coins):
if i >> j & 1:
v = lcm(v, x)
if v > mx:
break
m = i.bit_count()
if m & 1:
cnt += mx // v
else:
cnt -= mx // v
return cnt >= k
return bisect_left(range(10**11), True, key=check)
|
3,116
|
Kth Smallest Amount With Single Denomination Combination
|
Hard
|
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>k</code>.</p>
<p>You have an infinite number of coins of each denomination. However, you are <strong>not allowed</strong> to combine coins of different denominations.</p>
<p>Return the <code>k<sup>th</sup></code> <strong>smallest</strong> amount that can be made using these coins.</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;
">coins = [3,6,9], k = 3</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> The given coins can make the following amounts:<br />
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.<br />
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.<br />
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.<br />
All of the coins combined produce: 3, 6, <u><strong>9</strong></u>, 12, 15, etc.</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;
"> coins = [5,2], k = 7</span></p>
<p><strong>Output:</strong><span class="example-io" style="
font-family: Menlo,sans-serif;
font-size: 0.85rem;
"> 12 </span></p>
<p><strong>Explanation:</strong> The given coins can make the following amounts:<br />
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.<br />
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.<br />
All of the coins combined produce: 2, 4, 5, 6, 8, 10, <u><strong>12</strong></u>, 14, 15, etc.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= coins.length <= 15</code></li>
<li><code>1 <= coins[i] <= 25</code></li>
<li><code>1 <= k <= 2 * 10<sup>9</sup></code></li>
<li><code>coins</code> contains pairwise distinct integers.</li>
</ul>
|
Bit Manipulation; Array; Math; Binary Search; Combinatorics; Number Theory
|
TypeScript
|
function findKthSmallest(coins: number[], k: number): number {
let [l, r] = [1n, BigInt(1e11)];
const n = coins.length;
const check = (mx: bigint): boolean => {
let cnt = 0n;
for (let i = 1; i < 1 << n; ++i) {
let v = 1n;
for (let j = 0; j < n; ++j) {
if ((i >> j) & 1) {
v = lcm(v, BigInt(coins[j]));
if (v > mx) {
break;
}
}
}
const m = bitCount(i);
if (m & 1) {
cnt += mx / v;
} else {
cnt -= mx / v;
}
}
return cnt >= BigInt(k);
};
while (l < r) {
const mid = (l + r) >> 1n;
if (check(mid)) {
r = mid;
} else {
l = mid + 1n;
}
}
return Number(l);
}
function gcd(a: bigint, b: bigint): bigint {
return b === 0n ? a : gcd(b, a % b);
}
function lcm(a: bigint, b: bigint): bigint {
return (a * b) / gcd(a, b);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
3,117
|
Minimum Sum of Values by Dividing Array
|
Hard
|
<p>You are given two arrays <code>nums</code> and <code>andValues</code> of length <code>n</code> and <code>m</code> respectively.</p>
<p>The <strong>value</strong> of an array is equal to the <strong>last</strong> element of that array.</p>
<p>You have to divide <code>nums</code> into <code>m</code> <strong>disjoint contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> such that for the <code>i<sup>th</sup></code> subarray <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, the bitwise <code>AND</code> of the subarray elements is equal to <code>andValues[i]</code>, in other words, <code>nums[l<sub>i</sub>] & nums[l<sub>i</sub> + 1] & ... & nums[r<sub>i</sub>] == andValues[i]</code> for all <code>1 <= i <= m</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of the <strong>values</strong> of the </em><code>m</code><em> subarrays </em><code>nums</code><em> is divided into</em>. <em>If it is not possible to divide </em><code>nums</code><em> into </em><code>m</code><em> subarrays satisfying these conditions, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2], andValues = [0,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to divide <code>nums</code> is:</p>
<ol>
<li><code>[1,4]</code> as <code>1 & 4 == 0</code>.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[2]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
</ol>
<p>The sum of the values for these subarrays is <code>4 + 3 + 3 + 2 = 12</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7,7,7,5], andValues = [0,7,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">17</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three ways to divide <code>nums</code>:</p>
<ol>
<li><code>[[2,3,5],[7,7,7],[5]]</code> with the sum of the values <code>5 + 7 + 5 == 17</code>.</li>
<li><code>[[2,3,5,7],[7,7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
<li><code>[[2,3,5,7,7],[7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
</ol>
<p>The minimum possible sum of the values is <code>17</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], andValues = [2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The bitwise <code>AND</code> of the entire array <code>nums</code> is <code>0</code>. As there is no possible way to divide <code>nums</code> into a single subarray to have the bitwise <code>AND</code> of elements <code>2</code>, return <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m == andValues.length <= min(n, 10)</code></li>
<li><code>1 <= nums[i] < 10<sup>5</sup></code></li>
<li><code>0 <= andValues[j] < 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Queue; Array; Binary Search; Dynamic Programming
|
C++
|
class Solution {
public:
int minimumValueSum(vector<int>& nums, vector<int>& andValues) {
this->nums = nums;
this->andValues = andValues;
n = nums.size();
m = andValues.size();
int ans = dfs(0, 0, -1);
return ans >= inf ? -1 : ans;
}
private:
vector<int> nums;
vector<int> andValues;
int n;
int m;
const int inf = 1 << 29;
unordered_map<long long, int> f;
int dfs(int i, int j, int a) {
if (n - i < m - j) {
return inf;
}
if (j == m) {
return i == n ? 0 : inf;
}
a &= nums[i];
if (a < andValues[j]) {
return inf;
}
long long key = (long long) i << 36 | (long long) j << 32 | a;
if (f.contains(key)) {
return f[key];
}
int ans = dfs(i + 1, j, a);
if (a == andValues[j]) {
ans = min(ans, dfs(i + 1, j + 1, -1) + nums[i]);
}
return f[key] = ans;
}
};
|
3,117
|
Minimum Sum of Values by Dividing Array
|
Hard
|
<p>You are given two arrays <code>nums</code> and <code>andValues</code> of length <code>n</code> and <code>m</code> respectively.</p>
<p>The <strong>value</strong> of an array is equal to the <strong>last</strong> element of that array.</p>
<p>You have to divide <code>nums</code> into <code>m</code> <strong>disjoint contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> such that for the <code>i<sup>th</sup></code> subarray <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, the bitwise <code>AND</code> of the subarray elements is equal to <code>andValues[i]</code>, in other words, <code>nums[l<sub>i</sub>] & nums[l<sub>i</sub> + 1] & ... & nums[r<sub>i</sub>] == andValues[i]</code> for all <code>1 <= i <= m</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of the <strong>values</strong> of the </em><code>m</code><em> subarrays </em><code>nums</code><em> is divided into</em>. <em>If it is not possible to divide </em><code>nums</code><em> into </em><code>m</code><em> subarrays satisfying these conditions, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2], andValues = [0,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to divide <code>nums</code> is:</p>
<ol>
<li><code>[1,4]</code> as <code>1 & 4 == 0</code>.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[2]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
</ol>
<p>The sum of the values for these subarrays is <code>4 + 3 + 3 + 2 = 12</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7,7,7,5], andValues = [0,7,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">17</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three ways to divide <code>nums</code>:</p>
<ol>
<li><code>[[2,3,5],[7,7,7],[5]]</code> with the sum of the values <code>5 + 7 + 5 == 17</code>.</li>
<li><code>[[2,3,5,7],[7,7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
<li><code>[[2,3,5,7,7],[7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
</ol>
<p>The minimum possible sum of the values is <code>17</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], andValues = [2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The bitwise <code>AND</code> of the entire array <code>nums</code> is <code>0</code>. As there is no possible way to divide <code>nums</code> into a single subarray to have the bitwise <code>AND</code> of elements <code>2</code>, return <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m == andValues.length <= min(n, 10)</code></li>
<li><code>1 <= nums[i] < 10<sup>5</sup></code></li>
<li><code>0 <= andValues[j] < 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Queue; Array; Binary Search; Dynamic Programming
|
Go
|
func minimumValueSum(nums []int, andValues []int) int {
n, m := len(nums), len(andValues)
f := map[int]int{}
const inf int = 1 << 29
var dfs func(i, j, a int) int
dfs = func(i, j, a int) int {
if n-i < m-j {
return inf
}
if j == m {
if i == n {
return 0
}
return inf
}
a &= nums[i]
if a < andValues[j] {
return inf
}
key := i<<36 | j<<32 | a
if v, ok := f[key]; ok {
return v
}
ans := dfs(i+1, j, a)
if a == andValues[j] {
ans = min(ans, dfs(i+1, j+1, -1)+nums[i])
}
f[key] = ans
return ans
}
if ans := dfs(0, 0, -1); ans < inf {
return ans
}
return -1
}
|
3,117
|
Minimum Sum of Values by Dividing Array
|
Hard
|
<p>You are given two arrays <code>nums</code> and <code>andValues</code> of length <code>n</code> and <code>m</code> respectively.</p>
<p>The <strong>value</strong> of an array is equal to the <strong>last</strong> element of that array.</p>
<p>You have to divide <code>nums</code> into <code>m</code> <strong>disjoint contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> such that for the <code>i<sup>th</sup></code> subarray <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, the bitwise <code>AND</code> of the subarray elements is equal to <code>andValues[i]</code>, in other words, <code>nums[l<sub>i</sub>] & nums[l<sub>i</sub> + 1] & ... & nums[r<sub>i</sub>] == andValues[i]</code> for all <code>1 <= i <= m</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of the <strong>values</strong> of the </em><code>m</code><em> subarrays </em><code>nums</code><em> is divided into</em>. <em>If it is not possible to divide </em><code>nums</code><em> into </em><code>m</code><em> subarrays satisfying these conditions, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2], andValues = [0,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to divide <code>nums</code> is:</p>
<ol>
<li><code>[1,4]</code> as <code>1 & 4 == 0</code>.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[2]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
</ol>
<p>The sum of the values for these subarrays is <code>4 + 3 + 3 + 2 = 12</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7,7,7,5], andValues = [0,7,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">17</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three ways to divide <code>nums</code>:</p>
<ol>
<li><code>[[2,3,5],[7,7,7],[5]]</code> with the sum of the values <code>5 + 7 + 5 == 17</code>.</li>
<li><code>[[2,3,5,7],[7,7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
<li><code>[[2,3,5,7,7],[7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
</ol>
<p>The minimum possible sum of the values is <code>17</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], andValues = [2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The bitwise <code>AND</code> of the entire array <code>nums</code> is <code>0</code>. As there is no possible way to divide <code>nums</code> into a single subarray to have the bitwise <code>AND</code> of elements <code>2</code>, return <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m == andValues.length <= min(n, 10)</code></li>
<li><code>1 <= nums[i] < 10<sup>5</sup></code></li>
<li><code>0 <= andValues[j] < 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Queue; Array; Binary Search; Dynamic Programming
|
Java
|
class Solution {
private int[] nums;
private int[] andValues;
private final int inf = 1 << 29;
private Map<Long, Integer> f = new HashMap<>();
public int minimumValueSum(int[] nums, int[] andValues) {
this.nums = nums;
this.andValues = andValues;
int ans = dfs(0, 0, -1);
return ans >= inf ? -1 : ans;
}
private int dfs(int i, int j, int a) {
if (nums.length - i < andValues.length - j) {
return inf;
}
if (j == andValues.length) {
return i == nums.length ? 0 : inf;
}
a &= nums[i];
if (a < andValues[j]) {
return inf;
}
long key = (long) i << 36 | (long) j << 32 | a;
if (f.containsKey(key)) {
return f.get(key);
}
int ans = dfs(i + 1, j, a);
if (a == andValues[j]) {
ans = Math.min(ans, dfs(i + 1, j + 1, -1) + nums[i]);
}
f.put(key, ans);
return ans;
}
}
|
3,117
|
Minimum Sum of Values by Dividing Array
|
Hard
|
<p>You are given two arrays <code>nums</code> and <code>andValues</code> of length <code>n</code> and <code>m</code> respectively.</p>
<p>The <strong>value</strong> of an array is equal to the <strong>last</strong> element of that array.</p>
<p>You have to divide <code>nums</code> into <code>m</code> <strong>disjoint contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> such that for the <code>i<sup>th</sup></code> subarray <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, the bitwise <code>AND</code> of the subarray elements is equal to <code>andValues[i]</code>, in other words, <code>nums[l<sub>i</sub>] & nums[l<sub>i</sub> + 1] & ... & nums[r<sub>i</sub>] == andValues[i]</code> for all <code>1 <= i <= m</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of the <strong>values</strong> of the </em><code>m</code><em> subarrays </em><code>nums</code><em> is divided into</em>. <em>If it is not possible to divide </em><code>nums</code><em> into </em><code>m</code><em> subarrays satisfying these conditions, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2], andValues = [0,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to divide <code>nums</code> is:</p>
<ol>
<li><code>[1,4]</code> as <code>1 & 4 == 0</code>.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[2]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
</ol>
<p>The sum of the values for these subarrays is <code>4 + 3 + 3 + 2 = 12</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7,7,7,5], andValues = [0,7,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">17</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three ways to divide <code>nums</code>:</p>
<ol>
<li><code>[[2,3,5],[7,7,7],[5]]</code> with the sum of the values <code>5 + 7 + 5 == 17</code>.</li>
<li><code>[[2,3,5,7],[7,7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
<li><code>[[2,3,5,7,7],[7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
</ol>
<p>The minimum possible sum of the values is <code>17</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], andValues = [2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The bitwise <code>AND</code> of the entire array <code>nums</code> is <code>0</code>. As there is no possible way to divide <code>nums</code> into a single subarray to have the bitwise <code>AND</code> of elements <code>2</code>, return <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m == andValues.length <= min(n, 10)</code></li>
<li><code>1 <= nums[i] < 10<sup>5</sup></code></li>
<li><code>0 <= andValues[j] < 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Queue; Array; Binary Search; Dynamic Programming
|
Python
|
class Solution:
def minimumValueSum(self, nums: List[int], andValues: List[int]) -> int:
@cache
def dfs(i: int, j: int, a: int) -> int:
if n - i < m - j:
return inf
if j == m:
return 0 if i == n else inf
a &= nums[i]
if a < andValues[j]:
return inf
ans = dfs(i + 1, j, a)
if a == andValues[j]:
ans = min(ans, dfs(i + 1, j + 1, -1) + nums[i])
return ans
n, m = len(nums), len(andValues)
ans = dfs(0, 0, -1)
return ans if ans < inf else -1
|
3,117
|
Minimum Sum of Values by Dividing Array
|
Hard
|
<p>You are given two arrays <code>nums</code> and <code>andValues</code> of length <code>n</code> and <code>m</code> respectively.</p>
<p>The <strong>value</strong> of an array is equal to the <strong>last</strong> element of that array.</p>
<p>You have to divide <code>nums</code> into <code>m</code> <strong>disjoint contiguous</strong> <span data-keyword="subarray-nonempty">subarrays</span> such that for the <code>i<sup>th</sup></code> subarray <code>[l<sub>i</sub>, r<sub>i</sub>]</code>, the bitwise <code>AND</code> of the subarray elements is equal to <code>andValues[i]</code>, in other words, <code>nums[l<sub>i</sub>] & nums[l<sub>i</sub> + 1] & ... & nums[r<sub>i</sub>] == andValues[i]</code> for all <code>1 <= i <= m</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of the <strong>values</strong> of the </em><code>m</code><em> subarrays </em><code>nums</code><em> is divided into</em>. <em>If it is not possible to divide </em><code>nums</code><em> into </em><code>m</code><em> subarrays satisfying these conditions, return</em> <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2], andValues = [0,3,3,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible way to divide <code>nums</code> is:</p>
<ol>
<li><code>[1,4]</code> as <code>1 & 4 == 0</code>.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[3]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
<li><code>[2]</code> as the bitwise <code>AND</code> of a single element subarray is that element itself.</li>
</ol>
<p>The sum of the values for these subarrays is <code>4 + 3 + 3 + 2 = 12</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,5,7,7,7,5], andValues = [0,7,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">17</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three ways to divide <code>nums</code>:</p>
<ol>
<li><code>[[2,3,5],[7,7,7],[5]]</code> with the sum of the values <code>5 + 7 + 5 == 17</code>.</li>
<li><code>[[2,3,5,7],[7,7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
<li><code>[[2,3,5,7,7],[7],[5]]</code> with the sum of the values <code>7 + 7 + 5 == 19</code>.</li>
</ol>
<p>The minimum possible sum of the values is <code>17</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], andValues = [2]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>The bitwise <code>AND</code> of the entire array <code>nums</code> is <code>0</code>. As there is no possible way to divide <code>nums</code> into a single subarray to have the bitwise <code>AND</code> of elements <code>2</code>, return <code>-1</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>4</sup></code></li>
<li><code>1 <= m == andValues.length <= min(n, 10)</code></li>
<li><code>1 <= nums[i] < 10<sup>5</sup></code></li>
<li><code>0 <= andValues[j] < 10<sup>5</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Queue; Array; Binary Search; Dynamic Programming
|
TypeScript
|
function minimumValueSum(nums: number[], andValues: number[]): number {
const [n, m] = [nums.length, andValues.length];
const f: Map<bigint, number> = new Map();
const dfs = (i: number, j: number, a: number): number => {
if (n - i < m - j) {
return Infinity;
}
if (j === m) {
return i === n ? 0 : Infinity;
}
a &= nums[i];
if (a < andValues[j]) {
return Infinity;
}
const key = (BigInt(i) << 36n) | (BigInt(j) << 32n) | BigInt(a);
if (f.has(key)) {
return f.get(key)!;
}
let ans = dfs(i + 1, j, a);
if (a === andValues[j]) {
ans = Math.min(ans, dfs(i + 1, j + 1, -1) + nums[i]);
}
f.set(key, ans);
return ans;
};
const ans = dfs(0, 0, -1);
return ans >= Infinity ? -1 : ans;
}
|
3,118
|
Friday Purchase III
|
Medium
|
<p>Table: <code>Purchases</code></p>
<pre>
+---------------+------+
| Column Name | Type |
+---------------+------+
| user_id | int |
| purchase_date | date |
| amount_spend | int |
+---------------+------+
(user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table.
purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates.
Each row contains user_id, purchase_date, and amount_spend.
</pre>
<p>Table: <code>Users</code></p>
<pre>
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| membership | enum |
+-------------+------+
user_id is the primary key for this table.
membership is an ENUM (category) type of ('Standard', 'Premium', 'VIP').
Each row of this table indicates the user_id, membership type.
</pre>
<p>Write a solution to calculate the <strong>total spending</strong> by <code>Premium</code> and <code>VIP</code> members on <strong>each Friday of every week</strong> in November 2023. If there are <strong>no purchases</strong> on a <strong>particular Friday</strong> by <code>Premium</code> or <code>VIP</code> members, it should be considered as <code>0</code>.</p>
<p>Return <em>the result table</em> <em>ordered by week of the month, and </em><code>membership</code><em> in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Purchases table:</p>
<pre class="example-io">
+---------+---------------+--------------+
| user_id | purchase_date | amount_spend |
+---------+---------------+--------------+
| 11 | 2023-11-03 | 1126 |
| 15 | 2023-11-10 | 7473 |
| 17 | 2023-11-17 | 2414 |
| 12 | 2023-11-24 | 9692 |
| 8 | 2023-11-24 | 5117 |
| 1 | 2023-11-24 | 5241 |
| 10 | 2023-11-22 | 8266 |
| 13 | 2023-11-21 | 12000 |
+---------+---------------+--------------+
</pre>
<p>Users table:</p>
<pre class="example-io">
+---------+------------+
| user_id | membership |
+---------+------------+
| 11 | Premium |
| 15 | VIP |
| 17 | Standard |
| 12 | VIP |
| 8 | Premium |
| 1 | VIP |
| 10 | Standard |
| 13 | Premium |
+---------+------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+---------------+-------------+--------------+
| week_of_month | membership | total_amount |
+---------------+-------------+--------------+
| 1 | Premium | 1126 |
| 1 | VIP | 0 |
| 2 | Premium | 0 |
| 2 | VIP | 7473 |
| 3 | Premium | 0 |
| 3 | VIP | 0 |
| 4 | Premium | 5117 |
| 4 | VIP | 14933 |
+---------------+-------------+--------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>During the first week of November 2023, a transaction occurred on Friday, 2023-11-03, by a Premium member amounting to $1,126. No transactions were made by VIP members on this day, resulting in a value of 0.</li>
<li>For the second week of November 2023, there was a transaction on Friday, 2023-11-10, and it was made by a VIP member, amounting to $7,473. Since there were no purchases by Premium members that Friday, the output shows 0 for Premium members.</li>
<li>Similarly, during the third week of November 2023, no transactions by Premium or VIP members occurred on Friday, 2023-11-17, which shows 0 for both categories in this week.</li>
<li>In the fourth week of November 2023, transactions occurred on Friday, 2023-11-24, involving one Premium member purchase of $5,117 and VIP member purchases totaling $14,933 ($9,692 from one and $5,241 from another).</li>
</ul>
<p><strong>Note:</strong> The output table is ordered by week_of_month and membership in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH RECURSIVE
T AS (
SELECT 1 AS week_of_month
UNION
SELECT week_of_month + 1
FROM T
WHERE week_of_month < 4
),
M AS (
SELECT 'Premium' AS membership
UNION
SELECT 'VIP'
),
P AS (
SELECT CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month, membership, amount_spend
FROM
Purchases
JOIN Users USING (user_id)
WHERE DAYOFWEEK(purchase_date) = 6
)
SELECT week_of_month, membership, IFNULL(SUM(amount_spend), 0) AS total_amount
FROM
T
JOIN M
LEFT JOIN P USING (week_of_month, membership)
GROUP BY 1, 2
ORDER BY 1, 2;
|
3,119
|
Maximum Number of Potholes That Can Be Fixed
|
Medium
|
<p>You are given a string <code>road</code>, consisting only of characters <code>"x"</code> and <code>"."</code>, where each <code>"x"</code> denotes a <em>pothole</em> and each <code>"."</code> denotes a smooth road, and an integer <code>budget</code>.</p>
<p>In one repair operation, you can repair <code>n</code> <strong>consecutive</strong> potholes for a price of <code>n + 1</code>.</p>
<p>Return the <strong>maximum</strong> number of potholes that can be fixed such that the sum of the prices of all of the fixes <strong>doesn't go over</strong> the given budget.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">road = "..", budget = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are no potholes to be fixed.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">road = "..xxxxx", budget = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>We fix the first three potholes (they are consecutive). The budget needed for this task is <code>3 + 1 = 4</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">road = "x.x.xxx...x", budget = 14</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>We can fix all the potholes. The total cost would be <code>(1 + 1) + (1 + 1) + (3 + 1) + (1 + 1) = 10</code> which is within our budget of 14.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= road.length <= 10<sup>5</sup></code></li>
<li><code>1 <= budget <= 10<sup>5</sup> + 1</code></li>
<li><code>road</code> consists only of characters <code>'.'</code> and <code>'x'</code>.</li>
</ul>
|
Greedy; String; Sorting
|
C++
|
class Solution {
public:
int maxPotholes(string road, int budget) {
road.push_back('.');
int n = road.size();
vector<int> cnt(n);
int k = 0;
for (char& c : road) {
if (c == 'x') {
++k;
} else if (k) {
++cnt[k];
k = 0;
}
}
int ans = 0;
for (k = n - 1; k && budget; --k) {
int t = min(budget / (k + 1), cnt[k]);
ans += t * k;
budget -= t * (k + 1);
cnt[k - 1] += cnt[k] - t;
}
return ans;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.