id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
2,526
|
Find Consecutive Integers from a Data Stream
|
Medium
|
<p>For a stream of integers, implement a data structure that checks if the last <code>k</code> integers parsed in the stream are <strong>equal</strong> to <code>value</code>.</p>
<p>Implement the <strong>DataStream</strong> class:</p>
<ul>
<li><code>DataStream(int value, int k)</code> Initializes the object with an empty integer stream and the two integers <code>value</code> and <code>k</code>.</li>
<li><code>boolean consec(int num)</code> Adds <code>num</code> to the stream of integers. Returns <code>true</code> if the last <code>k</code> integers are equal to <code>value</code>, and <code>false</code> otherwise. If there are less than <code>k</code> integers, the condition does not hold true, so returns <code>false</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["DataStream", "consec", "consec", "consec", "consec"]
[[4, 3], [4], [4], [4], [3]]
<strong>Output</strong>
[null, false, false, true, false]
<strong>Explanation</strong>
DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3
dataStream.consec(4); // Only 1 integer is parsed, so returns False.
dataStream.consec(4); // Only 2 integers are parsed.
// Since 2 is less than k, returns False.
dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True.
dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3].
// Since 3 is not equal to value, it returns False.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= value, num <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>5</sup></code></li>
<li>At most <code>10<sup>5</sup></code> calls will be made to <code>consec</code>.</li>
</ul>
|
Design; Queue; Hash Table; Counting; Data Stream
|
TypeScript
|
class DataStream {
private val: number;
private k: number;
private cnt: number;
constructor(value: number, k: number) {
this.val = value;
this.k = k;
this.cnt = 0;
}
consec(num: number): boolean {
this.cnt = this.val === num ? this.cnt + 1 : 0;
return this.cnt >= this.k;
}
}
/**
* Your DataStream object will be instantiated and called as such:
* var obj = new DataStream(value, k)
* var param_1 = obj.consec(num)
*/
|
2,527
|
Find Xor-Beauty of Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>The <strong>effective value</strong> of three indices <code>i</code>, <code>j</code>, and <code>k</code> is defined as <code>((nums[i] | nums[j]) & nums[k])</code>.</p>
<p>The <strong>xor-beauty</strong> of the array is the XORing of <strong>the effective values of all the possible triplets</strong> of indices <code>(i, j, k)</code> where <code>0 <= i, j, k < n</code>.</p>
<p>Return <em>the xor-beauty of</em> <code>nums</code>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li><code>val1 | val2</code> is bitwise OR of <code>val1</code> and <code>val2</code>.</li>
<li><code>val1 & val2</code> is bitwise AND of <code>val1</code> and <code>val2</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [15,45,20,2,34,35,5,44,32,30]
<strong>Output:</strong> 34
<strong>Explanation:</strong> <code>The xor-beauty of the given array is 34.</code>
</pre>
<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>
|
Bit Manipulation; Array; Math
|
C++
|
class Solution {
public:
int xorBeauty(vector<int>& nums) {
int ans = 0;
for (auto& x : nums) {
ans ^= x;
}
return ans;
}
};
|
2,527
|
Find Xor-Beauty of Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>The <strong>effective value</strong> of three indices <code>i</code>, <code>j</code>, and <code>k</code> is defined as <code>((nums[i] | nums[j]) & nums[k])</code>.</p>
<p>The <strong>xor-beauty</strong> of the array is the XORing of <strong>the effective values of all the possible triplets</strong> of indices <code>(i, j, k)</code> where <code>0 <= i, j, k < n</code>.</p>
<p>Return <em>the xor-beauty of</em> <code>nums</code>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li><code>val1 | val2</code> is bitwise OR of <code>val1</code> and <code>val2</code>.</li>
<li><code>val1 & val2</code> is bitwise AND of <code>val1</code> and <code>val2</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [15,45,20,2,34,35,5,44,32,30]
<strong>Output:</strong> 34
<strong>Explanation:</strong> <code>The xor-beauty of the given array is 34.</code>
</pre>
<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>
|
Bit Manipulation; Array; Math
|
Go
|
func xorBeauty(nums []int) (ans int) {
for _, x := range nums {
ans ^= x
}
return
}
|
2,527
|
Find Xor-Beauty of Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>The <strong>effective value</strong> of three indices <code>i</code>, <code>j</code>, and <code>k</code> is defined as <code>((nums[i] | nums[j]) & nums[k])</code>.</p>
<p>The <strong>xor-beauty</strong> of the array is the XORing of <strong>the effective values of all the possible triplets</strong> of indices <code>(i, j, k)</code> where <code>0 <= i, j, k < n</code>.</p>
<p>Return <em>the xor-beauty of</em> <code>nums</code>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li><code>val1 | val2</code> is bitwise OR of <code>val1</code> and <code>val2</code>.</li>
<li><code>val1 & val2</code> is bitwise AND of <code>val1</code> and <code>val2</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [15,45,20,2,34,35,5,44,32,30]
<strong>Output:</strong> 34
<strong>Explanation:</strong> <code>The xor-beauty of the given array is 34.</code>
</pre>
<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>
|
Bit Manipulation; Array; Math
|
Java
|
class Solution {
public int xorBeauty(int[] nums) {
int ans = 0;
for (int x : nums) {
ans ^= x;
}
return ans;
}
}
|
2,527
|
Find Xor-Beauty of Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>The <strong>effective value</strong> of three indices <code>i</code>, <code>j</code>, and <code>k</code> is defined as <code>((nums[i] | nums[j]) & nums[k])</code>.</p>
<p>The <strong>xor-beauty</strong> of the array is the XORing of <strong>the effective values of all the possible triplets</strong> of indices <code>(i, j, k)</code> where <code>0 <= i, j, k < n</code>.</p>
<p>Return <em>the xor-beauty of</em> <code>nums</code>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li><code>val1 | val2</code> is bitwise OR of <code>val1</code> and <code>val2</code>.</li>
<li><code>val1 & val2</code> is bitwise AND of <code>val1</code> and <code>val2</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [15,45,20,2,34,35,5,44,32,30]
<strong>Output:</strong> 34
<strong>Explanation:</strong> <code>The xor-beauty of the given array is 34.</code>
</pre>
<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>
|
Bit Manipulation; Array; Math
|
Python
|
class Solution:
def xorBeauty(self, nums: List[int]) -> int:
return reduce(xor, nums)
|
2,527
|
Find Xor-Beauty of Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p>
<p>The <strong>effective value</strong> of three indices <code>i</code>, <code>j</code>, and <code>k</code> is defined as <code>((nums[i] | nums[j]) & nums[k])</code>.</p>
<p>The <strong>xor-beauty</strong> of the array is the XORing of <strong>the effective values of all the possible triplets</strong> of indices <code>(i, j, k)</code> where <code>0 <= i, j, k < n</code>.</p>
<p>Return <em>the xor-beauty of</em> <code>nums</code>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li><code>val1 | val2</code> is bitwise OR of <code>val1</code> and <code>val2</code>.</li>
<li><code>val1 & val2</code> is bitwise AND of <code>val1</code> and <code>val2</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4]
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [15,45,20,2,34,35,5,44,32,30]
<strong>Output:</strong> 34
<strong>Explanation:</strong> <code>The xor-beauty of the given array is 34.</code>
</pre>
<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>
|
Bit Manipulation; Array; Math
|
TypeScript
|
function xorBeauty(nums: number[]): number {
return nums.reduce((acc, cur) => acc ^ cur, 0);
}
|
2,528
|
Maximize the Minimum Powered City
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>stations</code> of length <code>n</code>, where <code>stations[i]</code> represents the number of power stations in the <code>i<sup>th</sup></code> city.</p>
<p>Each power station can provide power to every city in a fixed <strong>range</strong>. In other words, if the range is denoted by <code>r</code>, then a power station at city <code>i</code> can provide power to all cities <code>j</code> such that <code>|i - j| <= r</code> and <code>0 <= i, j <= n - 1</code>.</p>
<ul>
<li>Note that <code>|x|</code> denotes <strong>absolute</strong> value. For example, <code>|7 - 5| = 2</code> and <code>|3 - 10| = 7</code>.</li>
</ul>
<p>The <strong>power</strong> of a city is the total number of power stations it is being provided power from.</p>
<p>The government has sanctioned building <code>k</code> more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.</p>
<p>Given the two integers <code>r</code> and <code>k</code>, return <em>the <strong>maximum possible minimum power</strong> of a city, if the additional power stations are built optimally.</em></p>
<p><strong>Note</strong> that you can build the <code>k</code> power stations in multiple cities.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stations = [1,2,4,5,0], r = 1, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong>
One of the optimal ways is to install both the power stations at city 1.
So stations will become [1,4,4,5,0].
- City 0 is provided by 1 + 4 = 5 power stations.
- City 1 is provided by 1 + 4 + 4 = 9 power stations.
- City 2 is provided by 4 + 4 + 5 = 13 power stations.
- City 3 is provided by 5 + 4 = 9 power stations.
- City 4 is provided by 5 + 0 = 5 power stations.
So the minimum power of a city is 5.
Since it is not possible to obtain a larger power, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stations = [4,4,4,4], r = 0, k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong>
It can be proved that we cannot make the minimum power of a city greater than 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == stations.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= stations[i] <= 10<sup>5</sup></code></li>
<li><code>0 <= r <= n - 1</code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Queue; Array; Binary Search; Prefix Sum; Sliding Window
|
C++
|
class Solution {
public:
long long maxPower(vector<int>& stations, int r, int k) {
int n = stations.size();
long d[n + 1];
memset(d, 0, sizeof d);
for (int i = 0; i < n; ++i) {
int left = max(0, i - r), right = min(i + r, n - 1);
d[left] += stations[i];
d[right + 1] -= stations[i];
}
long s[n + 1];
s[0] = d[0];
for (int i = 1; i < n + 1; ++i) {
s[i] = s[i - 1] + d[i];
}
auto check = [&](long x, int k) {
memset(d, 0, sizeof d);
long t = 0;
for (int i = 0; i < n; ++i) {
t += d[i];
long dist = x - (s[i] + t);
if (dist > 0) {
if (k < dist) {
return false;
}
k -= dist;
int j = min(i + r, n - 1);
int left = max(0, j - r), right = min(j + r, n - 1);
d[left] += dist;
d[right + 1] -= dist;
t += dist;
}
}
return true;
};
long left = 0, right = 1e12;
while (left < right) {
long mid = (left + right + 1) >> 1;
if (check(mid, k)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
};
|
2,528
|
Maximize the Minimum Powered City
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>stations</code> of length <code>n</code>, where <code>stations[i]</code> represents the number of power stations in the <code>i<sup>th</sup></code> city.</p>
<p>Each power station can provide power to every city in a fixed <strong>range</strong>. In other words, if the range is denoted by <code>r</code>, then a power station at city <code>i</code> can provide power to all cities <code>j</code> such that <code>|i - j| <= r</code> and <code>0 <= i, j <= n - 1</code>.</p>
<ul>
<li>Note that <code>|x|</code> denotes <strong>absolute</strong> value. For example, <code>|7 - 5| = 2</code> and <code>|3 - 10| = 7</code>.</li>
</ul>
<p>The <strong>power</strong> of a city is the total number of power stations it is being provided power from.</p>
<p>The government has sanctioned building <code>k</code> more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.</p>
<p>Given the two integers <code>r</code> and <code>k</code>, return <em>the <strong>maximum possible minimum power</strong> of a city, if the additional power stations are built optimally.</em></p>
<p><strong>Note</strong> that you can build the <code>k</code> power stations in multiple cities.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stations = [1,2,4,5,0], r = 1, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong>
One of the optimal ways is to install both the power stations at city 1.
So stations will become [1,4,4,5,0].
- City 0 is provided by 1 + 4 = 5 power stations.
- City 1 is provided by 1 + 4 + 4 = 9 power stations.
- City 2 is provided by 4 + 4 + 5 = 13 power stations.
- City 3 is provided by 5 + 4 = 9 power stations.
- City 4 is provided by 5 + 0 = 5 power stations.
So the minimum power of a city is 5.
Since it is not possible to obtain a larger power, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stations = [4,4,4,4], r = 0, k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong>
It can be proved that we cannot make the minimum power of a city greater than 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == stations.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= stations[i] <= 10<sup>5</sup></code></li>
<li><code>0 <= r <= n - 1</code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Queue; Array; Binary Search; Prefix Sum; Sliding Window
|
Go
|
func maxPower(stations []int, r int, k int) int64 {
n := len(stations)
d := make([]int, n+1)
s := make([]int, n+1)
for i, v := range stations {
left, right := max(0, i-r), min(i+r, n-1)
d[left] += v
d[right+1] -= v
}
s[0] = d[0]
for i := 1; i < n+1; i++ {
s[i] = s[i-1] + d[i]
}
check := func(x, k int) bool {
d := make([]int, n+1)
t := 0
for i := range stations {
t += d[i]
dist := x - (s[i] + t)
if dist > 0 {
if k < dist {
return false
}
k -= dist
j := min(i+r, n-1)
left, right := max(0, j-r), min(j+r, n-1)
d[left] += dist
d[right+1] -= dist
t += dist
}
}
return true
}
left, right := 0, 1<<40
for left < right {
mid := (left + right + 1) >> 1
if check(mid, k) {
left = mid
} else {
right = mid - 1
}
}
return int64(left)
}
|
2,528
|
Maximize the Minimum Powered City
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>stations</code> of length <code>n</code>, where <code>stations[i]</code> represents the number of power stations in the <code>i<sup>th</sup></code> city.</p>
<p>Each power station can provide power to every city in a fixed <strong>range</strong>. In other words, if the range is denoted by <code>r</code>, then a power station at city <code>i</code> can provide power to all cities <code>j</code> such that <code>|i - j| <= r</code> and <code>0 <= i, j <= n - 1</code>.</p>
<ul>
<li>Note that <code>|x|</code> denotes <strong>absolute</strong> value. For example, <code>|7 - 5| = 2</code> and <code>|3 - 10| = 7</code>.</li>
</ul>
<p>The <strong>power</strong> of a city is the total number of power stations it is being provided power from.</p>
<p>The government has sanctioned building <code>k</code> more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.</p>
<p>Given the two integers <code>r</code> and <code>k</code>, return <em>the <strong>maximum possible minimum power</strong> of a city, if the additional power stations are built optimally.</em></p>
<p><strong>Note</strong> that you can build the <code>k</code> power stations in multiple cities.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stations = [1,2,4,5,0], r = 1, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong>
One of the optimal ways is to install both the power stations at city 1.
So stations will become [1,4,4,5,0].
- City 0 is provided by 1 + 4 = 5 power stations.
- City 1 is provided by 1 + 4 + 4 = 9 power stations.
- City 2 is provided by 4 + 4 + 5 = 13 power stations.
- City 3 is provided by 5 + 4 = 9 power stations.
- City 4 is provided by 5 + 0 = 5 power stations.
So the minimum power of a city is 5.
Since it is not possible to obtain a larger power, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stations = [4,4,4,4], r = 0, k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong>
It can be proved that we cannot make the minimum power of a city greater than 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == stations.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= stations[i] <= 10<sup>5</sup></code></li>
<li><code>0 <= r <= n - 1</code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Queue; Array; Binary Search; Prefix Sum; Sliding Window
|
Java
|
class Solution {
private long[] s;
private long[] d;
private int n;
public long maxPower(int[] stations, int r, int k) {
n = stations.length;
d = new long[n + 1];
s = new long[n + 1];
for (int i = 0; i < n; ++i) {
int left = Math.max(0, i - r), right = Math.min(i + r, n - 1);
d[left] += stations[i];
d[right + 1] -= stations[i];
}
s[0] = d[0];
for (int i = 1; i < n + 1; ++i) {
s[i] = s[i - 1] + d[i];
}
long left = 0, right = 1l << 40;
while (left < right) {
long mid = (left + right + 1) >>> 1;
if (check(mid, r, k)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
private boolean check(long x, int r, int k) {
Arrays.fill(d, 0);
long t = 0;
for (int i = 0; i < n; ++i) {
t += d[i];
long dist = x - (s[i] + t);
if (dist > 0) {
if (k < dist) {
return false;
}
k -= dist;
int j = Math.min(i + r, n - 1);
int left = Math.max(0, j - r), right = Math.min(j + r, n - 1);
d[left] += dist;
d[right + 1] -= dist;
t += dist;
}
}
return true;
}
}
|
2,528
|
Maximize the Minimum Powered City
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>stations</code> of length <code>n</code>, where <code>stations[i]</code> represents the number of power stations in the <code>i<sup>th</sup></code> city.</p>
<p>Each power station can provide power to every city in a fixed <strong>range</strong>. In other words, if the range is denoted by <code>r</code>, then a power station at city <code>i</code> can provide power to all cities <code>j</code> such that <code>|i - j| <= r</code> and <code>0 <= i, j <= n - 1</code>.</p>
<ul>
<li>Note that <code>|x|</code> denotes <strong>absolute</strong> value. For example, <code>|7 - 5| = 2</code> and <code>|3 - 10| = 7</code>.</li>
</ul>
<p>The <strong>power</strong> of a city is the total number of power stations it is being provided power from.</p>
<p>The government has sanctioned building <code>k</code> more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.</p>
<p>Given the two integers <code>r</code> and <code>k</code>, return <em>the <strong>maximum possible minimum power</strong> of a city, if the additional power stations are built optimally.</em></p>
<p><strong>Note</strong> that you can build the <code>k</code> power stations in multiple cities.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stations = [1,2,4,5,0], r = 1, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong>
One of the optimal ways is to install both the power stations at city 1.
So stations will become [1,4,4,5,0].
- City 0 is provided by 1 + 4 = 5 power stations.
- City 1 is provided by 1 + 4 + 4 = 9 power stations.
- City 2 is provided by 4 + 4 + 5 = 13 power stations.
- City 3 is provided by 5 + 4 = 9 power stations.
- City 4 is provided by 5 + 0 = 5 power stations.
So the minimum power of a city is 5.
Since it is not possible to obtain a larger power, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stations = [4,4,4,4], r = 0, k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong>
It can be proved that we cannot make the minimum power of a city greater than 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == stations.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= stations[i] <= 10<sup>5</sup></code></li>
<li><code>0 <= r <= n - 1</code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Queue; Array; Binary Search; Prefix Sum; Sliding Window
|
Python
|
class Solution:
def maxPower(self, stations: List[int], r: int, k: int) -> int:
def check(x, k):
d = [0] * (n + 1)
t = 0
for i in range(n):
t += d[i]
dist = x - (s[i] + t)
if dist > 0:
if k < dist:
return False
k -= dist
j = min(i + r, n - 1)
left, right = max(0, j - r), min(j + r, n - 1)
d[left] += dist
d[right + 1] -= dist
t += dist
return True
n = len(stations)
d = [0] * (n + 1)
for i, v in enumerate(stations):
left, right = max(0, i - r), min(i + r, n - 1)
d[left] += v
d[right + 1] -= v
s = list(accumulate(d))
left, right = 0, 1 << 40
while left < right:
mid = (left + right + 1) >> 1
if check(mid, k):
left = mid
else:
right = mid - 1
return left
|
2,528
|
Maximize the Minimum Powered City
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>stations</code> of length <code>n</code>, where <code>stations[i]</code> represents the number of power stations in the <code>i<sup>th</sup></code> city.</p>
<p>Each power station can provide power to every city in a fixed <strong>range</strong>. In other words, if the range is denoted by <code>r</code>, then a power station at city <code>i</code> can provide power to all cities <code>j</code> such that <code>|i - j| <= r</code> and <code>0 <= i, j <= n - 1</code>.</p>
<ul>
<li>Note that <code>|x|</code> denotes <strong>absolute</strong> value. For example, <code>|7 - 5| = 2</code> and <code>|3 - 10| = 7</code>.</li>
</ul>
<p>The <strong>power</strong> of a city is the total number of power stations it is being provided power from.</p>
<p>The government has sanctioned building <code>k</code> more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.</p>
<p>Given the two integers <code>r</code> and <code>k</code>, return <em>the <strong>maximum possible minimum power</strong> of a city, if the additional power stations are built optimally.</em></p>
<p><strong>Note</strong> that you can build the <code>k</code> power stations in multiple cities.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stations = [1,2,4,5,0], r = 1, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong>
One of the optimal ways is to install both the power stations at city 1.
So stations will become [1,4,4,5,0].
- City 0 is provided by 1 + 4 = 5 power stations.
- City 1 is provided by 1 + 4 + 4 = 9 power stations.
- City 2 is provided by 4 + 4 + 5 = 13 power stations.
- City 3 is provided by 5 + 4 = 9 power stations.
- City 4 is provided by 5 + 0 = 5 power stations.
So the minimum power of a city is 5.
Since it is not possible to obtain a larger power, we return 5.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stations = [4,4,4,4], r = 0, k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong>
It can be proved that we cannot make the minimum power of a city greater than 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == stations.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= stations[i] <= 10<sup>5</sup></code></li>
<li><code>0 <= r <= n - 1</code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Queue; Array; Binary Search; Prefix Sum; Sliding Window
|
TypeScript
|
function maxPower(stations: number[], r: number, k: number): number {
function check(x: bigint, k: bigint): boolean {
d.fill(0n);
let t = 0n;
for (let i = 0; i < n; ++i) {
t += d[i];
const dist = x - (s[i] + t);
if (dist > 0) {
if (k < dist) {
return false;
}
k -= dist;
const j = Math.min(i + r, n - 1);
const left = Math.max(0, j - r);
const right = Math.min(j + r, n - 1);
d[left] += dist;
d[right + 1] -= dist;
t += dist;
}
}
return true;
}
const n = stations.length;
const d: bigint[] = new Array(n + 1).fill(0n);
const s: bigint[] = new Array(n + 1).fill(0n);
for (let i = 0; i < n; ++i) {
const left = Math.max(0, i - r);
const right = Math.min(i + r, n - 1);
d[left] += BigInt(stations[i]);
d[right + 1] -= BigInt(stations[i]);
}
s[0] = d[0];
for (let i = 1; i < n + 1; ++i) {
s[i] = s[i - 1] + d[i];
}
let left = 0n,
right = 1n << 40n;
while (left < right) {
const mid = (left + right + 1n) >> 1n;
if (check(mid, BigInt(k))) {
left = mid;
} else {
right = mid - 1n;
}
}
return Number(left);
}
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
C
|
#define max(a, b) (a > b ? a : b)
int maximumCount(int* nums, int numsSize) {
int a = 0, b = 0;
for (int i = 0; i < numsSize; ++i) {
if (nums[i] > 0) {
++a;
} else if (nums[i] < 0) {
++b;
}
}
return max(a, b);
}
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
C++
|
class Solution {
public:
int maximumCount(vector<int>& nums) {
int a = 0, b = 0;
for (int x : nums) {
if (x > 0) {
++a;
} else if (x < 0) {
++b;
}
}
return max(a, b);
}
};
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
Go
|
func maximumCount(nums []int) int {
var a, b int
for _, x := range nums {
if x > 0 {
a++
} else if x < 0 {
b++
}
}
return max(a, b)
}
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
Java
|
class Solution {
public int maximumCount(int[] nums) {
int a = 0, b = 0;
for (int x : nums) {
if (x > 0) {
++a;
} else if (x < 0) {
++b;
}
}
return Math.max(a, b);
}
}
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
Python
|
class Solution:
def maximumCount(self, nums: List[int]) -> int:
a = sum(x > 0 for x in nums)
b = sum(x < 0 for x in nums)
return max(a, b)
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
Rust
|
impl Solution {
pub fn maximum_count(nums: Vec<i32>) -> i32 {
let mut a = 0;
let mut b = 0;
for x in nums {
if x > 0 {
a += 1;
} else if x < 0 {
b += 1;
}
}
std::cmp::max(a, b)
}
}
|
2,529
|
Maximum Count of Positive Integer and Negative Integer
|
Easy
|
<p>Given an array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>the maximum between the number of positive integers and the number of negative integers.</em></p>
<ul>
<li>In other words, if the number of positive integers in <code>nums</code> is <code>pos</code> and the number of negative integers is <code>neg</code>, then return the maximum of <code>pos</code> and <code>neg</code>.</li>
</ul>
<p><strong>Note</strong> that <code>0</code> is neither positive nor negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-1,-1,1,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-3,-2,-1,0,0,1,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 2 positive integers and 3 negative integers. The maximum count among them is 3.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,20,66,1314]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 positive integers and 0 negative integers. The maximum count among them is 4.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>-2000 <= nums[i] <= 2000</code></li>
<li><code>nums</code> is sorted in a <strong>non-decreasing order</strong>.</li>
</ul>
<p> </p>
<p><strong>Follow up:</strong> Can you solve the problem in <code>O(log(n))</code> time complexity?</p>
|
Array; Binary Search; Counting
|
TypeScript
|
function maximumCount(nums: number[]): number {
let [a, b] = [0, 0];
for (const x of nums) {
if (x > 0) {
++a;
} else if (x < 0) {
++b;
}
}
return Math.max(a, b);
}
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long maxKelements(vector<int>& nums, int k) {
priority_queue<int> pq(nums.begin(), nums.end());
long long ans = 0;
while (k--) {
int v = pq.top();
pq.pop();
ans += v;
pq.push((v + 2) / 3);
}
return ans;
}
};
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Go
|
func maxKelements(nums []int, k int) (ans int64) {
h := &hp{nums}
heap.Init(h)
for ; k > 0; k-- {
v := h.pop()
ans += int64(v)
h.push((v + 2) / 3)
}
return
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Java
|
class Solution {
public long maxKelements(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for (int v : nums) {
pq.offer(v);
}
long ans = 0;
while (k-- > 0) {
int v = pq.poll();
ans += v;
pq.offer((v + 2) / 3);
}
return ans;
}
}
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Python
|
class Solution:
def maxKelements(self, nums: List[int], k: int) -> int:
h = [-v for v in nums]
heapify(h)
ans = 0
for _ in range(k):
v = -heappop(h)
ans += v
heappush(h, -(ceil(v / 3)))
return ans
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Rust
|
use std::collections::BinaryHeap;
impl Solution {
pub fn max_kelements(nums: Vec<i32>, k: i32) -> i64 {
let mut pq = BinaryHeap::from(nums);
let mut ans = 0;
let mut k = k;
while k > 0 {
if let Some(v) = pq.pop() {
ans += v as i64;
pq.push((v + 2) / 3);
k -= 1;
}
}
ans
}
}
|
2,530
|
Maximal Score After Applying K Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. You have a <strong>starting score</strong> of <code>0</code>.</p>
<p>In one <strong>operation</strong>:</p>
<ol>
<li>choose an index <code>i</code> such that <code>0 <= i < nums.length</code>,</li>
<li>increase your <strong>score</strong> by <code>nums[i]</code>, and</li>
<li>replace <code>nums[i]</code> with <code>ceil(nums[i] / 3)</code>.</li>
</ol>
<p>Return <em>the maximum possible <strong>score</strong> you can attain after applying <strong>exactly</strong></em> <code>k</code> <em>operations</em>.</p>
<p>The ceiling function <code>ceil(val)</code> is the least integer greater than or equal to <code>val</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,10,10,10,10], k = 5
<strong>Output:</strong> 50
<strong>Explanation:</strong> Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,3,3,3], k = 3
<strong>Output:</strong> 17
<strong>Explanation: </strong>You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,<strong><u>4</u></strong>,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,<strong><u>2</u></strong>,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,<u><strong>1</strong></u>,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, k <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
TypeScript
|
function maxKelements(nums: number[], k: number): number {
const pq = new MaxPriorityQueue();
nums.forEach(num => pq.enqueue(num));
let ans = 0;
while (k > 0) {
const v = pq.dequeue()!.element;
ans += v;
pq.enqueue(Math.floor((v + 2) / 3));
k--;
}
return ans;
}
|
2,531
|
Make Number of Distinct Characters Equal
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>word1</code> and <code>word2</code>.</p>
<p>A <strong>move</strong> consists of choosing two indices <code>i</code> and <code>j</code> such that <code>0 <= i < word1.length</code> and <code>0 <= j < word2.length</code> and swapping <code>word1[i]</code> with <code>word2[j]</code>.</p>
<p>Return <code>true</code> <em>if it is possible to get the number of distinct characters in</em> <code>word1</code> <em>and</em> <code>word2</code> <em>to be equal with <strong>exactly one</strong> move. </em>Return <code>false</code> <em>otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word1 = "ac", word2 = "b"
<strong>Output:</strong> false
<strong>Explanation:</strong> Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcc", word2 = "aab"
<strong>Output:</strong> true
<strong>Explanation:</strong> We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcde", word2 = "fghij"
<strong>Output:</strong> true
<strong>Explanation:</strong> Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word1.length, word2.length <= 10<sup>5</sup></code></li>
<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
C++
|
class Solution {
public:
bool isItPossible(string word1, string word2) {
int cnt1[26]{};
int cnt2[26]{};
int x = 0, y = 0;
for (char& c : word1) {
if (++cnt1[c - 'a'] == 1) {
++x;
}
}
for (char& c : word2) {
if (++cnt2[c - 'a'] == 1) {
++y;
}
}
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < 26; ++j) {
if (cnt1[i] > 0 && cnt2[j] > 0) {
if (i == j) {
if (x == y) {
return true;
}
} else {
int a = x - (cnt1[i] == 1 ? 1 : 0) + (cnt1[j] == 0 ? 1 : 0);
int b = y - (cnt2[j] == 1 ? 1 : 0) + (cnt2[i] == 0 ? 1 : 0);
if (a == b) {
return true;
}
}
}
}
}
return false;
}
};
|
2,531
|
Make Number of Distinct Characters Equal
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>word1</code> and <code>word2</code>.</p>
<p>A <strong>move</strong> consists of choosing two indices <code>i</code> and <code>j</code> such that <code>0 <= i < word1.length</code> and <code>0 <= j < word2.length</code> and swapping <code>word1[i]</code> with <code>word2[j]</code>.</p>
<p>Return <code>true</code> <em>if it is possible to get the number of distinct characters in</em> <code>word1</code> <em>and</em> <code>word2</code> <em>to be equal with <strong>exactly one</strong> move. </em>Return <code>false</code> <em>otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word1 = "ac", word2 = "b"
<strong>Output:</strong> false
<strong>Explanation:</strong> Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcc", word2 = "aab"
<strong>Output:</strong> true
<strong>Explanation:</strong> We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcde", word2 = "fghij"
<strong>Output:</strong> true
<strong>Explanation:</strong> Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word1.length, word2.length <= 10<sup>5</sup></code></li>
<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Go
|
func isItPossible(word1 string, word2 string) bool {
cnt1 := [26]int{}
cnt2 := [26]int{}
x, y := 0, 0
for _, c := range word1 {
cnt1[c-'a']++
if cnt1[c-'a'] == 1 {
x++
}
}
for _, c := range word2 {
cnt2[c-'a']++
if cnt2[c-'a'] == 1 {
y++
}
}
for i := range cnt1 {
for j := range cnt2 {
if cnt1[i] > 0 && cnt2[j] > 0 {
if i == j {
if x == y {
return true
}
} else {
a := x
if cnt1[i] == 1 {
a--
}
if cnt1[j] == 0 {
a++
}
b := y
if cnt2[j] == 1 {
b--
}
if cnt2[i] == 0 {
b++
}
if a == b {
return true
}
}
}
}
}
return false
}
|
2,531
|
Make Number of Distinct Characters Equal
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>word1</code> and <code>word2</code>.</p>
<p>A <strong>move</strong> consists of choosing two indices <code>i</code> and <code>j</code> such that <code>0 <= i < word1.length</code> and <code>0 <= j < word2.length</code> and swapping <code>word1[i]</code> with <code>word2[j]</code>.</p>
<p>Return <code>true</code> <em>if it is possible to get the number of distinct characters in</em> <code>word1</code> <em>and</em> <code>word2</code> <em>to be equal with <strong>exactly one</strong> move. </em>Return <code>false</code> <em>otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word1 = "ac", word2 = "b"
<strong>Output:</strong> false
<strong>Explanation:</strong> Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcc", word2 = "aab"
<strong>Output:</strong> true
<strong>Explanation:</strong> We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcde", word2 = "fghij"
<strong>Output:</strong> true
<strong>Explanation:</strong> Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word1.length, word2.length <= 10<sup>5</sup></code></li>
<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Java
|
class Solution {
public boolean isItPossible(String word1, String word2) {
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
int x = 0, y = 0;
for (int i = 0; i < word1.length(); ++i) {
if (++cnt1[word1.charAt(i) - 'a'] == 1) {
++x;
}
}
for (int i = 0; i < word2.length(); ++i) {
if (++cnt2[word2.charAt(i) - 'a'] == 1) {
++y;
}
}
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < 26; ++j) {
if (cnt1[i] > 0 && cnt2[j] > 0) {
if (i == j) {
if (x == y) {
return true;
}
} else {
int a = x - (cnt1[i] == 1 ? 1 : 0) + (cnt1[j] == 0 ? 1 : 0);
int b = y - (cnt2[j] == 1 ? 1 : 0) + (cnt2[i] == 0 ? 1 : 0);
if (a == b) {
return true;
}
}
}
}
}
return false;
}
}
|
2,531
|
Make Number of Distinct Characters Equal
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>word1</code> and <code>word2</code>.</p>
<p>A <strong>move</strong> consists of choosing two indices <code>i</code> and <code>j</code> such that <code>0 <= i < word1.length</code> and <code>0 <= j < word2.length</code> and swapping <code>word1[i]</code> with <code>word2[j]</code>.</p>
<p>Return <code>true</code> <em>if it is possible to get the number of distinct characters in</em> <code>word1</code> <em>and</em> <code>word2</code> <em>to be equal with <strong>exactly one</strong> move. </em>Return <code>false</code> <em>otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word1 = "ac", word2 = "b"
<strong>Output:</strong> false
<strong>Explanation:</strong> Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcc", word2 = "aab"
<strong>Output:</strong> true
<strong>Explanation:</strong> We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcde", word2 = "fghij"
<strong>Output:</strong> true
<strong>Explanation:</strong> Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word1.length, word2.length <= 10<sup>5</sup></code></li>
<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Python
|
class Solution:
def isItPossible(self, word1: str, word2: str) -> bool:
cnt1 = Counter(word1)
cnt2 = Counter(word2)
x, y = len(cnt1), len(cnt2)
for c1, v1 in cnt1.items():
for c2, v2 in cnt2.items():
if c1 == c2:
if x == y:
return True
else:
a = x - (v1 == 1) + (cnt1[c2] == 0)
b = y - (v2 == 1) + (cnt2[c1] == 0)
if a == b:
return True
return False
|
2,531
|
Make Number of Distinct Characters Equal
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>word1</code> and <code>word2</code>.</p>
<p>A <strong>move</strong> consists of choosing two indices <code>i</code> and <code>j</code> such that <code>0 <= i < word1.length</code> and <code>0 <= j < word2.length</code> and swapping <code>word1[i]</code> with <code>word2[j]</code>.</p>
<p>Return <code>true</code> <em>if it is possible to get the number of distinct characters in</em> <code>word1</code> <em>and</em> <code>word2</code> <em>to be equal with <strong>exactly one</strong> move. </em>Return <code>false</code> <em>otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word1 = "ac", word2 = "b"
<strong>Output:</strong> false
<strong>Explanation:</strong> Any pair of swaps would yield two distinct characters in the first string, and one in the second string.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcc", word2 = "aab"
<strong>Output:</strong> true
<strong>Explanation:</strong> We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word1 = "abcde", word2 = "fghij"
<strong>Output:</strong> true
<strong>Explanation:</strong> Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word1.length, word2.length <= 10<sup>5</sup></code></li>
<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
TypeScript
|
function isItPossible(word1: string, word2: string): boolean {
const cnt1: number[] = Array(26).fill(0);
const cnt2: number[] = Array(26).fill(0);
let [x, y] = [0, 0];
for (const c of word1) {
if (++cnt1[c.charCodeAt(0) - 'a'.charCodeAt(0)] === 1) {
++x;
}
}
for (const c of word2) {
if (++cnt2[c.charCodeAt(0) - 'a'.charCodeAt(0)] === 1) {
++y;
}
}
for (let i = 0; i < 26; ++i) {
for (let j = 0; j < 26; ++j) {
if (cnt1[i] > 0 && cnt2[j] > 0) {
if (i === j) {
if (x === y) {
return true;
}
} else {
const a = x - (cnt1[i] === 1 ? 1 : 0) + (cnt1[j] === 0 ? 1 : 0);
const b = y - (cnt2[j] === 1 ? 1 : 0) + (cnt2[i] === 0 ? 1 : 0);
if (a === b) {
return true;
}
}
}
}
}
return false;
}
|
2,532
|
Time to Cross a Bridge
|
Hard
|
<p>There are <code>k</code> workers who want to move <code>n</code> boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>time</code> of size <code>k x 4</code> where <code>time[i] = [right<sub>i</sub>, pick<sub>i</sub>, left<sub>i</sub>, put<sub>i</sub>]</code>.</p>
<p>The warehouses are separated by a river and connected by a bridge. Initially, all <code>k</code> workers are waiting on the left side of the bridge. To move the boxes, the <code>i<sup>th</sup></code> worker can do the following:</p>
<ul>
<li>Cross the bridge to the right side in <code>right<sub>i</sub></code> minutes.</li>
<li>Pick a box from the right warehouse in <code>pick<sub>i</sub></code> minutes.</li>
<li>Cross the bridge to the left side in <code>left<sub>i</sub></code> minutes.</li>
<li>Put the box into the left warehouse in <code>put<sub>i</sub></code> minutes.</li>
</ul>
<p>The <code>i<sup>th</sup></code> worker is <strong>less efficient</strong> than the j<code><sup>th</sup></code> worker if either condition is met:</p>
<ul>
<li><code>left<sub>i</sub> + right<sub>i</sub> > left<sub>j</sub> + right<sub>j</sub></code></li>
<li><code>left<sub>i</sub> + right<sub>i</sub> == left<sub>j</sub> + right<sub>j</sub></code> and <code>i > j</code></li>
</ul>
<p>The following rules regulate the movement of the workers through the bridge:</p>
<ul>
<li>Only one worker can use the bridge at a time.</li>
<li>When the bridge is unused prioritize the <strong>least efficient</strong> worker (who have picked up the box) on the right side to cross. If not, prioritize the <strong>least efficient</strong> worker on the left side to cross.</li>
<li>If enough workers have already been dispatched from the left side to pick up all the remaining boxes, <strong>no more</strong> workers will be sent from the left side.</li>
</ul>
<p>Return the <strong>elapsed minutes</strong> at which the last box reaches the <strong>left side of the bridge</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<pre>
From 0 to 1 minutes: worker 2 crosses the bridge to the right.
From 1 to 2 minutes: worker 2 picks up a box from the right warehouse.
From 2 to 6 minutes: worker 2 crosses the bridge to the left.
From 6 to 7 minutes: worker 2 puts a box at the left warehouse.
The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left side of the bridge.
</pre>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, time =</span> [[1,5,1,8],[10,10,10,10]]</p>
<p><strong>Output:</strong> 37</p>
<p><strong>Explanation:</strong></p>
<pre>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2532.Time%20to%20Cross%20a%20Bridge/images/378539249-c6ce3c73-40e7-4670-a8b5-7ddb9abede11.png" style="width: 450px; height: 176px;" />
</pre>
<p>The last box reaches the left side at 37 seconds. Notice, how we <strong>do not</strong> put the last boxes down, as that would take more time, and they are already on the left with the workers.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>4</sup></code></li>
<li><code>time.length == k</code></li>
<li><code>time[i].length == 4</code></li>
<li><code>1 <= left<sub>i</sub>, pick<sub>i</sub>, right<sub>i</sub>, put<sub>i</sub> <= 1000</code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int findCrossingTime(int n, int k, vector<vector<int>>& time) {
using pii = pair<int, int>;
for (int i = 0; i < k; ++i) {
time[i].push_back(i);
}
sort(time.begin(), time.end(), [](auto& a, auto& b) {
int x = a[0] + a[2], y = b[0] + b[2];
return x == y ? a[4] < b[4] : x < y;
});
int cur = 0;
priority_queue<int> waitInLeft, waitInRight;
priority_queue<pii, vector<pii>, greater<pii>> workInLeft, workInRight;
for (int i = 0; i < k; ++i) {
waitInLeft.push(i);
}
while (true) {
while (!workInLeft.empty()) {
auto [t, i] = workInLeft.top();
if (t > cur) {
break;
}
workInLeft.pop();
waitInLeft.push(i);
}
while (!workInRight.empty()) {
auto [t, i] = workInRight.top();
if (t > cur) {
break;
}
workInRight.pop();
waitInRight.push(i);
}
bool leftToGo = n > 0 && !waitInLeft.empty();
bool rightToGo = !waitInRight.empty();
if (!leftToGo && !rightToGo) {
int nxt = 1 << 30;
if (!workInLeft.empty()) {
nxt = min(nxt, workInLeft.top().first);
}
if (!workInRight.empty()) {
nxt = min(nxt, workInRight.top().first);
}
cur = nxt;
continue;
}
if (rightToGo) {
int i = waitInRight.top();
waitInRight.pop();
cur += time[i][2];
if (n == 0 && waitInRight.empty() && workInRight.empty()) {
return cur;
}
workInLeft.push({cur + time[i][3], i});
} else {
int i = waitInLeft.top();
waitInLeft.pop();
cur += time[i][0];
--n;
workInRight.push({cur + time[i][1], i});
}
}
}
};
|
2,532
|
Time to Cross a Bridge
|
Hard
|
<p>There are <code>k</code> workers who want to move <code>n</code> boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>time</code> of size <code>k x 4</code> where <code>time[i] = [right<sub>i</sub>, pick<sub>i</sub>, left<sub>i</sub>, put<sub>i</sub>]</code>.</p>
<p>The warehouses are separated by a river and connected by a bridge. Initially, all <code>k</code> workers are waiting on the left side of the bridge. To move the boxes, the <code>i<sup>th</sup></code> worker can do the following:</p>
<ul>
<li>Cross the bridge to the right side in <code>right<sub>i</sub></code> minutes.</li>
<li>Pick a box from the right warehouse in <code>pick<sub>i</sub></code> minutes.</li>
<li>Cross the bridge to the left side in <code>left<sub>i</sub></code> minutes.</li>
<li>Put the box into the left warehouse in <code>put<sub>i</sub></code> minutes.</li>
</ul>
<p>The <code>i<sup>th</sup></code> worker is <strong>less efficient</strong> than the j<code><sup>th</sup></code> worker if either condition is met:</p>
<ul>
<li><code>left<sub>i</sub> + right<sub>i</sub> > left<sub>j</sub> + right<sub>j</sub></code></li>
<li><code>left<sub>i</sub> + right<sub>i</sub> == left<sub>j</sub> + right<sub>j</sub></code> and <code>i > j</code></li>
</ul>
<p>The following rules regulate the movement of the workers through the bridge:</p>
<ul>
<li>Only one worker can use the bridge at a time.</li>
<li>When the bridge is unused prioritize the <strong>least efficient</strong> worker (who have picked up the box) on the right side to cross. If not, prioritize the <strong>least efficient</strong> worker on the left side to cross.</li>
<li>If enough workers have already been dispatched from the left side to pick up all the remaining boxes, <strong>no more</strong> workers will be sent from the left side.</li>
</ul>
<p>Return the <strong>elapsed minutes</strong> at which the last box reaches the <strong>left side of the bridge</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<pre>
From 0 to 1 minutes: worker 2 crosses the bridge to the right.
From 1 to 2 minutes: worker 2 picks up a box from the right warehouse.
From 2 to 6 minutes: worker 2 crosses the bridge to the left.
From 6 to 7 minutes: worker 2 puts a box at the left warehouse.
The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left side of the bridge.
</pre>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, time =</span> [[1,5,1,8],[10,10,10,10]]</p>
<p><strong>Output:</strong> 37</p>
<p><strong>Explanation:</strong></p>
<pre>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2532.Time%20to%20Cross%20a%20Bridge/images/378539249-c6ce3c73-40e7-4670-a8b5-7ddb9abede11.png" style="width: 450px; height: 176px;" />
</pre>
<p>The last box reaches the left side at 37 seconds. Notice, how we <strong>do not</strong> put the last boxes down, as that would take more time, and they are already on the left with the workers.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>4</sup></code></li>
<li><code>time.length == k</code></li>
<li><code>time[i].length == 4</code></li>
<li><code>1 <= left<sub>i</sub>, pick<sub>i</sub>, right<sub>i</sub>, put<sub>i</sub> <= 1000</code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Go
|
func findCrossingTime(n int, k int, time [][]int) int {
sort.SliceStable(time, func(i, j int) bool { return time[i][0]+time[i][2] < time[j][0]+time[j][2] })
waitInLeft := hp{}
waitInRight := hp{}
workInLeft := hp2{}
workInRight := hp2{}
for i := range time {
heap.Push(&waitInLeft, i)
}
cur := 0
for {
for len(workInLeft) > 0 {
if workInLeft[0].t > cur {
break
}
heap.Push(&waitInLeft, heap.Pop(&workInLeft).(pair).i)
}
for len(workInRight) > 0 {
if workInRight[0].t > cur {
break
}
heap.Push(&waitInRight, heap.Pop(&workInRight).(pair).i)
}
leftToGo := n > 0 && waitInLeft.Len() > 0
rightToGo := waitInRight.Len() > 0
if !leftToGo && !rightToGo {
nxt := 1 << 30
if len(workInLeft) > 0 {
nxt = min(nxt, workInLeft[0].t)
}
if len(workInRight) > 0 {
nxt = min(nxt, workInRight[0].t)
}
cur = nxt
continue
}
if rightToGo {
i := heap.Pop(&waitInRight).(int)
cur += time[i][2]
if n == 0 && waitInRight.Len() == 0 && len(workInRight) == 0 {
return cur
}
heap.Push(&workInLeft, pair{cur + time[i][3], i})
} else {
i := heap.Pop(&waitInLeft).(int)
cur += time[i][0]
n--
heap.Push(&workInRight, pair{cur + time[i][1], i})
}
}
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
type pair struct{ t, i int }
type hp2 []pair
func (h hp2) Len() int { return len(h) }
func (h hp2) Less(i, j int) bool { return h[i].t < h[j].t }
func (h hp2) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
2,532
|
Time to Cross a Bridge
|
Hard
|
<p>There are <code>k</code> workers who want to move <code>n</code> boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>time</code> of size <code>k x 4</code> where <code>time[i] = [right<sub>i</sub>, pick<sub>i</sub>, left<sub>i</sub>, put<sub>i</sub>]</code>.</p>
<p>The warehouses are separated by a river and connected by a bridge. Initially, all <code>k</code> workers are waiting on the left side of the bridge. To move the boxes, the <code>i<sup>th</sup></code> worker can do the following:</p>
<ul>
<li>Cross the bridge to the right side in <code>right<sub>i</sub></code> minutes.</li>
<li>Pick a box from the right warehouse in <code>pick<sub>i</sub></code> minutes.</li>
<li>Cross the bridge to the left side in <code>left<sub>i</sub></code> minutes.</li>
<li>Put the box into the left warehouse in <code>put<sub>i</sub></code> minutes.</li>
</ul>
<p>The <code>i<sup>th</sup></code> worker is <strong>less efficient</strong> than the j<code><sup>th</sup></code> worker if either condition is met:</p>
<ul>
<li><code>left<sub>i</sub> + right<sub>i</sub> > left<sub>j</sub> + right<sub>j</sub></code></li>
<li><code>left<sub>i</sub> + right<sub>i</sub> == left<sub>j</sub> + right<sub>j</sub></code> and <code>i > j</code></li>
</ul>
<p>The following rules regulate the movement of the workers through the bridge:</p>
<ul>
<li>Only one worker can use the bridge at a time.</li>
<li>When the bridge is unused prioritize the <strong>least efficient</strong> worker (who have picked up the box) on the right side to cross. If not, prioritize the <strong>least efficient</strong> worker on the left side to cross.</li>
<li>If enough workers have already been dispatched from the left side to pick up all the remaining boxes, <strong>no more</strong> workers will be sent from the left side.</li>
</ul>
<p>Return the <strong>elapsed minutes</strong> at which the last box reaches the <strong>left side of the bridge</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<pre>
From 0 to 1 minutes: worker 2 crosses the bridge to the right.
From 1 to 2 minutes: worker 2 picks up a box from the right warehouse.
From 2 to 6 minutes: worker 2 crosses the bridge to the left.
From 6 to 7 minutes: worker 2 puts a box at the left warehouse.
The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left side of the bridge.
</pre>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, time =</span> [[1,5,1,8],[10,10,10,10]]</p>
<p><strong>Output:</strong> 37</p>
<p><strong>Explanation:</strong></p>
<pre>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2532.Time%20to%20Cross%20a%20Bridge/images/378539249-c6ce3c73-40e7-4670-a8b5-7ddb9abede11.png" style="width: 450px; height: 176px;" />
</pre>
<p>The last box reaches the left side at 37 seconds. Notice, how we <strong>do not</strong> put the last boxes down, as that would take more time, and they are already on the left with the workers.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>4</sup></code></li>
<li><code>time.length == k</code></li>
<li><code>time[i].length == 4</code></li>
<li><code>1 <= left<sub>i</sub>, pick<sub>i</sub>, right<sub>i</sub>, put<sub>i</sub> <= 1000</code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public int findCrossingTime(int n, int k, int[][] time) {
int[][] t = new int[k][5];
for (int i = 0; i < k; ++i) {
int[] x = time[i];
t[i] = new int[] {x[0], x[1], x[2], x[3], i};
}
Arrays.sort(t, (a, b) -> {
int x = a[0] + a[2], y = b[0] + b[2];
return x == y ? a[4] - b[4] : x - y;
});
int cur = 0;
PriorityQueue<Integer> waitInLeft = new PriorityQueue<>((a, b) -> b - a);
PriorityQueue<Integer> waitInRight = new PriorityQueue<>((a, b) -> b - a);
PriorityQueue<int[]> workInLeft = new PriorityQueue<>((a, b) -> a[0] - b[0]);
PriorityQueue<int[]> workInRight = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < k; ++i) {
waitInLeft.offer(i);
}
while (true) {
while (!workInLeft.isEmpty()) {
int[] p = workInLeft.peek();
if (p[0] > cur) {
break;
}
waitInLeft.offer(workInLeft.poll()[1]);
}
while (!workInRight.isEmpty()) {
int[] p = workInRight.peek();
if (p[0] > cur) {
break;
}
waitInRight.offer(workInRight.poll()[1]);
}
boolean leftToGo = n > 0 && !waitInLeft.isEmpty();
boolean rightToGo = !waitInRight.isEmpty();
if (!leftToGo && !rightToGo) {
int nxt = 1 << 30;
if (!workInLeft.isEmpty()) {
nxt = Math.min(nxt, workInLeft.peek()[0]);
}
if (!workInRight.isEmpty()) {
nxt = Math.min(nxt, workInRight.peek()[0]);
}
cur = nxt;
continue;
}
if (rightToGo) {
int i = waitInRight.poll();
cur += t[i][2];
if (n == 0 && waitInRight.isEmpty() && workInRight.isEmpty()) {
return cur;
}
workInLeft.offer(new int[] {cur + t[i][3], i});
} else {
int i = waitInLeft.poll();
cur += t[i][0];
--n;
workInRight.offer(new int[] {cur + t[i][1], i});
}
}
}
}
|
2,532
|
Time to Cross a Bridge
|
Hard
|
<p>There are <code>k</code> workers who want to move <code>n</code> boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers <code>n</code> and <code>k</code>, and a 2D integer array <code>time</code> of size <code>k x 4</code> where <code>time[i] = [right<sub>i</sub>, pick<sub>i</sub>, left<sub>i</sub>, put<sub>i</sub>]</code>.</p>
<p>The warehouses are separated by a river and connected by a bridge. Initially, all <code>k</code> workers are waiting on the left side of the bridge. To move the boxes, the <code>i<sup>th</sup></code> worker can do the following:</p>
<ul>
<li>Cross the bridge to the right side in <code>right<sub>i</sub></code> minutes.</li>
<li>Pick a box from the right warehouse in <code>pick<sub>i</sub></code> minutes.</li>
<li>Cross the bridge to the left side in <code>left<sub>i</sub></code> minutes.</li>
<li>Put the box into the left warehouse in <code>put<sub>i</sub></code> minutes.</li>
</ul>
<p>The <code>i<sup>th</sup></code> worker is <strong>less efficient</strong> than the j<code><sup>th</sup></code> worker if either condition is met:</p>
<ul>
<li><code>left<sub>i</sub> + right<sub>i</sub> > left<sub>j</sub> + right<sub>j</sub></code></li>
<li><code>left<sub>i</sub> + right<sub>i</sub> == left<sub>j</sub> + right<sub>j</sub></code> and <code>i > j</code></li>
</ul>
<p>The following rules regulate the movement of the workers through the bridge:</p>
<ul>
<li>Only one worker can use the bridge at a time.</li>
<li>When the bridge is unused prioritize the <strong>least efficient</strong> worker (who have picked up the box) on the right side to cross. If not, prioritize the <strong>least efficient</strong> worker on the left side to cross.</li>
<li>If enough workers have already been dispatched from the left side to pick up all the remaining boxes, <strong>no more</strong> workers will be sent from the left side.</li>
</ul>
<p>Return the <strong>elapsed minutes</strong> at which the last box reaches the <strong>left side of the bridge</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<pre>
From 0 to 1 minutes: worker 2 crosses the bridge to the right.
From 1 to 2 minutes: worker 2 picks up a box from the right warehouse.
From 2 to 6 minutes: worker 2 crosses the bridge to the left.
From 6 to 7 minutes: worker 2 puts a box at the left warehouse.
The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left side of the bridge.
</pre>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, k = 2, time =</span> [[1,5,1,8],[10,10,10,10]]</p>
<p><strong>Output:</strong> 37</p>
<p><strong>Explanation:</strong></p>
<pre>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2532.Time%20to%20Cross%20a%20Bridge/images/378539249-c6ce3c73-40e7-4670-a8b5-7ddb9abede11.png" style="width: 450px; height: 176px;" />
</pre>
<p>The last box reaches the left side at 37 seconds. Notice, how we <strong>do not</strong> put the last boxes down, as that would take more time, and they are already on the left with the workers.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>4</sup></code></li>
<li><code>time.length == k</code></li>
<li><code>time[i].length == 4</code></li>
<li><code>1 <= left<sub>i</sub>, pick<sub>i</sub>, right<sub>i</sub>, put<sub>i</sub> <= 1000</code></li>
</ul>
|
Array; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int:
time.sort(key=lambda x: x[0] + x[2])
cur = 0
wait_in_left, wait_in_right = [], []
work_in_left, work_in_right = [], []
for i in range(k):
heappush(wait_in_left, -i)
while 1:
while work_in_left:
t, i = work_in_left[0]
if t > cur:
break
heappop(work_in_left)
heappush(wait_in_left, -i)
while work_in_right:
t, i = work_in_right[0]
if t > cur:
break
heappop(work_in_right)
heappush(wait_in_right, -i)
left_to_go = n > 0 and wait_in_left
right_to_go = bool(wait_in_right)
if not left_to_go and not right_to_go:
nxt = inf
if work_in_left:
nxt = min(nxt, work_in_left[0][0])
if work_in_right:
nxt = min(nxt, work_in_right[0][0])
cur = nxt
continue
if right_to_go:
i = -heappop(wait_in_right)
cur += time[i][2]
if n == 0 and not wait_in_right and not work_in_right:
return cur
heappush(work_in_left, (cur + time[i][3], i))
else:
i = -heappop(wait_in_left)
cur += time[i][0]
n -= 1
heappush(work_in_right, (cur + time[i][1], i))
|
2,533
|
Number of Good Binary Strings
|
Medium
|
<p>You are given four integers <code>minLength</code>, <code>maxLength</code>, <code>oneGroup</code> and <code>zeroGroup</code>.</p>
<p>A binary string is <strong>good</strong> if it satisfies the following conditions:</p>
<ul>
<li>The length of the string is in the range <code>[minLength, maxLength]</code>.</li>
<li>The size of each block of consecutive <code>1</code>'s is a multiple of <code>oneGroup</code>.
<ul>
<li>For example in a binary string <code>00<u>11</u>0<u>1111</u>00</code> sizes of each block of consecutive ones are <code>[2,4]</code>.</li>
</ul>
</li>
<li>The size of each block of consecutive <code>0</code>'s is a multiple of <code>zeroGroup</code>.
<ul>
<li>For example, in a binary string <code><u>00</u>11<u>0</u>1111<u>00</u></code> sizes of each block of consecutive zeros are <code>[2,1,2]</code>.</li>
</ul>
</li>
</ul>
<p>Return <em>the number of <strong>good</strong> binary strings</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that <code>0</code> is considered a multiple of all the numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".
It can be proven that there are only 5 good strings satisfying all conditions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only 1 good binary string in this example: "1111".
It can be proven that there is only 1 good string satisfying all conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= minLength <= maxLength <= 10<sup>5</sup></code></li>
<li><code>1 <= oneGroup, zeroGroup <= maxLength</code></li>
</ul>
|
Dynamic Programming
|
C++
|
class Solution {
public:
int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) {
const int mod = 1e9 + 7;
int f[maxLength + 1];
memset(f, 0, sizeof f);
f[0] = 1;
for (int i = 1; i <= maxLength; ++i) {
if (i - oneGroup >= 0) {
f[i] = (f[i] + f[i - oneGroup]) % mod;
}
if (i - zeroGroup >= 0) {
f[i] = (f[i] + f[i - zeroGroup]) % mod;
}
}
int ans = 0;
for (int i = minLength; i <= maxLength; ++i) {
ans = (ans + f[i]) % mod;
}
return ans;
}
};
|
2,533
|
Number of Good Binary Strings
|
Medium
|
<p>You are given four integers <code>minLength</code>, <code>maxLength</code>, <code>oneGroup</code> and <code>zeroGroup</code>.</p>
<p>A binary string is <strong>good</strong> if it satisfies the following conditions:</p>
<ul>
<li>The length of the string is in the range <code>[minLength, maxLength]</code>.</li>
<li>The size of each block of consecutive <code>1</code>'s is a multiple of <code>oneGroup</code>.
<ul>
<li>For example in a binary string <code>00<u>11</u>0<u>1111</u>00</code> sizes of each block of consecutive ones are <code>[2,4]</code>.</li>
</ul>
</li>
<li>The size of each block of consecutive <code>0</code>'s is a multiple of <code>zeroGroup</code>.
<ul>
<li>For example, in a binary string <code><u>00</u>11<u>0</u>1111<u>00</u></code> sizes of each block of consecutive zeros are <code>[2,1,2]</code>.</li>
</ul>
</li>
</ul>
<p>Return <em>the number of <strong>good</strong> binary strings</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that <code>0</code> is considered a multiple of all the numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".
It can be proven that there are only 5 good strings satisfying all conditions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only 1 good binary string in this example: "1111".
It can be proven that there is only 1 good string satisfying all conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= minLength <= maxLength <= 10<sup>5</sup></code></li>
<li><code>1 <= oneGroup, zeroGroup <= maxLength</code></li>
</ul>
|
Dynamic Programming
|
Go
|
func goodBinaryStrings(minLength int, maxLength int, oneGroup int, zeroGroup int) (ans int) {
const mod int = 1e9 + 7
f := make([]int, maxLength+1)
f[0] = 1
for i := 1; i <= maxLength; i++ {
if i-oneGroup >= 0 {
f[i] += f[i-oneGroup]
}
if i-zeroGroup >= 0 {
f[i] += f[i-zeroGroup]
}
f[i] %= mod
}
for _, v := range f[minLength:] {
ans = (ans + v) % mod
}
return
}
|
2,533
|
Number of Good Binary Strings
|
Medium
|
<p>You are given four integers <code>minLength</code>, <code>maxLength</code>, <code>oneGroup</code> and <code>zeroGroup</code>.</p>
<p>A binary string is <strong>good</strong> if it satisfies the following conditions:</p>
<ul>
<li>The length of the string is in the range <code>[minLength, maxLength]</code>.</li>
<li>The size of each block of consecutive <code>1</code>'s is a multiple of <code>oneGroup</code>.
<ul>
<li>For example in a binary string <code>00<u>11</u>0<u>1111</u>00</code> sizes of each block of consecutive ones are <code>[2,4]</code>.</li>
</ul>
</li>
<li>The size of each block of consecutive <code>0</code>'s is a multiple of <code>zeroGroup</code>.
<ul>
<li>For example, in a binary string <code><u>00</u>11<u>0</u>1111<u>00</u></code> sizes of each block of consecutive zeros are <code>[2,1,2]</code>.</li>
</ul>
</li>
</ul>
<p>Return <em>the number of <strong>good</strong> binary strings</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that <code>0</code> is considered a multiple of all the numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".
It can be proven that there are only 5 good strings satisfying all conditions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only 1 good binary string in this example: "1111".
It can be proven that there is only 1 good string satisfying all conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= minLength <= maxLength <= 10<sup>5</sup></code></li>
<li><code>1 <= oneGroup, zeroGroup <= maxLength</code></li>
</ul>
|
Dynamic Programming
|
Java
|
class Solution {
public int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) {
final int mod = (int) 1e9 + 7;
int[] f = new int[maxLength + 1];
f[0] = 1;
for (int i = 1; i <= maxLength; ++i) {
if (i - oneGroup >= 0) {
f[i] = (f[i] + f[i - oneGroup]) % mod;
}
if (i - zeroGroup >= 0) {
f[i] = (f[i] + f[i - zeroGroup]) % mod;
}
}
int ans = 0;
for (int i = minLength; i <= maxLength; ++i) {
ans = (ans + f[i]) % mod;
}
return ans;
}
}
|
2,533
|
Number of Good Binary Strings
|
Medium
|
<p>You are given four integers <code>minLength</code>, <code>maxLength</code>, <code>oneGroup</code> and <code>zeroGroup</code>.</p>
<p>A binary string is <strong>good</strong> if it satisfies the following conditions:</p>
<ul>
<li>The length of the string is in the range <code>[minLength, maxLength]</code>.</li>
<li>The size of each block of consecutive <code>1</code>'s is a multiple of <code>oneGroup</code>.
<ul>
<li>For example in a binary string <code>00<u>11</u>0<u>1111</u>00</code> sizes of each block of consecutive ones are <code>[2,4]</code>.</li>
</ul>
</li>
<li>The size of each block of consecutive <code>0</code>'s is a multiple of <code>zeroGroup</code>.
<ul>
<li>For example, in a binary string <code><u>00</u>11<u>0</u>1111<u>00</u></code> sizes of each block of consecutive zeros are <code>[2,1,2]</code>.</li>
</ul>
</li>
</ul>
<p>Return <em>the number of <strong>good</strong> binary strings</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that <code>0</code> is considered a multiple of all the numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".
It can be proven that there are only 5 good strings satisfying all conditions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only 1 good binary string in this example: "1111".
It can be proven that there is only 1 good string satisfying all conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= minLength <= maxLength <= 10<sup>5</sup></code></li>
<li><code>1 <= oneGroup, zeroGroup <= maxLength</code></li>
</ul>
|
Dynamic Programming
|
Python
|
class Solution:
def goodBinaryStrings(
self, minLength: int, maxLength: int, oneGroup: int, zeroGroup: int
) -> int:
mod = 10**9 + 7
f = [1] + [0] * maxLength
for i in range(1, len(f)):
if i - oneGroup >= 0:
f[i] += f[i - oneGroup]
if i - zeroGroup >= 0:
f[i] += f[i - zeroGroup]
f[i] %= mod
return sum(f[minLength:]) % mod
|
2,533
|
Number of Good Binary Strings
|
Medium
|
<p>You are given four integers <code>minLength</code>, <code>maxLength</code>, <code>oneGroup</code> and <code>zeroGroup</code>.</p>
<p>A binary string is <strong>good</strong> if it satisfies the following conditions:</p>
<ul>
<li>The length of the string is in the range <code>[minLength, maxLength]</code>.</li>
<li>The size of each block of consecutive <code>1</code>'s is a multiple of <code>oneGroup</code>.
<ul>
<li>For example in a binary string <code>00<u>11</u>0<u>1111</u>00</code> sizes of each block of consecutive ones are <code>[2,4]</code>.</li>
</ul>
</li>
<li>The size of each block of consecutive <code>0</code>'s is a multiple of <code>zeroGroup</code>.
<ul>
<li>For example, in a binary string <code><u>00</u>11<u>0</u>1111<u>00</u></code> sizes of each block of consecutive zeros are <code>[2,1,2]</code>.</li>
</ul>
</li>
</ul>
<p>Return <em>the number of <strong>good</strong> binary strings</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that <code>0</code> is considered a multiple of all the numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> minLength = 2, maxLength = 3, oneGroup = 1, zeroGroup = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> There are 5 good binary strings in this example: "00", "11", "001", "100", and "111".
It can be proven that there are only 5 good strings satisfying all conditions.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> minLength = 4, maxLength = 4, oneGroup = 4, zeroGroup = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is only 1 good binary string in this example: "1111".
It can be proven that there is only 1 good string satisfying all conditions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= minLength <= maxLength <= 10<sup>5</sup></code></li>
<li><code>1 <= oneGroup, zeroGroup <= maxLength</code></li>
</ul>
|
Dynamic Programming
|
TypeScript
|
function goodBinaryStrings(
minLength: number,
maxLength: number,
oneGroup: number,
zeroGroup: number,
): number {
const mod = 10 ** 9 + 7;
const f: number[] = Array(maxLength + 1).fill(0);
f[0] = 1;
for (let i = 1; i <= maxLength; ++i) {
if (i >= oneGroup) {
f[i] += f[i - oneGroup];
}
if (i >= zeroGroup) {
f[i] += f[i - zeroGroup];
}
f[i] %= mod;
}
return f.slice(minLength).reduce((a, b) => a + b, 0) % mod;
}
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
C++
|
class Solution {
public:
vector<int> timeTaken(vector<int>& arrival, vector<int>& state) {
int n = arrival.size();
queue<int> q[2];
int t = 0, i = 0, st = 1;
vector<int> ans(n);
while (i < n || !q[0].empty() || !q[1].empty()) {
while (i < n && arrival[i] <= t) {
q[state[i]].push(i++);
}
if (!q[0].empty() && !q[1].empty()) {
ans[q[st].front()] = t;
q[st].pop();
} else if (!q[0].empty() || !q[1].empty()) {
st = q[0].empty() ? 1 : 0;
ans[q[st].front()] = t;
q[st].pop();
} else {
st = 1;
}
++t;
}
return ans;
}
};
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
Go
|
func timeTaken(arrival []int, state []int) []int {
n := len(arrival)
q := [2][]int{}
t, i, st := 0, 0, 1
ans := make([]int, n)
for i < n || len(q[0]) > 0 || len(q[1]) > 0 {
for i < n && arrival[i] <= t {
q[state[i]] = append(q[state[i]], i)
i++
}
if len(q[0]) > 0 && len(q[1]) > 0 {
ans[q[st][0]] = t
q[st] = q[st][1:]
} else if len(q[0]) > 0 || len(q[1]) > 0 {
if len(q[0]) == 0 {
st = 1
} else {
st = 0
}
ans[q[st][0]] = t
q[st] = q[st][1:]
} else {
st = 1
}
t++
}
return ans
}
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
Java
|
class Solution {
public int[] timeTaken(int[] arrival, int[] state) {
Deque<Integer>[] q = new Deque[2];
Arrays.setAll(q, i -> new ArrayDeque<>());
int n = arrival.length;
int t = 0, i = 0, st = 1;
int[] ans = new int[n];
while (i < n || !q[0].isEmpty() || !q[1].isEmpty()) {
while (i < n && arrival[i] <= t) {
q[state[i]].add(i++);
}
if (!q[0].isEmpty() && !q[1].isEmpty()) {
ans[q[st].poll()] = t;
} else if (!q[0].isEmpty() || !q[1].isEmpty()) {
st = q[0].isEmpty() ? 1 : 0;
ans[q[st].poll()] = t;
} else {
st = 1;
}
++t;
}
return ans;
}
}
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
Python
|
class Solution:
def timeTaken(self, arrival: List[int], state: List[int]) -> List[int]:
q = [deque(), deque()]
n = len(arrival)
t = i = 0
st = 1
ans = [0] * n
while i < n or q[0] or q[1]:
while i < n and arrival[i] <= t:
q[state[i]].append(i)
i += 1
if q[0] and q[1]:
ans[q[st].popleft()] = t
elif q[0] or q[1]:
st = 0 if q[0] else 1
ans[q[st].popleft()] = t
else:
st = 1
t += 1
return ans
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
Rust
|
use std::collections::VecDeque;
impl Solution {
pub fn time_taken(arrival: Vec<i32>, state: Vec<i32>) -> Vec<i32> {
let n = arrival.len();
let mut q = vec![VecDeque::new(), VecDeque::new()];
let mut t = 0;
let mut i = 0;
let mut st = 1;
let mut ans = vec![-1; n];
while i < n || !q[0].is_empty() || !q[1].is_empty() {
while i < n && arrival[i] <= t {
q[state[i] as usize].push_back(i);
i += 1;
}
if !q[0].is_empty() && !q[1].is_empty() {
ans[*q[st].front().unwrap()] = t;
q[st].pop_front();
} else if !q[0].is_empty() || !q[1].is_empty() {
st = if q[0].is_empty() { 1 } else { 0 };
ans[*q[st].front().unwrap()] = t;
q[st].pop_front();
} else {
st = 1;
}
t += 1;
}
ans
}
}
|
2,534
|
Time Taken to Cross the Door
|
Hard
|
<p>There are <code>n</code> persons numbered from <code>0</code> to <code>n - 1</code> and a door. Each person can enter or exit through the door once, taking one second.</p>
<p>You are given a <strong>non-decreasing</strong> integer array <code>arrival</code> of size <code>n</code>, where <code>arrival[i]</code> is the arrival time of the <code>i<sup>th</sup></code> person at the door. You are also given an array <code>state</code> of size <code>n</code>, where <code>state[i]</code> is <code>0</code> if person <code>i</code> wants to enter through the door or <code>1</code> if they want to exit through the door.</p>
<p>If two or more persons want to use the door at the <strong>same</strong> time, they follow the following rules:</p>
<ul>
<li>If the door was <strong>not</strong> used in the previous second, then the person who wants to <strong>exit</strong> goes first.</li>
<li>If the door was used in the previous second for <strong>entering</strong>, the person who wants to enter goes first.</li>
<li>If the door was used in the previous second for <strong>exiting</strong>, the person who wants to <strong>exit</strong> goes first.</li>
<li>If multiple persons want to go in the same direction, the person with the <strong>smallest</strong> index goes first.</li>
</ul>
<p>Return <em>an array </em><code>answer</code><em> of size </em><code>n</code><em> where </em><code>answer[i]</code><em> is the second at which the </em><code>i<sup>th</sup></code><em> person crosses the door</em>.</p>
<p><strong>Note</strong> that:</p>
<ul>
<li>Only one person can cross the door at each second.</li>
<li>A person may arrive at the door and wait without entering or exiting to follow the mentioned rules.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,1,1,2,4], state = [0,1,0,0,1]
<strong>Output:</strong> [0,3,1,2,4]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 0 is the only one who wants to enter, so they just enter through the door.
- At t = 1: Person 1 wants to exit, and person 2 wants to enter. Since the door was used the previous second for entering, person 2 enters.
- At t = 2: Person 1 still wants to exit, and person 3 wants to enter. Since the door was used the previous second for entering, person 3 enters.
- At t = 3: Person 1 is the only one who wants to exit, so they just exit through the door.
- At t = 4: Person 4 is the only one who wants to exit, so they just exit through the door.
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> arrival = [0,0,0], state = [1,0,1]
<strong>Output:</strong> [0,2,1]
<strong>Explanation:</strong> At each second we have the following:
- At t = 0: Person 1 wants to enter while persons 0 and 2 want to exit. Since the door was not used in the previous second, the persons who want to exit get to go first. Since person 0 has a smaller index, they exit first.
- At t = 1: Person 1 wants to enter, and person 2 wants to exit. Since the door was used in the previous second for exiting, person 2 exits.
- At t = 2: Person 1 is the only one who wants to enter, so they just enter through the door.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == arrival.length == state.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= arrival[i] <= n</code></li>
<li><code>arrival</code> is sorted in <strong>non-decreasing</strong> order.</li>
<li><code>state[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
|
Queue; Array; Simulation
|
TypeScript
|
function timeTaken(arrival: number[], state: number[]): number[] {
const n = arrival.length;
const q: number[][] = [[], []];
let [t, i, st] = [0, 0, 1];
const ans: number[] = Array(n).fill(0);
while (i < n || q[0].length || q[1].length) {
while (i < n && arrival[i] <= t) {
q[state[i]].push(i++);
}
if (q[0].length && q[1].length) {
ans[q[st][0]] = t;
q[st].shift();
} else if (q[0].length || q[1].length) {
st = q[0].length ? 0 : 1;
ans[q[st][0]] = t;
q[st].shift();
} else {
st = 1;
}
t++;
}
return ans;
}
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
C
|
int differenceOfSum(int* nums, int numsSize) {
int x = 0, y = 0;
for (int i = 0; i < numsSize; i++) {
int v = nums[i];
x += v;
while (v > 0) {
y += v % 10;
v /= 10;
}
}
return x - y;
}
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
C++
|
class Solution {
public:
int differenceOfSum(vector<int>& nums) {
int x = 0, y = 0;
for (int v : nums) {
x += v;
for (; v; v /= 10) {
y += v % 10;
}
}
return x - y;
}
};
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
Go
|
func differenceOfSum(nums []int) int {
var x, y int
for _, v := range nums {
x += v
for ; v > 0; v /= 10 {
y += v % 10
}
}
return x - y
}
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
Java
|
class Solution {
public int differenceOfSum(int[] nums) {
int x = 0, y = 0;
for (int v : nums) {
x += v;
for (; v > 0; v /= 10) {
y += v % 10;
}
}
return x - y;
}
}
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
Python
|
class Solution:
def differenceOfSum(self, nums: List[int]) -> int:
x = y = 0
for v in nums:
x += v
while v:
y += v % 10
v //= 10
return x - y
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
Rust
|
impl Solution {
pub fn difference_of_sum(nums: Vec<i32>) -> i32 {
let mut x = 0;
let mut y = 0;
for &v in &nums {
x += v;
let mut num = v;
while num > 0 {
y += num % 10;
num /= 10;
}
}
x - y
}
}
|
2,535
|
Difference Between Element Sum and Digit Sum of an Array
|
Easy
|
<p>You are given a positive integer array <code>nums</code>.</p>
<ul>
<li>The <strong>element sum</strong> is the sum of all the elements in <code>nums</code>.</li>
<li>The <strong>digit sum</strong> is the sum of all the digits (not necessarily distinct) that appear in <code>nums</code>.</li>
</ul>
<p>Return <em>the <strong>absolute</strong> difference between the <strong>element sum</strong> and <strong>digit sum</strong> of </em><code>nums</code>.</p>
<p><strong>Note</strong> that the absolute difference between two integers <code>x</code> and <code>y</code> is defined as <code>|x - y|</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,15,6,3]
<strong>Output:</strong> 9
<strong>Explanation:</strong>
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong>
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 2000</code></li>
</ul>
|
Array; Math
|
TypeScript
|
function differenceOfSum(nums: number[]): number {
let [x, y] = [0, 0];
for (let v of nums) {
x += v;
for (; v; v = Math.floor(v / 10)) {
y += v % 10;
}
}
return x - y;
}
|
2,536
|
Increment Submatrices by One
|
Medium
|
<p>You are given a positive integer <code>n</code>, indicating that we initially have an <code>n x n</code> <strong>0-indexed</strong> integer matrix <code>mat</code> filled with zeroes.</p>
<p>You are also given a 2D integer array <code>query</code>. For each <code>query[i] = [row1<sub>i</sub>, col1<sub>i</sub>, row2<sub>i</sub>, col2<sub>i</sub>]</code>, you should do the following operation:</p>
<ul>
<li>Add <code>1</code> to <strong>every element</strong> in the submatrix with the <strong>top left</strong> corner <code>(row1<sub>i</sub>, col1<sub>i</sub>)</code> and the <strong>bottom right</strong> corner <code>(row2<sub>i</sub>, col2<sub>i</sub>)</code>. That is, add <code>1</code> to <code>mat[x][y]</code> for all <code>row1<sub>i</sub> <= x <= row2<sub>i</sub></code> and <code>col1<sub>i</sub> <= y <= col2<sub>i</sub></code>.</li>
</ul>
<p>Return<em> the matrix</em> <code>mat</code><em> after performing every query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example11.png" style="width: 531px; height: 121px;" />
<pre>
<strong>Input:</strong> n = 3, queries = [[1,1,2,2],[0,0,1,1]]
<strong>Output:</strong> [[1,1,0],[1,2,1],[0,1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example22.png" style="width: 261px; height: 82px;" />
<pre>
<strong>Input:</strong> n = 2, queries = [[0,0,1,1]]
<strong>Output:</strong> [[1,1],[1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 500</code></li>
<li><code>1 <= queries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= row1<sub>i</sub> <= row2<sub>i</sub> < n</code></li>
<li><code>0 <= col1<sub>i</sub> <= col2<sub>i</sub> < n</code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
C++
|
class Solution {
public:
vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
vector<vector<int>> mat(n, vector<int>(n));
for (auto& q : queries) {
int x1 = q[0], y1 = q[1], x2 = q[2], y2 = q[3];
mat[x1][y1]++;
if (x2 + 1 < n) {
mat[x2 + 1][y1]--;
}
if (y2 + 1 < n) {
mat[x1][y2 + 1]--;
}
if (x2 + 1 < n && y2 + 1 < n) {
mat[x2 + 1][y2 + 1]++;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i > 0) {
mat[i][j] += mat[i - 1][j];
}
if (j > 0) {
mat[i][j] += mat[i][j - 1];
}
if (i > 0 && j > 0) {
mat[i][j] -= mat[i - 1][j - 1];
}
}
}
return mat;
}
};
|
2,536
|
Increment Submatrices by One
|
Medium
|
<p>You are given a positive integer <code>n</code>, indicating that we initially have an <code>n x n</code> <strong>0-indexed</strong> integer matrix <code>mat</code> filled with zeroes.</p>
<p>You are also given a 2D integer array <code>query</code>. For each <code>query[i] = [row1<sub>i</sub>, col1<sub>i</sub>, row2<sub>i</sub>, col2<sub>i</sub>]</code>, you should do the following operation:</p>
<ul>
<li>Add <code>1</code> to <strong>every element</strong> in the submatrix with the <strong>top left</strong> corner <code>(row1<sub>i</sub>, col1<sub>i</sub>)</code> and the <strong>bottom right</strong> corner <code>(row2<sub>i</sub>, col2<sub>i</sub>)</code>. That is, add <code>1</code> to <code>mat[x][y]</code> for all <code>row1<sub>i</sub> <= x <= row2<sub>i</sub></code> and <code>col1<sub>i</sub> <= y <= col2<sub>i</sub></code>.</li>
</ul>
<p>Return<em> the matrix</em> <code>mat</code><em> after performing every query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example11.png" style="width: 531px; height: 121px;" />
<pre>
<strong>Input:</strong> n = 3, queries = [[1,1,2,2],[0,0,1,1]]
<strong>Output:</strong> [[1,1,0],[1,2,1],[0,1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example22.png" style="width: 261px; height: 82px;" />
<pre>
<strong>Input:</strong> n = 2, queries = [[0,0,1,1]]
<strong>Output:</strong> [[1,1],[1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 500</code></li>
<li><code>1 <= queries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= row1<sub>i</sub> <= row2<sub>i</sub> < n</code></li>
<li><code>0 <= col1<sub>i</sub> <= col2<sub>i</sub> < n</code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Go
|
func rangeAddQueries(n int, queries [][]int) [][]int {
mat := make([][]int, n)
for i := range mat {
mat[i] = make([]int, n)
}
for _, q := range queries {
x1, y1, x2, y2 := q[0], q[1], q[2], q[3]
mat[x1][y1]++
if x2+1 < n {
mat[x2+1][y1]--
}
if y2+1 < n {
mat[x1][y2+1]--
}
if x2+1 < n && y2+1 < n {
mat[x2+1][y2+1]++
}
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i > 0 {
mat[i][j] += mat[i-1][j]
}
if j > 0 {
mat[i][j] += mat[i][j-1]
}
if i > 0 && j > 0 {
mat[i][j] -= mat[i-1][j-1]
}
}
}
return mat
}
|
2,536
|
Increment Submatrices by One
|
Medium
|
<p>You are given a positive integer <code>n</code>, indicating that we initially have an <code>n x n</code> <strong>0-indexed</strong> integer matrix <code>mat</code> filled with zeroes.</p>
<p>You are also given a 2D integer array <code>query</code>. For each <code>query[i] = [row1<sub>i</sub>, col1<sub>i</sub>, row2<sub>i</sub>, col2<sub>i</sub>]</code>, you should do the following operation:</p>
<ul>
<li>Add <code>1</code> to <strong>every element</strong> in the submatrix with the <strong>top left</strong> corner <code>(row1<sub>i</sub>, col1<sub>i</sub>)</code> and the <strong>bottom right</strong> corner <code>(row2<sub>i</sub>, col2<sub>i</sub>)</code>. That is, add <code>1</code> to <code>mat[x][y]</code> for all <code>row1<sub>i</sub> <= x <= row2<sub>i</sub></code> and <code>col1<sub>i</sub> <= y <= col2<sub>i</sub></code>.</li>
</ul>
<p>Return<em> the matrix</em> <code>mat</code><em> after performing every query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example11.png" style="width: 531px; height: 121px;" />
<pre>
<strong>Input:</strong> n = 3, queries = [[1,1,2,2],[0,0,1,1]]
<strong>Output:</strong> [[1,1,0],[1,2,1],[0,1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example22.png" style="width: 261px; height: 82px;" />
<pre>
<strong>Input:</strong> n = 2, queries = [[0,0,1,1]]
<strong>Output:</strong> [[1,1],[1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 500</code></li>
<li><code>1 <= queries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= row1<sub>i</sub> <= row2<sub>i</sub> < n</code></li>
<li><code>0 <= col1<sub>i</sub> <= col2<sub>i</sub> < n</code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Java
|
class Solution {
public int[][] rangeAddQueries(int n, int[][] queries) {
int[][] mat = new int[n][n];
for (var q : queries) {
int x1 = q[0], y1 = q[1], x2 = q[2], y2 = q[3];
mat[x1][y1]++;
if (x2 + 1 < n) {
mat[x2 + 1][y1]--;
}
if (y2 + 1 < n) {
mat[x1][y2 + 1]--;
}
if (x2 + 1 < n && y2 + 1 < n) {
mat[x2 + 1][y2 + 1]++;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i > 0) {
mat[i][j] += mat[i - 1][j];
}
if (j > 0) {
mat[i][j] += mat[i][j - 1];
}
if (i > 0 && j > 0) {
mat[i][j] -= mat[i - 1][j - 1];
}
}
}
return mat;
}
}
|
2,536
|
Increment Submatrices by One
|
Medium
|
<p>You are given a positive integer <code>n</code>, indicating that we initially have an <code>n x n</code> <strong>0-indexed</strong> integer matrix <code>mat</code> filled with zeroes.</p>
<p>You are also given a 2D integer array <code>query</code>. For each <code>query[i] = [row1<sub>i</sub>, col1<sub>i</sub>, row2<sub>i</sub>, col2<sub>i</sub>]</code>, you should do the following operation:</p>
<ul>
<li>Add <code>1</code> to <strong>every element</strong> in the submatrix with the <strong>top left</strong> corner <code>(row1<sub>i</sub>, col1<sub>i</sub>)</code> and the <strong>bottom right</strong> corner <code>(row2<sub>i</sub>, col2<sub>i</sub>)</code>. That is, add <code>1</code> to <code>mat[x][y]</code> for all <code>row1<sub>i</sub> <= x <= row2<sub>i</sub></code> and <code>col1<sub>i</sub> <= y <= col2<sub>i</sub></code>.</li>
</ul>
<p>Return<em> the matrix</em> <code>mat</code><em> after performing every query.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example11.png" style="width: 531px; height: 121px;" />
<pre>
<strong>Input:</strong> n = 3, queries = [[1,1,2,2],[0,0,1,1]]
<strong>Output:</strong> [[1,1,0],[1,2,1],[0,1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2536.Increment%20Submatrices%20by%20One/images/p2example22.png" style="width: 261px; height: 82px;" />
<pre>
<strong>Input:</strong> n = 2, queries = [[0,0,1,1]]
<strong>Output:</strong> [[1,1],[1,1]]
<strong>Explanation:</strong> The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 500</code></li>
<li><code>1 <= queries.length <= 10<sup>4</sup></code></li>
<li><code>0 <= row1<sub>i</sub> <= row2<sub>i</sub> < n</code></li>
<li><code>0 <= col1<sub>i</sub> <= col2<sub>i</sub> < n</code></li>
</ul>
|
Array; Matrix; Prefix Sum
|
Python
|
class Solution:
def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
mat = [[0] * n for _ in range(n)]
for x1, y1, x2, y2 in queries:
mat[x1][y1] += 1
if x2 + 1 < n:
mat[x2 + 1][y1] -= 1
if y2 + 1 < n:
mat[x1][y2 + 1] -= 1
if x2 + 1 < n and y2 + 1 < n:
mat[x2 + 1][y2 + 1] += 1
for i in range(n):
for j in range(n):
if i:
mat[i][j] += mat[i - 1][j]
if j:
mat[i][j] += mat[i][j - 1]
if i and j:
mat[i][j] -= mat[i - 1][j - 1]
return mat
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
C++
|
class Solution {
public:
long long countGood(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
long long ans = 0;
long long cur = 0;
int i = 0;
for (int& x : nums) {
cur += cnt[x]++;
while (cur - cnt[nums[i]] + 1 >= k) {
cur -= --cnt[nums[i++]];
}
if (cur >= k) {
ans += i + 1;
}
}
return ans;
}
};
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Go
|
func countGood(nums []int, k int) int64 {
cnt := map[int]int{}
ans, cur := 0, 0
i := 0
for _, x := range nums {
cur += cnt[x]
cnt[x]++
for cur-cnt[nums[i]]+1 >= k {
cnt[nums[i]]--
cur -= cnt[nums[i]]
i++
}
if cur >= k {
ans += i + 1
}
}
return int64(ans)
}
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Java
|
class Solution {
public long countGood(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
long ans = 0, cur = 0;
int i = 0;
for (int x : nums) {
cur += cnt.merge(x, 1, Integer::sum) - 1;
while (cur - cnt.get(nums[i]) + 1 >= k) {
cur -= cnt.merge(nums[i++], -1, Integer::sum);
}
if (cur >= k) {
ans += i + 1;
}
}
return ans;
}
}
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Python
|
class Solution:
def countGood(self, nums: List[int], k: int) -> int:
cnt = Counter()
ans = cur = 0
i = 0
for x in nums:
cur += cnt[x]
cnt[x] += 1
while cur - cnt[nums[i]] + 1 >= k:
cnt[nums[i]] -= 1
cur -= cnt[nums[i]]
i += 1
if cur >= k:
ans += i + 1
return ans
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn count_good(nums: Vec<i32>, k: i32) -> i64 {
let mut cnt = HashMap::new();
let (mut ans, mut cur, mut i) = (0i64, 0i64, 0);
for &x in &nums {
cur += *cnt.get(&x).unwrap_or(&0);
*cnt.entry(x).or_insert(0) += 1;
while cur - (cnt[&nums[i]] - 1) >= k as i64 {
*cnt.get_mut(&nums[i]).unwrap() -= 1;
cur -= cnt[&nums[i]];
i += 1;
}
if cur >= k as i64 {
ans += (i + 1) as i64;
}
}
ans
}
}
|
2,537
|
Count the Number of Good Subarrays
|
Medium
|
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good</strong> subarrays of</em> <code>nums</code>.</p>
<p>A subarray <code>arr</code> is <strong>good</strong> if there are <strong>at least </strong><code>k</code> pairs of indices <code>(i, j)</code> such that <code>i < j</code> and <code>arr[i] == arr[j]</code>.</p>
<p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,1,1,1,1], k = 10
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good subarray is the array nums itself.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,1,4,3,2,2,4], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 different good subarrays:
- [3,1,4,3,2,2] that has 2 pairs.
- [3,1,4,3,2,2,4] that has 3 pairs.
- [1,4,3,2,2,4] that has 2 pairs.
- [4,3,2,2,4] that has 2 pairs.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Sliding Window
|
TypeScript
|
function countGood(nums: number[], k: number): number {
const cnt: Map<number, number> = new Map();
let [ans, cur, i] = [0, 0, 0];
for (const x of nums) {
const count = cnt.get(x) || 0;
cur += count;
cnt.set(x, count + 1);
while (cur - (cnt.get(nums[i])! - 1) >= k) {
const countI = cnt.get(nums[i])!;
cnt.set(nums[i], countI - 1);
cur -= countI - 1;
i += 1;
}
if (cur >= k) {
ans += i + 1;
}
}
return ans;
}
|
2,538
|
Difference Between Maximum and Minimum Price Sum
|
Hard
|
<p>There exists an undirected and initially unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p>
<p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p>
<p>The tree can be rooted at any node <code>root</code> of your choice. The incurred <strong>cost</strong> after choosing <code>root</code> is the difference between the maximum and minimum <strong>price sum</strong> amongst all paths starting at <code>root</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible <strong>cost</strong></em> <em>amongst all possible root choices</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/example14.png" style="width: 556px; height: 231px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.
- The second path contains the node [2] with the price [7].
The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/p1_example2.png" style="width: 352px; height: 184px;" />
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]], price = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.
- The second path contains node [0] with a price [1].
The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>price.length == n</code></li>
<li><code>1 <= price[i] <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
C++
|
class Solution {
public:
long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {
vector<vector<int>> g(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
using ll = long long;
using pll = pair<ll, ll>;
ll ans = 0;
function<pll(int, int)> dfs = [&](int i, int fa) {
ll a = price[i], b = 0;
for (int j : g[i]) {
if (j != fa) {
auto [c, d] = dfs(j, i);
ans = max({ans, a + d, b + c});
a = max(a, price[i] + c);
b = max(b, price[i] + d);
}
}
return pll{a, b};
};
dfs(0, -1);
return ans;
}
};
|
2,538
|
Difference Between Maximum and Minimum Price Sum
|
Hard
|
<p>There exists an undirected and initially unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p>
<p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p>
<p>The tree can be rooted at any node <code>root</code> of your choice. The incurred <strong>cost</strong> after choosing <code>root</code> is the difference between the maximum and minimum <strong>price sum</strong> amongst all paths starting at <code>root</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible <strong>cost</strong></em> <em>amongst all possible root choices</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/example14.png" style="width: 556px; height: 231px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.
- The second path contains the node [2] with the price [7].
The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/p1_example2.png" style="width: 352px; height: 184px;" />
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]], price = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.
- The second path contains node [0] with a price [1].
The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>price.length == n</code></li>
<li><code>1 <= price[i] <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Go
|
func maxOutput(n int, edges [][]int, price []int) int64 {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
type pair struct{ a, b int }
ans := 0
var dfs func(i, fa int) pair
dfs = func(i, fa int) pair {
a, b := price[i], 0
for _, j := range g[i] {
if j != fa {
e := dfs(j, i)
c, d := e.a, e.b
ans = max(ans, max(a+d, b+c))
a = max(a, price[i]+c)
b = max(b, price[i]+d)
}
}
return pair{a, b}
}
dfs(0, -1)
return int64(ans)
}
|
2,538
|
Difference Between Maximum and Minimum Price Sum
|
Hard
|
<p>There exists an undirected and initially unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p>
<p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p>
<p>The tree can be rooted at any node <code>root</code> of your choice. The incurred <strong>cost</strong> after choosing <code>root</code> is the difference between the maximum and minimum <strong>price sum</strong> amongst all paths starting at <code>root</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible <strong>cost</strong></em> <em>amongst all possible root choices</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/example14.png" style="width: 556px; height: 231px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.
- The second path contains the node [2] with the price [7].
The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/p1_example2.png" style="width: 352px; height: 184px;" />
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]], price = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.
- The second path contains node [0] with a price [1].
The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>price.length == n</code></li>
<li><code>1 <= price[i] <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Java
|
class Solution {
private List<Integer>[] g;
private long ans;
private int[] price;
public long maxOutput(int n, int[][] edges, int[] price) {
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
this.price = price;
dfs(0, -1);
return ans;
}
private long[] dfs(int i, int fa) {
long a = price[i], b = 0;
for (int j : g[i]) {
if (j != fa) {
var e = dfs(j, i);
long c = e[0], d = e[1];
ans = Math.max(ans, Math.max(a + d, b + c));
a = Math.max(a, price[i] + c);
b = Math.max(b, price[i] + d);
}
}
return new long[] {a, b};
}
}
|
2,538
|
Difference Between Maximum and Minimum Price Sum
|
Hard
|
<p>There exists an undirected and initially unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Each node has an associated price. You are given an integer array <code>price</code>, where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> node.</p>
<p>The <strong>price sum</strong> of a given path is the sum of the prices of all nodes lying on that path.</p>
<p>The tree can be rooted at any node <code>root</code> of your choice. The incurred <strong>cost</strong> after choosing <code>root</code> is the difference between the maximum and minimum <strong>price sum</strong> amongst all paths starting at <code>root</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible <strong>cost</strong></em> <em>amongst all possible root choices</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/example14.png" style="width: 556px; height: 231px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.
- The second path contains the node [2] with the price [7].
The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2538.Difference%20Between%20Maximum%20and%20Minimum%20Price%20Sum/images/p1_example2.png" style="width: 352px; height: 184px;" />
<pre>
<strong>Input:</strong> n = 3, edges = [[0,1],[1,2]], price = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.
- The second path contains node [0] with a price [1].
The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>edges.length == n - 1</code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1</code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>price.length == n</code></li>
<li><code>1 <= price[i] <= 10<sup>5</sup></code></li>
</ul>
|
Tree; Depth-First Search; Array; Dynamic Programming
|
Python
|
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
def dfs(i, fa):
a, b = price[i], 0
for j in g[i]:
if j != fa:
c, d = dfs(j, i)
nonlocal ans
ans = max(ans, a + d, b + c)
a = max(a, price[i] + c)
b = max(b, price[i] + d)
return a, b
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans
|
2,539
|
Count the Number of Good Subsequences
|
Medium
|
<p>A <strong>subsequence</strong> of a string is good if it is not empty and the frequency of each one of its characters is the same.</p>
<p>Given a string <code>s</code>, return <em>the number of good subsequences of</em> <code>s</code>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabb"
<strong>Output:</strong> 11
<strong>Explanation:</strong> The total number of subsequences is <code>2<sup>4</sup>. </code>There are five subsequences which are not good: "<strong><u>aab</u></strong>b", "a<u><strong>abb</strong></u>", "<strong><u>a</u></strong>a<u><strong>bb</strong></u>", "<u><strong>aa</strong></u>b<strong><u>b</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-5 = 11</code>.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "leet"
<strong>Output:</strong> 12
<strong>Explanation:</strong> There are four subsequences which are not good: "<strong><u>l</u><em>ee</em></strong>t", "l<u><strong>eet</strong></u>", "<strong><u>leet</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-4 = 12</code>.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 15
<strong>Explanation:</strong> All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is <code>2<sup>4</sup>-1 = 15</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; Math; String; Combinatorics; Counting
|
C++
|
int N = 10001;
int MOD = 1e9 + 7;
long f[10001];
long g[10001];
long qmi(long a, long k, long p) {
long res = 1;
while (k != 0) {
if ((k & 1) == 1) {
res = res * a % p;
}
k >>= 1;
a = a * a % p;
}
return res;
}
int init = []() {
f[0] = 1;
g[0] = 1;
for (int i = 1; i < N; ++i) {
f[i] = f[i - 1] * i % MOD;
g[i] = qmi(f[i], MOD - 2, MOD);
}
return 0;
}();
int comb(int n, int k) {
return (f[n] * g[k] % MOD) * g[n - k] % MOD;
}
class Solution {
public:
int countGoodSubsequences(string s) {
int cnt[26]{};
int mx = 1;
for (char& c : s) {
mx = max(mx, ++cnt[c - 'a']);
}
long ans = 0;
for (int i = 1; i <= mx; ++i) {
long x = 1;
for (int j = 0; j < 26; ++j) {
if (cnt[j] >= i) {
x = (x * (comb(cnt[j], i) + 1)) % MOD;
}
}
ans = (ans + x - 1) % MOD;
}
return ans;
}
};
|
2,539
|
Count the Number of Good Subsequences
|
Medium
|
<p>A <strong>subsequence</strong> of a string is good if it is not empty and the frequency of each one of its characters is the same.</p>
<p>Given a string <code>s</code>, return <em>the number of good subsequences of</em> <code>s</code>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabb"
<strong>Output:</strong> 11
<strong>Explanation:</strong> The total number of subsequences is <code>2<sup>4</sup>. </code>There are five subsequences which are not good: "<strong><u>aab</u></strong>b", "a<u><strong>abb</strong></u>", "<strong><u>a</u></strong>a<u><strong>bb</strong></u>", "<u><strong>aa</strong></u>b<strong><u>b</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-5 = 11</code>.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "leet"
<strong>Output:</strong> 12
<strong>Explanation:</strong> There are four subsequences which are not good: "<strong><u>l</u><em>ee</em></strong>t", "l<u><strong>eet</strong></u>", "<strong><u>leet</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-4 = 12</code>.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 15
<strong>Explanation:</strong> All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is <code>2<sup>4</sup>-1 = 15</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; Math; String; Combinatorics; Counting
|
Go
|
const n = 1e4 + 1
const mod = 1e9 + 7
var f = make([]int, n)
var g = make([]int, n)
func qmi(a, k, p int) int {
res := 1
for k != 0 {
if k&1 == 1 {
res = res * a % p
}
k >>= 1
a = a * a % p
}
return res
}
func init() {
f[0], g[0] = 1, 1
for i := 1; i < n; i++ {
f[i] = f[i-1] * i % mod
g[i] = qmi(f[i], mod-2, mod)
}
}
func comb(n, k int) int {
return (f[n] * g[k] % mod) * g[n-k] % mod
}
func countGoodSubsequences(s string) (ans int) {
cnt := [26]int{}
mx := 1
for _, c := range s {
cnt[c-'a']++
mx = max(mx, cnt[c-'a'])
}
for i := 1; i <= mx; i++ {
x := 1
for _, v := range cnt {
if v >= i {
x = (x * (comb(v, i) + 1)) % mod
}
}
ans = (ans + x - 1) % mod
}
return
}
|
2,539
|
Count the Number of Good Subsequences
|
Medium
|
<p>A <strong>subsequence</strong> of a string is good if it is not empty and the frequency of each one of its characters is the same.</p>
<p>Given a string <code>s</code>, return <em>the number of good subsequences of</em> <code>s</code>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabb"
<strong>Output:</strong> 11
<strong>Explanation:</strong> The total number of subsequences is <code>2<sup>4</sup>. </code>There are five subsequences which are not good: "<strong><u>aab</u></strong>b", "a<u><strong>abb</strong></u>", "<strong><u>a</u></strong>a<u><strong>bb</strong></u>", "<u><strong>aa</strong></u>b<strong><u>b</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-5 = 11</code>.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "leet"
<strong>Output:</strong> 12
<strong>Explanation:</strong> There are four subsequences which are not good: "<strong><u>l</u><em>ee</em></strong>t", "l<u><strong>eet</strong></u>", "<strong><u>leet</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-4 = 12</code>.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 15
<strong>Explanation:</strong> All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is <code>2<sup>4</sup>-1 = 15</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; Math; String; Combinatorics; Counting
|
Java
|
class Solution {
private static final int N = 10001;
private static final int MOD = (int) 1e9 + 7;
private static final long[] F = new long[N];
private static final long[] G = new long[N];
static {
F[0] = 1;
G[0] = 1;
for (int i = 1; i < N; ++i) {
F[i] = F[i - 1] * i % MOD;
G[i] = qmi(F[i], MOD - 2, MOD);
}
}
public static long qmi(long a, long k, long p) {
long res = 1;
while (k != 0) {
if ((k & 1) == 1) {
res = res * a % p;
}
k >>= 1;
a = a * a % p;
}
return res;
}
public static long comb(int n, int k) {
return (F[n] * G[k] % MOD) * G[n - k] % MOD;
}
public int countGoodSubsequences(String s) {
int[] cnt = new int[26];
int mx = 1;
for (int i = 0; i < s.length(); ++i) {
mx = Math.max(mx, ++cnt[s.charAt(i) - 'a']);
}
long ans = 0;
for (int i = 1; i <= mx; ++i) {
long x = 1;
for (int j = 0; j < 26; ++j) {
if (cnt[j] >= i) {
x = x * (comb(cnt[j], i) + 1) % MOD;
}
}
ans = (ans + x - 1) % MOD;
}
return (int) ans;
}
}
|
2,539
|
Count the Number of Good Subsequences
|
Medium
|
<p>A <strong>subsequence</strong> of a string is good if it is not empty and the frequency of each one of its characters is the same.</p>
<p>Given a string <code>s</code>, return <em>the number of good subsequences of</em> <code>s</code>. Since the answer may be too large, return it modulo <code>10<sup>9</sup> + 7</code>.</p>
<p>A <strong>subsequence</strong> is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabb"
<strong>Output:</strong> 11
<strong>Explanation:</strong> The total number of subsequences is <code>2<sup>4</sup>. </code>There are five subsequences which are not good: "<strong><u>aab</u></strong>b", "a<u><strong>abb</strong></u>", "<strong><u>a</u></strong>a<u><strong>bb</strong></u>", "<u><strong>aa</strong></u>b<strong><u>b</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-5 = 11</code>.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "leet"
<strong>Output:</strong> 12
<strong>Explanation:</strong> There are four subsequences which are not good: "<strong><u>l</u><em>ee</em></strong>t", "l<u><strong>eet</strong></u>", "<strong><u>leet</u></strong>", and the empty subsequence. Hence, the number of good subsequences is <code>2<sup>4</sup>-4 = 12</code>.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> 15
<strong>Explanation:</strong> All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is <code>2<sup>4</sup>-1 = 15</code>.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
Hash Table; Math; String; Combinatorics; Counting
|
Python
|
N = 10001
MOD = 10**9 + 7
f = [1] * N
g = [1] * N
for i in range(1, N):
f[i] = f[i - 1] * i % MOD
g[i] = pow(f[i], MOD - 2, MOD)
def comb(n, k):
return f[n] * g[k] * g[n - k] % MOD
class Solution:
def countGoodSubsequences(self, s: str) -> int:
cnt = Counter(s)
ans = 0
for i in range(1, max(cnt.values()) + 1):
x = 1
for v in cnt.values():
if v >= i:
x = x * (comb(v, i) + 1) % MOD
ans = (ans + x - 1) % MOD
return ans
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
C
|
int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int i = 0;
int j = 0;
while (i < nums1Size && j < nums2Size) {
if (nums1[i] == nums2[j]) {
return nums1[i];
}
if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return -1;
}
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
C++
|
class Solution {
public:
int getCommon(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
for (int i = 0, j = 0; i < m && j < n;) {
if (nums1[i] == nums2[j]) {
return nums1[i];
}
if (nums1[i] < nums2[j]) {
++i;
} else {
++j;
}
}
return -1;
}
};
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
Go
|
func getCommon(nums1 []int, nums2 []int) int {
m, n := len(nums1), len(nums2)
for i, j := 0, 0; i < m && j < n; {
if nums1[i] == nums2[j] {
return nums1[i]
}
if nums1[i] < nums2[j] {
i++
} else {
j++
}
}
return -1
}
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
Java
|
class Solution {
public int getCommon(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
for (int i = 0, j = 0; i < m && j < n;) {
if (nums1[i] == nums2[j]) {
return nums1[i];
}
if (nums1[i] < nums2[j]) {
++i;
} else {
++j;
}
}
return -1;
}
}
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
Python
|
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
i = j = 0
m, n = len(nums1), len(nums2)
while i < m and j < n:
if nums1[i] == nums2[j]:
return nums1[i]
if nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
Rust
|
impl Solution {
pub fn get_common(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let m = nums1.len();
let n = nums2.len();
let mut i = 0;
let mut j = 0;
while i < m && j < n {
if nums1[i] == nums2[j] {
return nums1[i];
}
if nums1[i] < nums2[j] {
i += 1;
} else {
j += 1;
}
}
-1
}
}
|
2,540
|
Minimum Common Value
|
Easy
|
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in non-decreasing order, return <em>the <strong>minimum integer common</strong> to both arrays</em>. If there is no common integer amongst <code>nums1</code> and <code>nums2</code>, return <code>-1</code>.</p>
<p>Note that an integer is said to be <strong>common</strong> to <code>nums1</code> and <code>nums2</code> if both arrays have <strong>at least one</strong> occurrence of that integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The smallest element common to both arrays is 2, so we return 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3,6], nums2 = [2,3,4,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums1.length, nums2.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li>Both <code>nums1</code> and <code>nums2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
|
Array; Hash Table; Two Pointers; Binary Search
|
TypeScript
|
function getCommon(nums1: number[], nums2: number[]): number {
const m = nums1.length;
const n = nums2.length;
let i = 0;
let j = 0;
while (i < m && j < n) {
if (nums1[i] === nums2[j]) {
return nums1[i];
}
if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return -1;
}
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
C
|
long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) {
if (k == 0) {
for (int i = 0; i < nums1Size; i++) {
if (nums1[i] != nums2[i]) {
return -1;
}
}
return 0;
}
long long sum1 = 0;
long long sum2 = 0;
for (int i = 0; i < nums1Size; i++) {
long long diff = nums1[i] - nums2[i];
sum1 += diff;
if (diff % k != 0) {
return -1;
}
sum2 += llabs(diff);
}
if (sum1 != 0) {
return -1;
}
return sum2 / (k * 2);
}
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
C++
|
class Solution {
public:
long long minOperations(vector<int>& nums1, vector<int>& nums2, int k) {
long long ans = 0, x = 0;
for (int i = 0; i < nums1.size(); ++i) {
int a = nums1[i], b = nums2[i];
if (k == 0) {
if (a != b) {
return -1;
}
continue;
}
if ((a - b) % k != 0) {
return -1;
}
int y = (a - b) / k;
ans += abs(y);
x += y;
}
return x == 0 ? ans / 2 : -1;
}
};
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
Go
|
func minOperations(nums1 []int, nums2 []int, k int) int64 {
ans, x := 0, 0
for i, a := range nums1 {
b := nums2[i]
if k == 0 {
if a != b {
return -1
}
continue
}
if (a-b)%k != 0 {
return -1
}
y := (a - b) / k
ans += abs(y)
x += y
}
if x != 0 {
return -1
}
return int64(ans / 2)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
Java
|
class Solution {
public long minOperations(int[] nums1, int[] nums2, int k) {
long ans = 0, x = 0;
for (int i = 0; i < nums1.length; ++i) {
int a = nums1[i], b = nums2[i];
if (k == 0) {
if (a != b) {
return -1;
}
continue;
}
if ((a - b) % k != 0) {
return -1;
}
int y = (a - b) / k;
ans += Math.abs(y);
x += y;
}
return x == 0 ? ans / 2 : -1;
}
}
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
Python
|
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:
ans = x = 0
for a, b in zip(nums1, nums2):
if k == 0:
if a != b:
return -1
continue
if (a - b) % k:
return -1
y = (a - b) // k
ans += abs(y)
x += y
return -1 if x else ans // 2
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
Rust
|
impl Solution {
pub fn min_operations(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> i64 {
let k = k as i64;
let n = nums1.len();
if k == 0 {
return if nums1.iter().enumerate().all(|(i, &v)| v == nums2[i]) {
0
} else {
-1
};
}
let mut sum1 = 0;
let mut sum2 = 0;
for i in 0..n {
let diff = (nums1[i] - nums2[i]) as i64;
sum1 += diff;
if diff % k != 0 {
return -1;
}
sum2 += diff.abs();
}
if sum1 != 0 {
return -1;
}
sum2 / (k * 2)
}
}
|
2,541
|
Minimum Operations to Make Array Equal II
|
Medium
|
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and an integer <code>k</code>. You can perform the following operation on <code>nums1</code>:</p>
<ul>
<li>Choose two indexes <code>i</code> and <code>j</code> and increment <code>nums1[i]</code> by <code>k</code> and decrement <code>nums1[j]</code> by <code>k</code>. In other words, <code>nums1[i] = nums1[i] + k</code> and <code>nums1[j] = nums1[j] - k</code>.</li>
</ul>
<p><code>nums1</code> is said to be <strong>equal</strong> to <code>nums2</code> if for all indices <code>i</code> such that <code>0 <= i < n</code>, <code>nums1[i] == nums2[i]</code>.</p>
<p>Return <em>the <strong>minimum</strong> number of operations required to make </em><code>nums1</code><em> equal to </em><code>nums2</code>. If it is impossible to make them equal, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> In 2 operations, we can transform nums1 to nums2.
1<sup>st</sup> operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2<sup>nd</sup> operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].
One can prove that it is impossible to make arrays equal in fewer operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be proved that it is impossible to make the two arrays equal.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
|
Greedy; Array; Math
|
TypeScript
|
function minOperations(nums1: number[], nums2: number[], k: number): number {
const n = nums1.length;
if (k === 0) {
return nums1.every((v, i) => v === nums2[i]) ? 0 : -1;
}
let sum1 = 0;
let sum2 = 0;
for (let i = 0; i < n; i++) {
const diff = nums1[i] - nums2[i];
sum1 += diff;
if (diff % k !== 0) {
return -1;
}
sum2 += Math.abs(diff);
}
if (sum1 !== 0) {
return -1;
}
return sum2 / (k * 2);
}
|
2,542
|
Maximum Subsequence Score
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and a positive integer <code>k</code>. You must choose a <strong>subsequence</strong> of indices from <code>nums1</code> of length <code>k</code>.</p>
<p>For chosen indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ..., <code>i<sub>k - 1</sub></code>, your <strong>score</strong> is defined as:</p>
<ul>
<li>The sum of the selected elements from <code>nums1</code> multiplied with the <strong>minimum</strong> of the selected elements from <code>nums2</code>.</li>
<li>It can defined simply as: <code>(nums1[i<sub>0</sub>] + nums1[i<sub>1</sub>] +...+ nums1[i<sub>k - 1</sub>]) * min(nums2[i<sub>0</sub>] , nums2[i<sub>1</sub>], ... ,nums2[i<sub>k - 1</sub>])</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible score.</em></p>
<p>A <strong>subsequence</strong> of indices of an array is a set that can be derived from the set <code>{0, 1, ..., n-1}</code> by deleting some or no elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong>
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
<strong>Output:</strong> 30
<strong>Explanation:</strong>
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long maxScore(vector<int>& nums1, vector<int>& nums2, int k) {
int n = nums1.size();
vector<pair<int, int>> nums(n);
for (int i = 0; i < n; ++i) {
nums[i] = {-nums2[i], nums1[i]};
}
sort(nums.begin(), nums.end());
priority_queue<int, vector<int>, greater<int>> q;
long long ans = 0, s = 0;
for (auto& [a, b] : nums) {
s += b;
q.push(b);
if (q.size() == k) {
ans = max(ans, s * -a);
s -= q.top();
q.pop();
}
}
return ans;
}
};
|
2,542
|
Maximum Subsequence Score
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and a positive integer <code>k</code>. You must choose a <strong>subsequence</strong> of indices from <code>nums1</code> of length <code>k</code>.</p>
<p>For chosen indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ..., <code>i<sub>k - 1</sub></code>, your <strong>score</strong> is defined as:</p>
<ul>
<li>The sum of the selected elements from <code>nums1</code> multiplied with the <strong>minimum</strong> of the selected elements from <code>nums2</code>.</li>
<li>It can defined simply as: <code>(nums1[i<sub>0</sub>] + nums1[i<sub>1</sub>] +...+ nums1[i<sub>k - 1</sub>]) * min(nums2[i<sub>0</sub>] , nums2[i<sub>1</sub>], ... ,nums2[i<sub>k - 1</sub>])</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible score.</em></p>
<p>A <strong>subsequence</strong> of indices of an array is a set that can be derived from the set <code>{0, 1, ..., n-1}</code> by deleting some or no elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong>
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
<strong>Output:</strong> 30
<strong>Explanation:</strong>
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Go
|
func maxScore(nums1 []int, nums2 []int, k int) int64 {
type pair struct{ a, b int }
nums := []pair{}
for i, a := range nums1 {
b := nums2[i]
nums = append(nums, pair{a, b})
}
sort.Slice(nums, func(i, j int) bool { return nums[i].b > nums[j].b })
q := hp{}
var ans, s int
for _, e := range nums {
a, b := e.a, e.b
s += a
heap.Push(&q, a)
if q.Len() == k {
ans = max(ans, s*b)
s -= heap.Pop(&q).(int)
}
}
return int64(ans)
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
2,542
|
Maximum Subsequence Score
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and a positive integer <code>k</code>. You must choose a <strong>subsequence</strong> of indices from <code>nums1</code> of length <code>k</code>.</p>
<p>For chosen indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ..., <code>i<sub>k - 1</sub></code>, your <strong>score</strong> is defined as:</p>
<ul>
<li>The sum of the selected elements from <code>nums1</code> multiplied with the <strong>minimum</strong> of the selected elements from <code>nums2</code>.</li>
<li>It can defined simply as: <code>(nums1[i<sub>0</sub>] + nums1[i<sub>1</sub>] +...+ nums1[i<sub>k - 1</sub>]) * min(nums2[i<sub>0</sub>] , nums2[i<sub>1</sub>], ... ,nums2[i<sub>k - 1</sub>])</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible score.</em></p>
<p>A <strong>subsequence</strong> of indices of an array is a set that can be derived from the set <code>{0, 1, ..., n-1}</code> by deleting some or no elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong>
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
<strong>Output:</strong> 30
<strong>Explanation:</strong>
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long maxScore(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
int[][] nums = new int[n][2];
for (int i = 0; i < n; ++i) {
nums[i] = new int[] {nums1[i], nums2[i]};
}
Arrays.sort(nums, (a, b) -> b[1] - a[1]);
long ans = 0, s = 0;
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < n; ++i) {
s += nums[i][0];
q.offer(nums[i][0]);
if (q.size() == k) {
ans = Math.max(ans, s * nums[i][1]);
s -= q.poll();
}
}
return ans;
}
}
|
2,542
|
Maximum Subsequence Score
|
Medium
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length <code>n</code> and a positive integer <code>k</code>. You must choose a <strong>subsequence</strong> of indices from <code>nums1</code> of length <code>k</code>.</p>
<p>For chosen indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ..., <code>i<sub>k - 1</sub></code>, your <strong>score</strong> is defined as:</p>
<ul>
<li>The sum of the selected elements from <code>nums1</code> multiplied with the <strong>minimum</strong> of the selected elements from <code>nums2</code>.</li>
<li>It can defined simply as: <code>(nums1[i<sub>0</sub>] + nums1[i<sub>1</sub>] +...+ nums1[i<sub>k - 1</sub>]) * min(nums2[i<sub>0</sub>] , nums2[i<sub>1</sub>], ... ,nums2[i<sub>k - 1</sub>])</code>.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> possible score.</em></p>
<p>A <strong>subsequence</strong> of indices of an array is a set that can be derived from the set <code>{0, 1, ..., n-1}</code> by deleting some or no elements.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
<strong>Output:</strong> 12
<strong>Explanation:</strong>
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
<strong>Output:</strong> 30
<strong>Explanation:</strong>
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums1.length == nums2.length</code></li>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>0 <= nums1[i], nums2[j] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Greedy; Array; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums = sorted(zip(nums2, nums1), reverse=True)
q = []
ans = s = 0
for a, b in nums:
s += b
heappush(q, b)
if len(q) == k:
ans = max(ans, s * a)
s -= heappop(q)
return ans
|
2,543
|
Check if Point Is Reachable
|
Hard
|
<p>There exists an infinitely large grid. You are currently at point <code>(1, 1)</code>, and you need to reach the point <code>(targetX, targetY)</code> using a finite number of steps.</p>
<p>In one <strong>step</strong>, you can move from point <code>(x, y)</code> to any one of the following points:</p>
<ul>
<li><code>(x, y - x)</code></li>
<li><code>(x - y, y)</code></li>
<li><code>(2 * x, y)</code></li>
<li><code>(x, 2 * y)</code></li>
</ul>
<p>Given two integers <code>targetX</code> and <code>targetY</code> representing the X-coordinate and Y-coordinate of your final position, return <code>true</code> <em>if you can reach the point from</em> <code>(1, 1)</code> <em>using some number of steps, and </em><code>false</code><em> otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> targetX = 6, targetY = 9
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> targetX = 4, targetY = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= targetX, targetY <= 10<sup>9</sup></code></li>
</ul>
|
Math; Number Theory
|
C++
|
class Solution {
public:
bool isReachable(int targetX, int targetY) {
int x = gcd(targetX, targetY);
return (x & (x - 1)) == 0;
}
};
|
2,543
|
Check if Point Is Reachable
|
Hard
|
<p>There exists an infinitely large grid. You are currently at point <code>(1, 1)</code>, and you need to reach the point <code>(targetX, targetY)</code> using a finite number of steps.</p>
<p>In one <strong>step</strong>, you can move from point <code>(x, y)</code> to any one of the following points:</p>
<ul>
<li><code>(x, y - x)</code></li>
<li><code>(x - y, y)</code></li>
<li><code>(2 * x, y)</code></li>
<li><code>(x, 2 * y)</code></li>
</ul>
<p>Given two integers <code>targetX</code> and <code>targetY</code> representing the X-coordinate and Y-coordinate of your final position, return <code>true</code> <em>if you can reach the point from</em> <code>(1, 1)</code> <em>using some number of steps, and </em><code>false</code><em> otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> targetX = 6, targetY = 9
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> targetX = 4, targetY = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= targetX, targetY <= 10<sup>9</sup></code></li>
</ul>
|
Math; Number Theory
|
Go
|
func isReachable(targetX int, targetY int) bool {
x := gcd(targetX, targetY)
return x&(x-1) == 0
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
|
2,543
|
Check if Point Is Reachable
|
Hard
|
<p>There exists an infinitely large grid. You are currently at point <code>(1, 1)</code>, and you need to reach the point <code>(targetX, targetY)</code> using a finite number of steps.</p>
<p>In one <strong>step</strong>, you can move from point <code>(x, y)</code> to any one of the following points:</p>
<ul>
<li><code>(x, y - x)</code></li>
<li><code>(x - y, y)</code></li>
<li><code>(2 * x, y)</code></li>
<li><code>(x, 2 * y)</code></li>
</ul>
<p>Given two integers <code>targetX</code> and <code>targetY</code> representing the X-coordinate and Y-coordinate of your final position, return <code>true</code> <em>if you can reach the point from</em> <code>(1, 1)</code> <em>using some number of steps, and </em><code>false</code><em> otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> targetX = 6, targetY = 9
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> targetX = 4, targetY = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= targetX, targetY <= 10<sup>9</sup></code></li>
</ul>
|
Math; Number Theory
|
Java
|
class Solution {
public boolean isReachable(int targetX, int targetY) {
int x = gcd(targetX, targetY);
return (x & (x - 1)) == 0;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
2,543
|
Check if Point Is Reachable
|
Hard
|
<p>There exists an infinitely large grid. You are currently at point <code>(1, 1)</code>, and you need to reach the point <code>(targetX, targetY)</code> using a finite number of steps.</p>
<p>In one <strong>step</strong>, you can move from point <code>(x, y)</code> to any one of the following points:</p>
<ul>
<li><code>(x, y - x)</code></li>
<li><code>(x - y, y)</code></li>
<li><code>(2 * x, y)</code></li>
<li><code>(x, 2 * y)</code></li>
</ul>
<p>Given two integers <code>targetX</code> and <code>targetY</code> representing the X-coordinate and Y-coordinate of your final position, return <code>true</code> <em>if you can reach the point from</em> <code>(1, 1)</code> <em>using some number of steps, and </em><code>false</code><em> otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> targetX = 6, targetY = 9
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> targetX = 4, targetY = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= targetX, targetY <= 10<sup>9</sup></code></li>
</ul>
|
Math; Number Theory
|
Python
|
class Solution:
def isReachable(self, targetX: int, targetY: int) -> bool:
x = gcd(targetX, targetY)
return x & (x - 1) == 0
|
2,543
|
Check if Point Is Reachable
|
Hard
|
<p>There exists an infinitely large grid. You are currently at point <code>(1, 1)</code>, and you need to reach the point <code>(targetX, targetY)</code> using a finite number of steps.</p>
<p>In one <strong>step</strong>, you can move from point <code>(x, y)</code> to any one of the following points:</p>
<ul>
<li><code>(x, y - x)</code></li>
<li><code>(x - y, y)</code></li>
<li><code>(2 * x, y)</code></li>
<li><code>(x, 2 * y)</code></li>
</ul>
<p>Given two integers <code>targetX</code> and <code>targetY</code> representing the X-coordinate and Y-coordinate of your final position, return <code>true</code> <em>if you can reach the point from</em> <code>(1, 1)</code> <em>using some number of steps, and </em><code>false</code><em> otherwise</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> targetX = 6, targetY = 9
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> targetX = 4, targetY = 7
<strong>Output:</strong> true
<strong>Explanation:</strong> You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= targetX, targetY <= 10<sup>9</sup></code></li>
</ul>
|
Math; Number Theory
|
TypeScript
|
function isReachable(targetX: number, targetY: number): boolean {
const x = gcd(targetX, targetY);
return (x & (x - 1)) === 0;
}
function gcd(a: number, b: number): number {
return b == 0 ? a : gcd(b, a % b);
}
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
C
|
int alternateDigitSum(int n) {
int ans = 0;
int sign = 1;
while (n) {
ans += (n % 10) * sign;
sign = -sign;
n /= 10;
}
return ans * -sign;
}
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
C++
|
class Solution {
public:
int alternateDigitSum(int n) {
int ans = 0, sign = 1;
for (char c : to_string(n)) {
int x = c - '0';
ans += sign * x;
sign *= -1;
}
return ans;
}
};
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
Go
|
func alternateDigitSum(n int) (ans int) {
sign := 1
for _, c := range strconv.Itoa(n) {
x := int(c - '0')
ans += sign * x
sign *= -1
}
return
}
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
Java
|
class Solution {
public int alternateDigitSum(int n) {
int ans = 0, sign = 1;
for (char c : String.valueOf(n).toCharArray()) {
int x = c - '0';
ans += sign * x;
sign *= -1;
}
return ans;
}
}
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
Python
|
class Solution:
def alternateDigitSum(self, n: int) -> int:
return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
Rust
|
impl Solution {
pub fn alternate_digit_sum(mut n: i32) -> i32 {
let mut ans = 0;
let mut sign = 1;
while n != 0 {
ans += (n % 10) * sign;
sign = -sign;
n /= 10;
}
ans * -sign
}
}
|
2,544
|
Alternating Digit Sum
|
Easy
|
<p>You are given a positive integer <code>n</code>. Each digit of <code>n</code> has a sign according to the following rules:</p>
<ul>
<li>The <strong>most significant digit</strong> is assigned a <strong>positive</strong> sign.</li>
<li>Each other digit has an opposite sign to its adjacent digits.</li>
</ul>
<p>Return <em>the sum of all digits with their corresponding sign</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 521
<strong>Output:</strong> 4
<strong>Explanation:</strong> (+5) + (-2) + (+1) = 4.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 111
<strong>Output:</strong> 1
<strong>Explanation:</strong> (+1) + (-1) + (+1) = 1.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 886996
<strong>Output:</strong> 0
<strong>Explanation:</strong> (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>9</sup></code></li>
</ul>
<p> </p>
<style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;
}
.spoiler {overflow:hidden;}
.spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;}
.spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;}
.spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}
</style>
|
Math
|
TypeScript
|
function alternateDigitSum(n: number): number {
let ans = 0;
let sign = 1;
while (n) {
ans += (n % 10) * sign;
sign = -sign;
n = Math.floor(n / 10);
}
return ans * -sign;
}
|
2,545
|
Sort the Students by Their Kth Score
|
Medium
|
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p>
<p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code> (<strong>0-indexed</strong>) exam from the highest to the lowest.</p>
<p>Return <em>the matrix after sorting it.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" />
<pre>
<strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2
<strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
<strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.
- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.
- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" />
<pre>
<strong>Input:</strong> score = [[3,4],[5,6]], k = 0
<strong>Output:</strong> [[5,6],[3,4]]
<strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.
- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == score.length</code></li>
<li><code>n == score[i].length</code></li>
<li><code>1 <= m, n <= 250</code></li>
<li><code>1 <= score[i][j] <= 10<sup>5</sup></code></li>
<li><code>score</code> consists of <strong>distinct</strong> integers.</li>
<li><code>0 <= k < n</code></li>
</ul>
|
Array; Matrix; Sorting
|
C++
|
class Solution {
public:
vector<vector<int>> sortTheStudents(vector<vector<int>>& score, int k) {
ranges::sort(score, [k](const auto& a, const auto& b) { return a[k] > b[k]; });
return score;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.