id
int64 1
3.65k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,020 |
Find the Maximum Number of Elements in Subset
|
Medium
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p>
<ul>
<li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,1,2,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Enumeration
|
Python
|
class Solution:
def maximumLength(self, nums: List[int]) -> int:
cnt = Counter(nums)
ans = cnt[1] - (cnt[1] % 2 ^ 1)
del cnt[1]
for x in cnt:
t = 0
while cnt[x] > 1:
x = x * x
t += 2
t += 1 if cnt[x] else -1
ans = max(ans, t)
return ans
|
3,020 |
Find the Maximum Number of Elements in Subset
|
Medium
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>You need to select a <span data-keyword="subset">subset</span> of <code>nums</code> which satisfies the following condition:</p>
<ul>
<li>You can place the selected elements in a <strong>0-indexed</strong> array such that it follows the pattern: <code>[x, x<sup>2</sup>, x<sup>4</sup>, ..., x<sup>k/2</sup>, x<sup>k</sup>, x<sup>k/2</sup>, ..., x<sup>4</sup>, x<sup>2</sup>, x]</code> (<strong>Note</strong> that <code>k</code> can be be any <strong>non-negative</strong> power of <code>2</code>). For example, <code>[2, 4, 16, 4, 2]</code> and <code>[3, 9, 3]</code> follow the pattern while <code>[2, 4, 8, 4, 2]</code> does not.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of elements in a subset that satisfies these conditions.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,4,1,2,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 2<sup>2</sup> == 4. Hence the answer is 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,2,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Enumeration
|
TypeScript
|
function maximumLength(nums: number[]): number {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) ?? 0) + 1);
}
let ans = cnt.has(1) ? cnt.get(1)! - (cnt.get(1)! % 2 ^ 1) : 0;
cnt.delete(1);
for (let [x, _] of cnt) {
let t = 0;
while (cnt.has(x) && cnt.get(x)! > 1) {
x = x * x;
t += 2;
}
t += cnt.has(x) ? 1 : -1;
ans = Math.max(ans, t);
}
return ans;
}
|
3,021 |
Alice and Bob Playing Flower Game
|
Medium
|
<p>Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are <code>x</code> flowers in the clockwise direction between Alice and Bob, and <code>y</code> flowers in the anti-clockwise direction between them.</p>
<p>The game proceeds as follows:</p>
<ol>
<li>Alice takes the first turn.</li>
<li>In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.</li>
<li>At the end of the turn, if there are no flowers left at all, the <strong>current</strong> player captures their opponent and wins the game.</li>
</ol>
<p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p>
<ul>
<li>Alice must win the game according to the described rules.</li>
<li>The number of flowers <code>x</code> in the clockwise direction must be in the range <code>[1,n]</code>.</li>
<li>The number of flowers <code>y</code> in the anti-clockwise direction must be in the range <code>[1,m]</code>.</li>
</ul>
<p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, m = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No pairs satisfy the conditions described in the statement.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
</ul>
|
Math
|
C++
|
class Solution {
public:
long long flowerGame(int n, int m) {
long long a1 = (n + 1) / 2;
long long b1 = (m + 1) / 2;
long long a2 = n / 2;
long long b2 = m / 2;
return a1 * b2 + a2 * b1;
}
};
|
3,021 |
Alice and Bob Playing Flower Game
|
Medium
|
<p>Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are <code>x</code> flowers in the clockwise direction between Alice and Bob, and <code>y</code> flowers in the anti-clockwise direction between them.</p>
<p>The game proceeds as follows:</p>
<ol>
<li>Alice takes the first turn.</li>
<li>In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.</li>
<li>At the end of the turn, if there are no flowers left at all, the <strong>current</strong> player captures their opponent and wins the game.</li>
</ol>
<p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p>
<ul>
<li>Alice must win the game according to the described rules.</li>
<li>The number of flowers <code>x</code> in the clockwise direction must be in the range <code>[1,n]</code>.</li>
<li>The number of flowers <code>y</code> in the anti-clockwise direction must be in the range <code>[1,m]</code>.</li>
</ul>
<p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, m = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No pairs satisfy the conditions described in the statement.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
</ul>
|
Math
|
Go
|
func flowerGame(n int, m int) int64 {
a1, b1 := (n+1)/2, (m+1)/2
a2, b2 := n/2, m/2
return int64(a1*b2 + a2*b1)
}
|
3,021 |
Alice and Bob Playing Flower Game
|
Medium
|
<p>Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are <code>x</code> flowers in the clockwise direction between Alice and Bob, and <code>y</code> flowers in the anti-clockwise direction between them.</p>
<p>The game proceeds as follows:</p>
<ol>
<li>Alice takes the first turn.</li>
<li>In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.</li>
<li>At the end of the turn, if there are no flowers left at all, the <strong>current</strong> player captures their opponent and wins the game.</li>
</ol>
<p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p>
<ul>
<li>Alice must win the game according to the described rules.</li>
<li>The number of flowers <code>x</code> in the clockwise direction must be in the range <code>[1,n]</code>.</li>
<li>The number of flowers <code>y</code> in the anti-clockwise direction must be in the range <code>[1,m]</code>.</li>
</ul>
<p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, m = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No pairs satisfy the conditions described in the statement.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
</ul>
|
Math
|
Java
|
class Solution {
public long flowerGame(int n, int m) {
long a1 = (n + 1) / 2;
long b1 = (m + 1) / 2;
long a2 = n / 2;
long b2 = m / 2;
return a1 * b2 + a2 * b1;
}
}
|
3,021 |
Alice and Bob Playing Flower Game
|
Medium
|
<p>Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are <code>x</code> flowers in the clockwise direction between Alice and Bob, and <code>y</code> flowers in the anti-clockwise direction between them.</p>
<p>The game proceeds as follows:</p>
<ol>
<li>Alice takes the first turn.</li>
<li>In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.</li>
<li>At the end of the turn, if there are no flowers left at all, the <strong>current</strong> player captures their opponent and wins the game.</li>
</ol>
<p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p>
<ul>
<li>Alice must win the game according to the described rules.</li>
<li>The number of flowers <code>x</code> in the clockwise direction must be in the range <code>[1,n]</code>.</li>
<li>The number of flowers <code>y</code> in the anti-clockwise direction must be in the range <code>[1,m]</code>.</li>
</ul>
<p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, m = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No pairs satisfy the conditions described in the statement.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
</ul>
|
Math
|
Python
|
class Solution:
def flowerGame(self, n: int, m: int) -> int:
a1 = (n + 1) // 2
b1 = (m + 1) // 2
a2 = n // 2
b2 = m // 2
return a1 * b2 + a2 * b1
|
3,021 |
Alice and Bob Playing Flower Game
|
Medium
|
<p>Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are <code>x</code> flowers in the clockwise direction between Alice and Bob, and <code>y</code> flowers in the anti-clockwise direction between them.</p>
<p>The game proceeds as follows:</p>
<ol>
<li>Alice takes the first turn.</li>
<li>In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side.</li>
<li>At the end of the turn, if there are no flowers left at all, the <strong>current</strong> player captures their opponent and wins the game.</li>
</ol>
<p>Given two integers, <code>n</code> and <code>m</code>, the task is to compute the number of possible pairs <code>(x, y)</code> that satisfy the conditions:</p>
<ul>
<li>Alice must win the game according to the described rules.</li>
<li>The number of flowers <code>x</code> in the clockwise direction must be in the range <code>[1,n]</code>.</li>
<li>The number of flowers <code>y</code> in the anti-clockwise direction must be in the range <code>[1,m]</code>.</li>
</ul>
<p>Return <em>the number of possible pairs</em> <code>(x, y)</code> <em>that satisfy the conditions mentioned in the statement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 3, m = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 1, m = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No pairs satisfy the conditions described in the statement.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, m <= 10<sup>5</sup></code></li>
</ul>
|
Math
|
TypeScript
|
function flowerGame(n: number, m: number): number {
const [a1, b1] = [(n + 1) >> 1, (m + 1) >> 1];
const [a2, b2] = [n >> 1, m >> 1];
return a1 * b2 + a2 * b1;
}
|
3,022 |
Minimize OR of Remaining Elements Using Operations
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 <= i < nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] & nums[i + 1]</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,5,3,2,7], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].
2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].
The bitwise-or of the final array is 3.
It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8].
2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].
3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].
4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].
The bitwise-or of the final array is 2.
It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1
<strong>Output:</strong> 15
<strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15.
It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>30</sup></code></li>
<li><code>0 <= k < nums.length</code></li>
</ul>
|
Greedy; Bit Manipulation; Array
|
C++
|
class Solution {
public:
int minOrAfterOperations(vector<int>& nums, int k) {
int ans = 0, rans = 0;
for (int i = 29; i >= 0; i--) {
int test = ans + (1 << i);
int cnt = 0;
int val = 0;
for (auto it : nums) {
if (val == 0) {
val = test & it;
} else {
val &= test & it;
}
if (val) {
cnt++;
}
}
if (cnt > k) {
rans += (1 << i);
} else {
ans += (1 << i);
}
}
return rans;
}
};
|
3,022 |
Minimize OR of Remaining Elements Using Operations
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 <= i < nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] & nums[i + 1]</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,5,3,2,7], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].
2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].
The bitwise-or of the final array is 3.
It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8].
2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].
3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].
4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].
The bitwise-or of the final array is 2.
It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1
<strong>Output:</strong> 15
<strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15.
It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>30</sup></code></li>
<li><code>0 <= k < nums.length</code></li>
</ul>
|
Greedy; Bit Manipulation; Array
|
Go
|
func minOrAfterOperations(nums []int, k int) int {
ans := 0
rans := 0
for i := 29; i >= 0; i-- {
test := ans + (1 << i)
cnt := 0
val := 0
for _, num := range nums {
if val == 0 {
val = test & num
} else {
val &= test & num
}
if val != 0 {
cnt++
}
}
if cnt > k {
rans += (1 << i)
} else {
ans += (1 << i)
}
}
return rans
}
|
3,022 |
Minimize OR of Remaining Elements Using Operations
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 <= i < nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] & nums[i + 1]</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,5,3,2,7], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].
2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].
The bitwise-or of the final array is 3.
It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8].
2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].
3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].
4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].
The bitwise-or of the final array is 2.
It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1
<strong>Output:</strong> 15
<strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15.
It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>30</sup></code></li>
<li><code>0 <= k < nums.length</code></li>
</ul>
|
Greedy; Bit Manipulation; Array
|
Java
|
class Solution {
public int minOrAfterOperations(int[] nums, int k) {
int ans = 0, rans = 0;
for (int i = 29; i >= 0; i--) {
int test = ans + (1 << i);
int cnt = 0;
int val = 0;
for (int num : nums) {
if (val == 0) {
val = test & num;
} else {
val &= test & num;
}
if (val != 0) {
cnt++;
}
}
if (cnt > k) {
rans += (1 << i);
} else {
ans += (1 << i);
}
}
return rans;
}
}
|
3,022 |
Minimize OR of Remaining Elements Using Operations
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>In one operation, you can pick any index <code>i</code> of <code>nums</code> such that <code>0 <= i < nums.length - 1</code> and replace <code>nums[i]</code> and <code>nums[i + 1]</code> with a single occurrence of <code>nums[i] & nums[i + 1]</code>, where <code>&</code> represents the bitwise <code>AND</code> operator.</p>
<p>Return <em>the <strong>minimum</strong> possible value of the bitwise </em><code>OR</code><em> of the remaining elements of</em> <code>nums</code> <em>after applying <strong>at most</strong></em> <code>k</code> <em>operations</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,5,3,2,7], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].
2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].
The bitwise-or of the final array is 3.
It can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [7,3,15,14,2,8], k = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> Let's do the following operations:
1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8].
2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].
3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].
4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].
The bitwise-or of the final array is 2.
It can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [10,7,10,3,9,14,9,4], k = 1
<strong>Output:</strong> 15
<strong>Explanation:</strong> Without applying any operations, the bitwise-or of nums is 15.
It can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] < 2<sup>30</sup></code></li>
<li><code>0 <= k < nums.length</code></li>
</ul>
|
Greedy; Bit Manipulation; Array
|
Python
|
class Solution:
def minOrAfterOperations(self, nums: List[int], k: int) -> int:
ans = 0
rans = 0
for i in range(29, -1, -1):
test = ans + (1 << i)
cnt = 0
val = 0
for num in nums:
if val == 0:
val = test & num
else:
val &= test & num
if val:
cnt += 1
if cnt > k:
rans += 1 << i
else:
ans += 1 << i
return rans
|
3,023 |
Find Pattern in Infinite Stream I
|
Medium
|
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p>
<p>The class <code>InfiniteStream</code> contains the following function:</p>
<ul>
<li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li>
</ul>
<p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= pattern.length <= 100</code></li>
<li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li>
<li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li>
<li>The input is generated such that the pattern's start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li>
</ul>
|
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
|
C++
|
/**
* Definition for an infinite stream.
* class InfiniteStream {
* public:
* InfiniteStream(vector<int> bits);
* int next();
* };
*/
class Solution {
public:
int findPattern(InfiniteStream* stream, vector<int>& pattern) {
long long a = 0, b = 0;
int m = pattern.size();
int half = m >> 1;
long long mask1 = (1LL << half) - 1;
long long mask2 = (1LL << (m - half)) - 1;
for (int i = 0; i < half; ++i) {
a |= (long long) pattern[i] << (half - 1 - i);
}
for (int i = half; i < m; ++i) {
b |= (long long) pattern[i] << (m - 1 - i);
}
long x = 0, y = 0;
for (int i = 1;; ++i) {
int v = stream->next();
y = y << 1 | v;
v = (int) ((y >> (m - half)) & 1);
y &= mask2;
x = x << 1 | v;
x &= mask1;
if (i >= m && a == x && b == y) {
return i - m;
}
}
}
};
|
3,023 |
Find Pattern in Infinite Stream I
|
Medium
|
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p>
<p>The class <code>InfiniteStream</code> contains the following function:</p>
<ul>
<li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li>
</ul>
<p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= pattern.length <= 100</code></li>
<li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li>
<li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li>
<li>The input is generated such that the pattern's start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li>
</ul>
|
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
|
Go
|
/**
* Definition for an infinite stream.
* type InfiniteStream interface {
* Next() int
* }
*/
func findPattern(stream InfiniteStream, pattern []int) int {
a, b := 0, 0
m := len(pattern)
half := m >> 1
mask1 := (1 << half) - 1
mask2 := (1 << (m - half)) - 1
for i := 0; i < half; i++ {
a |= pattern[i] << (half - 1 - i)
}
for i := half; i < m; i++ {
b |= pattern[i] << (m - 1 - i)
}
x, y := 0, 0
for i := 1; ; i++ {
v := stream.Next()
y = y<<1 | v
v = (y >> (m - half)) & 1
y &= mask2
x = x<<1 | v
x &= mask1
if i >= m && a == x && b == y {
return i - m
}
}
}
|
3,023 |
Find Pattern in Infinite Stream I
|
Medium
|
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p>
<p>The class <code>InfiniteStream</code> contains the following function:</p>
<ul>
<li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li>
</ul>
<p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= pattern.length <= 100</code></li>
<li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li>
<li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li>
<li>The input is generated such that the pattern's start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li>
</ul>
|
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
|
Java
|
/**
* Definition for an infinite stream.
* class InfiniteStream {
* public InfiniteStream(int[] bits);
* public int next();
* }
*/
class Solution {
public int findPattern(InfiniteStream infiniteStream, int[] pattern) {
long a = 0, b = 0;
int m = pattern.length;
int half = m >> 1;
long mask1 = (1L << half) - 1;
long mask2 = (1L << (m - half)) - 1;
for (int i = 0; i < half; ++i) {
a |= (long) pattern[i] << (half - 1 - i);
}
for (int i = half; i < m; ++i) {
b |= (long) pattern[i] << (m - 1 - i);
}
long x = 0, y = 0;
for (int i = 1;; ++i) {
int v = infiniteStream.next();
y = y << 1 | v;
v = (int) ((y >> (m - half)) & 1);
y &= mask2;
x = x << 1 | v;
x &= mask1;
if (i >= m && a == x && b == y) {
return i - m;
}
}
}
}
|
3,023 |
Find Pattern in Infinite Stream I
|
Medium
|
<p>You are given a binary array <code>pattern</code> and an object <code>stream</code> of class <code>InfiniteStream</code> representing a <strong>0-indexed</strong> infinite stream of bits.</p>
<p>The class <code>InfiniteStream</code> contains the following function:</p>
<ul>
<li><code>int next()</code>: Reads a <strong>single</strong> bit (which is either <code>0</code> or <code>1</code>) from the stream and returns it.</li>
</ul>
<p>Return <em>the <strong>first starting</strong> index where the pattern matches the bits read from the stream</em>. For example, if the pattern is <code>[1, 0]</code>, the first match is the highlighted part in the stream <code>[0, <strong><u>1, 0</u></strong>, 1, ...]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,1,1,0,1,1,1,...], pattern = [0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The first occurrence of the pattern [0,1] is highlighted in the stream [1,1,1,<strong><u>0,1</u></strong>,...], which starts at index 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> stream = [0,0,0,0,...], pattern = [0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The first occurrence of the pattern [0] is highlighted in the stream [<strong><u>0</u></strong>,...], which starts at index 0.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> stream = [1,0,1,1,0,1,1,0,1,...], pattern = [1,1,0,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The first occurrence of the pattern [1,1,0,1] is highlighted in the stream [1,0,<strong><u>1,1,0,1</u></strong>,...], which starts at index 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= pattern.length <= 100</code></li>
<li><code>pattern</code> consists only of <code>0</code> and <code>1</code>.</li>
<li><code>stream</code> consists only of <code>0</code> and <code>1</code>.</li>
<li>The input is generated such that the pattern's start index exists in the first <code>10<sup>5</sup></code> bits of the stream.</li>
</ul>
|
Array; String Matching; Sliding Window; Hash Function; Rolling Hash
|
Python
|
# Definition for an infinite stream.
# class InfiniteStream:
# def next(self) -> int:
# pass
class Solution:
def findPattern(
self, stream: Optional["InfiniteStream"], pattern: List[int]
) -> int:
a = b = 0
m = len(pattern)
half = m >> 1
mask1 = (1 << half) - 1
mask2 = (1 << (m - half)) - 1
for i in range(half):
a |= pattern[i] << (half - 1 - i)
for i in range(half, m):
b |= pattern[i] << (m - 1 - i)
x = y = 0
for i in count(1):
v = stream.next()
y = y << 1 | v
v = y >> (m - half) & 1
y &= mask2
x = x << 1 | v
x &= mask1
if i >= m and a == x and b == y:
return i - m
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
C++
|
class Solution {
public:
string triangleType(vector<int>& nums) {
sort(nums.begin(), nums.end());
if (nums[0] + nums[1] <= nums[2]) {
return "none";
}
if (nums[0] == nums[2]) {
return "equilateral";
}
if (nums[0] == nums[1] || nums[1] == nums[2]) {
return "isosceles";
}
return "scalene";
}
};
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
C#
|
public class Solution {
public string TriangleType(int[] nums) {
Array.Sort(nums);
if (nums[0] + nums[1] <= nums[2]) {
return "none";
}
if (nums[0] == nums[2]) {
return "equilateral";
}
if (nums[0] == nums[1] || nums[1] == nums[2]) {
return "isosceles";
}
return "scalene";
}
}
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
Go
|
func triangleType(nums []int) string {
sort.Ints(nums)
if nums[0]+nums[1] <= nums[2] {
return "none"
}
if nums[0] == nums[2] {
return "equilateral"
}
if nums[0] == nums[1] || nums[1] == nums[2] {
return "isosceles"
}
return "scalene"
}
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
Java
|
class Solution {
public String triangleType(int[] nums) {
Arrays.sort(nums);
if (nums[0] + nums[1] <= nums[2]) {
return "none";
}
if (nums[0] == nums[2]) {
return "equilateral";
}
if (nums[0] == nums[1] || nums[1] == nums[2]) {
return "isosceles";
}
return "scalene";
}
}
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
Python
|
class Solution:
def triangleType(self, nums: List[int]) -> str:
nums.sort()
if nums[0] + nums[1] <= nums[2]:
return "none"
if nums[0] == nums[2]:
return "equilateral"
if nums[0] == nums[1] or nums[1] == nums[2]:
return "isosceles"
return "scalene"
|
3,024 |
Type of Triangle
|
Easy
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>3</code> which can form the sides of a triangle.</p>
<ul>
<li>A triangle is called <strong>equilateral</strong> if it has all sides of equal length.</li>
<li>A triangle is called <strong>isosceles</strong> if it has exactly two sides of equal length.</li>
<li>A triangle is called <strong>scalene</strong> if all its sides are of different lengths.</li>
</ul>
<p>Return <em>a string representing</em> <em>the type of triangle that can be formed </em><em>or </em><code>"none"</code><em> if it <strong>cannot</strong> form a triangle.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,3,3]
<strong>Output:</strong> "equilateral"
<strong>Explanation:</strong> Since all the sides are of equal length, therefore, it will form an equilateral triangle.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,4,5]
<strong>Output:</strong> "scalene"
<strong>Explanation:</strong>
nums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.
nums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.
nums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3.
Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.
As all the sides are of different lengths, it will form a scalene triangle.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums.length == 3</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Math; Sorting
|
TypeScript
|
function triangleType(nums: number[]): string {
nums.sort((a, b) => a - b);
if (nums[0] + nums[1] <= nums[2]) {
return 'none';
}
if (nums[0] === nums[2]) {
return 'equilateral';
}
if (nums[0] === nums[1] || nums[1] === nums[2]) {
return 'isosceles';
}
return 'scalene';
}
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
C++
|
class Solution {
public:
int numberOfPairs(vector<vector<int>>& points) {
sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]);
});
int n = points.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = INT_MIN;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
};
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
C#
|
public class Solution {
public int NumberOfPairs(int[][] points) {
Array.Sort(points, (a, b) => a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
int ans = 0;
int n = points.Length;
int inf = 1 << 30;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = -inf;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
}
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Go
|
func numberOfPairs(points [][]int) (ans int) {
sort.Slice(points, func(i, j int) bool {
return points[i][0] < points[j][0] || points[i][0] == points[j][0] && points[j][1] < points[i][1]
})
for i, p1 := range points {
y1 := p1[1]
maxY := math.MinInt32
for _, p2 := range points[i+1:] {
y2 := p2[1]
if maxY < y2 && y2 <= y1 {
maxY = y2
ans++
}
}
}
return
}
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Java
|
class Solution {
public int numberOfPairs(int[][] points) {
Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
int ans = 0;
int n = points.length;
final int inf = 1 << 30;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = -inf;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
}
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Python
|
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: (x[0], -x[1]))
ans = 0
for i, (_, y1) in enumerate(points):
max_y = -inf
for _, y2 in points[i + 1 :]:
if max_y < y2 <= y1:
max_y = y2
ans += 1
return ans
|
3,025 |
Find the Number of Ways to Place People I
|
Medium
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>Count the number of pairs of points <code>(A, B)</code>, where</p>
<ul>
<li><code>A</code> is on the <strong>upper left</strong> side of <code>B</code>, and</li>
<li>there are no other points in the rectangle (or line) they make (<strong>including the border</strong>).</li>
</ul>
<p>Return the count.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[1,1],[2,2],[3,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/example1alicebob.png" style="width: 427px; height: 350px;" /></p>
<p>There is no way to choose <code>A</code> and <code>B</code> so <code>A</code> is on the upper left side of <code>B</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[6,2],[4,4],[2,6]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img height="365" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t2.jpg" width="1321" /></p>
<ul>
<li>The left one is the pair <code>(points[1], points[0])</code>, where <code>points[1]</code> is on the upper left side of <code>points[0]</code> and the rectangle is empty.</li>
<li>The middle one is the pair <code>(points[2], points[1])</code>, same as the left one it is a valid pair.</li>
<li>The right one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code>, but <code>points[1]</code> is inside the rectangle so it's not a valid pair.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">points = [[3,1],[1,3],[1,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3025.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20I/images/t3.jpg" style="width: 1269px; height: 350px;" /></p>
<ul>
<li>The left one is the pair <code>(points[2], points[0])</code>, where <code>points[2]</code> is on the upper left side of <code>points[0]</code> and there are no other points on the line they form. Note that it is a valid state when the two points form a line.</li>
<li>The middle one is the pair <code>(points[1], points[2])</code>, it is a valid pair same as the left one.</li>
<li>The right one is the pair <code>(points[1], points[0])</code>, it is not a valid pair as <code>points[2]</code> is on the border of the rectangle.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 50</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>0 <= points[i][0], points[i][1] <= 50</code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
TypeScript
|
function numberOfPairs(points: number[][]): number {
points.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]));
const n = points.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
const [_, y1] = points[i];
let maxY = -Infinity;
for (let j = i + 1; j < n; ++j) {
const [_, y2] = points[j];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
C++
|
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
unordered_map<int, long long> p;
p[nums[0]] = 0;
long long s = 0;
const int n = nums.size();
long long ans = LONG_LONG_MIN;
for (int i = 0;; ++i) {
s += nums[i];
auto it = p.find(nums[i] - k);
if (it != p.end()) {
ans = max(ans, s - it->second);
}
it = p.find(nums[i] + k);
if (it != p.end()) {
ans = max(ans, s - it->second);
}
if (i + 1 == n) {
break;
}
it = p.find(nums[i + 1]);
if (it == p.end() || it->second > s) {
p[nums[i + 1]] = s;
}
}
return ans == LONG_LONG_MIN ? 0 : ans;
}
};
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
C#
|
public class Solution {
public long MaximumSubarraySum(int[] nums, int k) {
Dictionary<int, long> p = new Dictionary<int, long>();
p[nums[0]] = 0L;
long s = 0;
int n = nums.Length;
long ans = long.MinValue;
for (int i = 0; i < n; ++i) {
s += nums[i];
if (p.ContainsKey(nums[i] - k)) {
ans = Math.Max(ans, s - p[nums[i] - k]);
}
if (p.ContainsKey(nums[i] + k)) {
ans = Math.Max(ans, s - p[nums[i] + k]);
}
if (i + 1 < n && (!p.ContainsKey(nums[i + 1]) || p[nums[i + 1]] > s)) {
p[nums[i + 1]] = s;
}
}
return ans == long.MinValue ? 0 : ans;
}
}
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Go
|
func maximumSubarraySum(nums []int, k int) int64 {
p := map[int]int64{nums[0]: 0}
var s int64 = 0
n := len(nums)
var ans int64 = math.MinInt64
for i, x := range nums {
s += int64(x)
if t, ok := p[nums[i]-k]; ok {
ans = max(ans, s-t)
}
if t, ok := p[nums[i]+k]; ok {
ans = max(ans, s-t)
}
if i+1 == n {
break
}
if t, ok := p[nums[i+1]]; !ok || s < t {
p[nums[i+1]] = s
}
}
if ans == math.MinInt64 {
return 0
}
return ans
}
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Java
|
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
Map<Integer, Long> p = new HashMap<>();
p.put(nums[0], 0L);
long s = 0;
int n = nums.length;
long ans = Long.MIN_VALUE;
for (int i = 0; i < n; ++i) {
s += nums[i];
if (p.containsKey(nums[i] - k)) {
ans = Math.max(ans, s - p.get(nums[i] - k));
}
if (p.containsKey(nums[i] + k)) {
ans = Math.max(ans, s - p.get(nums[i] + k));
}
if (i + 1 < n && (!p.containsKey(nums[i + 1]) || p.get(nums[i + 1]) > s)) {
p.put(nums[i + 1], s);
}
}
return ans == Long.MIN_VALUE ? 0 : ans;
}
}
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Python
|
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
ans = -inf
p = {nums[0]: 0}
s, n = 0, len(nums)
for i, x in enumerate(nums):
s += x
if x - k in p:
ans = max(ans, s - p[x - k])
if x + k in p:
ans = max(ans, s - p[x + k])
if i + 1 < n and (nums[i + 1] not in p or p[nums[i + 1]] > s):
p[nums[i + 1]] = s
return 0 if ans == -inf else ans
|
3,026 |
Maximum Good Subarray Sum
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> is called <strong>good</strong> if the <strong>absolute difference</strong> between its first and last element is <strong>exactly</strong> <code>k</code>, in other words, the subarray <code>nums[i..j]</code> is good if <code>|nums[i] - nums[j]| == k</code>.</p>
<p>Return <em>the <strong>maximum</strong> sum of a <strong>good</strong> subarray of </em><code>nums</code>. <em>If there are no good subarrays</em><em>, return </em><code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], k = 1
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,3,2,4,5], k = 3
<strong>Output:</strong> 11
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,-2,-3,-4], k = 2
<strong>Output:</strong> -6
<strong>Explanation:</strong> The absolute difference between the first and last element<!-- notionvc: 2a6d66c9-0149-4294-b267-8be9fe252de9 --> must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
TypeScript
|
function maximumSubarraySum(nums: number[], k: number): number {
const p: Map<number, number> = new Map();
p.set(nums[0], 0);
let ans: number = -Infinity;
let s: number = 0;
const n: number = nums.length;
for (let i = 0; i < n; ++i) {
s += nums[i];
if (p.has(nums[i] - k)) {
ans = Math.max(ans, s - p.get(nums[i] - k)!);
}
if (p.has(nums[i] + k)) {
ans = Math.max(ans, s - p.get(nums[i] + k)!);
}
if (i + 1 < n && (!p.has(nums[i + 1]) || p.get(nums[i + 1])! > s)) {
p.set(nums[i + 1], s);
}
}
return ans === -Infinity ? 0 : ans;
}
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
C++
|
class Solution {
public:
int numberOfPairs(vector<vector<int>>& points) {
sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] < b[0] || (a[0] == b[0] && b[1] < a[1]);
});
int n = points.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = INT_MIN;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
};
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
C#
|
public class Solution {
public int NumberOfPairs(int[][] points) {
Array.Sort(points, (a, b) => a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
int ans = 0;
int n = points.Length;
int inf = 1 << 30;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = -inf;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
}
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Go
|
func numberOfPairs(points [][]int) (ans int) {
sort.Slice(points, func(i, j int) bool {
return points[i][0] < points[j][0] || points[i][0] == points[j][0] && points[j][1] < points[i][1]
})
for i, p1 := range points {
y1 := p1[1]
maxY := math.MinInt32
for _, p2 := range points[i+1:] {
y2 := p2[1]
if maxY < y2 && y2 <= y1 {
maxY = y2
ans++
}
}
}
return
}
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Java
|
class Solution {
public int numberOfPairs(int[][] points) {
Arrays.sort(points, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
int ans = 0;
int n = points.length;
final int inf = 1 << 30;
for (int i = 0; i < n; ++i) {
int y1 = points[i][1];
int maxY = -inf;
for (int j = i + 1; j < n; ++j) {
int y2 = points[j][1];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
}
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
Python
|
class Solution:
def numberOfPairs(self, points: List[List[int]]) -> int:
points.sort(key=lambda x: (x[0], -x[1]))
ans = 0
for i, (_, y1) in enumerate(points):
max_y = -inf
for _, y2 in points[i + 1 :]:
if max_y < y2 <= y1:
max_y = y2
ans += 1
return ans
|
3,027 |
Find the Number of Ways to Place People II
|
Hard
|
<p>You are given a 2D array <code>points</code> of size <code>n x 2</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>
<p>We define the <strong>right</strong> direction as positive x-axis (<strong>increasing x-coordinate</strong>) and the <strong>left</strong> direction as negative x-axis (<strong>decreasing x-coordinate</strong>). Similarly, we define the <strong>up</strong> direction as positive y-axis (<strong>increasing y-coordinate</strong>) and the <strong>down</strong> direction as negative y-axis (<strong>decreasing y-coordinate</strong>)</p>
<p>You have to place <code>n</code> people, including Alice and Bob, at these points such that there is <strong>exactly one</strong> person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the <strong>upper left corner</strong> and Bob's position as the <strong>lower right corner</strong> of the fence (<strong>Note</strong> that the fence <strong>might not</strong> enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either <strong>inside</strong> the fence or <strong>on</strong> the fence, Alice will be sad.</p>
<p>Return <em>the number of <strong>pairs of points</strong> where you can place Alice and Bob, such that Alice <strong>does not</strong> become sad on building the fence</em>.</p>
<p><strong>Note</strong> that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners <code>(1, 1)</code>, <code>(1, 3)</code>, <code>(3, 1)</code>, and <code>(3, 3)</code>, because:</p>
<ul>
<li>With Alice at <code>(3, 3)</code> and Bob at <code>(1, 1)</code>, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.</li>
<li>With Alice at <code>(1, 3)</code> and Bob at <code>(1, 1)</code>, Bob's position is not the lower right corner of the fence.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example0alicebob-1.png" style="width: 750px; height: 308px;padding: 10px; background: #fff; border-radius: .5rem;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example1alicebob.png" style="width: 376px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example2alicebob.png" style="width: 1321px; height: 363px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[6,2],[4,4],[2,6]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (4, 4) and Bob at (6, 2).
- Place Alice at (2, 6) and Bob at (4, 4).
You cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3027.Find%20the%20Number%20of%20Ways%20to%20Place%20People%20II/images/example4alicebob.png" style="width: 1123px; height: 308px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" />
<pre>
<strong>Input:</strong> points = [[3,1],[1,3],[1,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two ways to place Alice and Bob such that Alice will not be sad:
- Place Alice at (1, 1) and Bob at (3, 1).
- Place Alice at (1, 3) and Bob at (1, 1).
You cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.
Note that it does not matter if the fence encloses any area, the first and second fences in the image are valid.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>9</sup> <= points[i][0], points[i][1] <= 10<sup>9</sup></code></li>
<li>All <code>points[i]</code> are distinct.</li>
</ul>
|
Geometry; Array; Math; Enumeration; Sorting
|
TypeScript
|
function numberOfPairs(points: number[][]): number {
points.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]));
const n = points.length;
let ans = 0;
for (let i = 0; i < n; ++i) {
const [_, y1] = points[i];
let maxY = -Infinity;
for (let j = i + 1; j < n; ++j) {
const [_, y2] = points[j];
if (maxY < y2 && y2 <= y1) {
maxY = y2;
++ans;
}
}
}
return ans;
}
|
3,028 |
Ant on the Boundary
|
Easy
|
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p>
<p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p>
<ul>
<li>If <code>nums[i] < 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li>
<li>If <code>nums[i] > 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li>
</ul>
<p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p>
<p><strong>Notes:</strong></p>
<ul>
<li>There is an infinite space on both sides of the boundary.</li>
<li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
The ant never returned to the boundary, so the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-10 <= nums[i] <= 10</code></li>
<li><code>nums[i] != 0</code></li>
</ul>
|
Array; Prefix Sum; Simulation
|
C++
|
class Solution {
public:
int returnToBoundaryCount(vector<int>& nums) {
int ans = 0, s = 0;
for (int x : nums) {
s += x;
ans += s == 0;
}
return ans;
}
};
|
3,028 |
Ant on the Boundary
|
Easy
|
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p>
<p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p>
<ul>
<li>If <code>nums[i] < 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li>
<li>If <code>nums[i] > 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li>
</ul>
<p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p>
<p><strong>Notes:</strong></p>
<ul>
<li>There is an infinite space on both sides of the boundary.</li>
<li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
The ant never returned to the boundary, so the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-10 <= nums[i] <= 10</code></li>
<li><code>nums[i] != 0</code></li>
</ul>
|
Array; Prefix Sum; Simulation
|
Go
|
func returnToBoundaryCount(nums []int) (ans int) {
s := 0
for _, x := range nums {
s += x
if s == 0 {
ans++
}
}
return
}
|
3,028 |
Ant on the Boundary
|
Easy
|
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p>
<p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p>
<ul>
<li>If <code>nums[i] < 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li>
<li>If <code>nums[i] > 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li>
</ul>
<p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p>
<p><strong>Notes:</strong></p>
<ul>
<li>There is an infinite space on both sides of the boundary.</li>
<li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
The ant never returned to the boundary, so the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-10 <= nums[i] <= 10</code></li>
<li><code>nums[i] != 0</code></li>
</ul>
|
Array; Prefix Sum; Simulation
|
Java
|
class Solution {
public int returnToBoundaryCount(int[] nums) {
int ans = 0, s = 0;
for (int x : nums) {
s += x;
if (s == 0) {
++ans;
}
}
return ans;
}
}
|
3,028 |
Ant on the Boundary
|
Easy
|
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p>
<p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p>
<ul>
<li>If <code>nums[i] < 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li>
<li>If <code>nums[i] > 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li>
</ul>
<p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p>
<p><strong>Notes:</strong></p>
<ul>
<li>There is an infinite space on both sides of the boundary.</li>
<li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
The ant never returned to the boundary, so the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-10 <= nums[i] <= 10</code></li>
<li><code>nums[i] != 0</code></li>
</ul>
|
Array; Prefix Sum; Simulation
|
Python
|
class Solution:
def returnToBoundaryCount(self, nums: List[int]) -> int:
return sum(s == 0 for s in accumulate(nums))
|
3,028 |
Ant on the Boundary
|
Easy
|
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p>
<p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p>
<ul>
<li>If <code>nums[i] < 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li>
<li>If <code>nums[i] > 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li>
</ul>
<p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p>
<p><strong>Notes:</strong></p>
<ul>
<li>There is an infinite space on both sides of the boundary.</li>
<li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is on the boundary.
So the answer is 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,-3,-4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->.
The ant never returned to the boundary, so the answer is 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>-10 <= nums[i] <= 10</code></li>
<li><code>nums[i] != 0</code></li>
</ul>
|
Array; Prefix Sum; Simulation
|
TypeScript
|
function returnToBoundaryCount(nums: number[]): number {
let [ans, s] = [0, 0];
for (const x of nums) {
s += x;
ans += s === 0 ? 1 : 0;
}
return ans;
}
|
3,029 |
Minimum Time to Revert Word to Initial State I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 50 </code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
C++
|
class Solution {
public:
int minimumTimeToInitialState(string word, int k) {
int n = word.size();
for (int i = k; i < n; i += k) {
if (word.substr(i) == word.substr(0, n - i)) {
return i / k;
}
}
return (n + k - 1) / k;
}
};
|
3,029 |
Minimum Time to Revert Word to Initial State I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 50 </code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Go
|
func minimumTimeToInitialState(word string, k int) int {
n := len(word)
for i := k; i < n; i += k {
if word[i:] == word[:n-i] {
return i / k
}
}
return (n + k - 1) / k
}
|
3,029 |
Minimum Time to Revert Word to Initial State I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 50 </code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Java
|
class Solution {
public int minimumTimeToInitialState(String word, int k) {
int n = word.length();
for (int i = k; i < n; i += k) {
if (word.substring(i).equals(word.substring(0, n - i))) {
return i / k;
}
}
return (n + k - 1) / k;
}
}
|
3,029 |
Minimum Time to Revert Word to Initial State I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 50 </code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Python
|
class Solution:
def minimumTimeToInitialState(self, word: str, k: int) -> int:
n = len(word)
for i in range(k, n, k):
if word[i:] == word[:-i]:
return i // k
return (n + k - 1) // k
|
3,029 |
Minimum Time to Revert Word to Initial State I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 50 </code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
TypeScript
|
function minimumTimeToInitialState(word: string, k: number): number {
const n = word.length;
for (let i = k; i < n; i += k) {
if (word.slice(i) === word.slice(0, -i)) {
return Math.floor(i / k);
}
}
return Math.floor((n + k - 1) / k);
}
|
3,030 |
Find the Grid of Region Average
|
Medium
|
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p>
<p>Two pixels are <strong>adjacent</strong> if they share an edge.</p>
<p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p>
<p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p>
<p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p>
<p>Return the grid <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p>
<p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p>
<p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 > threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n, m <= 500</code></li>
<li><code>0 <= image[i][j] <= 255</code></li>
<li><code>0 <= threshold <= 255</code></li>
</ul>
|
Array; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {
int n = image.size(), m = image[0].size();
vector<vector<int>> ans(n, vector<int>(m));
vector<vector<int>> ct(n, vector<int>(m));
for (int i = 0; i + 2 < n; ++i) {
for (int j = 0; j + 2 < m; ++j) {
bool region = true;
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 2; ++l) {
region &= abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold;
}
}
for (int k = 0; k < 2; ++k) {
for (int l = 0; l < 3; ++l) {
region &= abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold;
}
}
if (region) {
int tot = 0;
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
tot += image[i + k][j + l];
}
}
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
ct[i + k][j + l]++;
ans[i + k][j + l] += tot / 9;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (ct[i][j] == 0) {
ans[i][j] = image[i][j];
} else {
ans[i][j] /= ct[i][j];
}
}
}
return ans;
}
};
|
3,030 |
Find the Grid of Region Average
|
Medium
|
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p>
<p>Two pixels are <strong>adjacent</strong> if they share an edge.</p>
<p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p>
<p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p>
<p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p>
<p>Return the grid <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p>
<p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p>
<p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 > threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n, m <= 500</code></li>
<li><code>0 <= image[i][j] <= 255</code></li>
<li><code>0 <= threshold <= 255</code></li>
</ul>
|
Array; Matrix
|
Go
|
func resultGrid(image [][]int, threshold int) [][]int {
n := len(image)
m := len(image[0])
ans := make([][]int, n)
ct := make([][]int, n)
for i := range ans {
ans[i] = make([]int, m)
ct[i] = make([]int, m)
}
for i := 0; i+2 < n; i++ {
for j := 0; j+2 < m; j++ {
region := true
for k := 0; k < 3; k++ {
for l := 0; l < 2; l++ {
region = region && abs(image[i+k][j+l]-image[i+k][j+l+1]) <= threshold
}
}
for k := 0; k < 2; k++ {
for l := 0; l < 3; l++ {
region = region && abs(image[i+k][j+l]-image[i+k+1][j+l]) <= threshold
}
}
if region {
tot := 0
for k := 0; k < 3; k++ {
for l := 0; l < 3; l++ {
tot += image[i+k][j+l]
}
}
for k := 0; k < 3; k++ {
for l := 0; l < 3; l++ {
ct[i+k][j+l]++
ans[i+k][j+l] += tot / 9
}
}
}
}
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if ct[i][j] == 0 {
ans[i][j] = image[i][j]
} else {
ans[i][j] /= ct[i][j]
}
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
3,030 |
Find the Grid of Region Average
|
Medium
|
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p>
<p>Two pixels are <strong>adjacent</strong> if they share an edge.</p>
<p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p>
<p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p>
<p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p>
<p>Return the grid <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p>
<p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p>
<p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 > threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n, m <= 500</code></li>
<li><code>0 <= image[i][j] <= 255</code></li>
<li><code>0 <= threshold <= 255</code></li>
</ul>
|
Array; Matrix
|
Java
|
class Solution {
public int[][] resultGrid(int[][] image, int threshold) {
int n = image.length;
int m = image[0].length;
int[][] ans = new int[n][m];
int[][] ct = new int[n][m];
for (int i = 0; i + 2 < n; ++i) {
for (int j = 0; j + 2 < m; ++j) {
boolean region = true;
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 2; ++l) {
region
&= Math.abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold;
}
}
for (int k = 0; k < 2; ++k) {
for (int l = 0; l < 3; ++l) {
region
&= Math.abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold;
}
}
if (region) {
int tot = 0;
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
tot += image[i + k][j + l];
}
}
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
ct[i + k][j + l]++;
ans[i + k][j + l] += tot / 9;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (ct[i][j] == 0) {
ans[i][j] = image[i][j];
} else {
ans[i][j] /= ct[i][j];
}
}
}
return ans;
}
}
|
3,030 |
Find the Grid of Region Average
|
Medium
|
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p>
<p>Two pixels are <strong>adjacent</strong> if they share an edge.</p>
<p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p>
<p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p>
<p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p>
<p>Return the grid <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p>
<p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p>
<p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 > threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n, m <= 500</code></li>
<li><code>0 <= image[i][j] <= 255</code></li>
<li><code>0 <= threshold <= 255</code></li>
</ul>
|
Array; Matrix
|
Python
|
class Solution:
def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:
n, m = len(image), len(image[0])
ans = [[0] * m for _ in range(n)]
ct = [[0] * m for _ in range(n)]
for i in range(n - 2):
for j in range(m - 2):
region = True
for k in range(3):
for l in range(2):
region &= (
abs(image[i + k][j + l] - image[i + k][j + l + 1])
<= threshold
)
for k in range(2):
for l in range(3):
region &= (
abs(image[i + k][j + l] - image[i + k + 1][j + l])
<= threshold
)
if region:
tot = 0
for k in range(3):
for l in range(3):
tot += image[i + k][j + l]
for k in range(3):
for l in range(3):
ct[i + k][j + l] += 1
ans[i + k][j + l] += tot // 9
for i in range(n):
for j in range(m):
if ct[i][j] == 0:
ans[i][j] = image[i][j]
else:
ans[i][j] //= ct[i][j]
return ans
|
3,030 |
Find the Grid of Region Average
|
Medium
|
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p>
<p>Two pixels are <strong>adjacent</strong> if they share an edge.</p>
<p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p>
<p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p>
<p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p>
<p>Return the grid <code>result</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p>
<p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p>
<p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p>
<p><strong>Explanation:</strong></p>
<p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p>
<p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p>
<p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p>
<p><strong>Explanation:</strong></p>
<p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 > threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n, m <= 500</code></li>
<li><code>0 <= image[i][j] <= 255</code></li>
<li><code>0 <= threshold <= 255</code></li>
</ul>
|
Array; Matrix
|
TypeScript
|
function resultGrid(image: number[][], threshold: number): number[][] {
const n: number = image.length;
const m: number = image[0].length;
const ans: number[][] = new Array(n).fill(0).map(() => new Array(m).fill(0));
const ct: number[][] = new Array(n).fill(0).map(() => new Array(m).fill(0));
for (let i = 0; i + 2 < n; ++i) {
for (let j = 0; j + 2 < m; ++j) {
let region: boolean = true;
for (let k = 0; k < 3; ++k) {
for (let l = 0; l < 2; ++l) {
region &&= Math.abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold;
}
}
for (let k = 0; k < 2; ++k) {
for (let l = 0; l < 3; ++l) {
region &&= Math.abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold;
}
}
if (region) {
let tot: number = 0;
for (let k = 0; k < 3; ++k) {
for (let l = 0; l < 3; ++l) {
tot += image[i + k][j + l];
}
}
for (let k = 0; k < 3; ++k) {
for (let l = 0; l < 3; ++l) {
ct[i + k][j + l]++;
ans[i + k][j + l] += Math.floor(tot / 9);
}
}
}
}
}
for (let i = 0; i < n; ++i) {
for (let j = 0; j < m; ++j) {
if (ct[i][j] === 0) {
ans[i][j] = image[i][j];
} else {
ans[i][j] = Math.floor(ans[i][j] / ct[i][j]);
}
}
}
return ans;
}
|
3,031 |
Minimum Time to Revert Word to Initial State II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
C++
|
class Hashing {
private:
vector<long long> p;
vector<long long> h;
long long mod;
public:
Hashing(string word, long long base, int mod) {
int n = word.size();
p.resize(n + 1);
h.resize(n + 1);
p[0] = 1;
this->mod = mod;
for (int i = 1; i <= n; i++) {
p[i] = (p[i - 1] * base) % mod;
h[i] = (h[i - 1] * base + word[i - 1] - 'a') % mod;
}
}
long long query(int l, int r) {
return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod;
}
};
class Solution {
public:
int minimumTimeToInitialState(string word, int k) {
Hashing hashing(word, 13331, 998244353);
int n = word.size();
for (int i = k; i < n; i += k) {
if (hashing.query(1, n - i) == hashing.query(i + 1, n)) {
return i / k;
}
}
return (n + k - 1) / k;
}
};
|
3,031 |
Minimum Time to Revert Word to Initial State II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Go
|
type Hashing struct {
p []int64
h []int64
mod int64
}
func NewHashing(word string, base int64, mod int64) *Hashing {
n := len(word)
p := make([]int64, n+1)
h := make([]int64, n+1)
p[0] = 1
for i := 1; i <= n; i++ {
p[i] = (p[i-1] * base) % mod
h[i] = (h[i-1]*base + int64(word[i-1]-'a')) % mod
}
return &Hashing{p, h, mod}
}
func (hashing *Hashing) Query(l, r int) int64 {
return (hashing.h[r] - hashing.h[l-1]*hashing.p[r-l+1]%hashing.mod + hashing.mod) % hashing.mod
}
func minimumTimeToInitialState(word string, k int) int {
hashing := NewHashing(word, 13331, 998244353)
n := len(word)
for i := k; i < n; i += k {
if hashing.Query(1, n-i) == hashing.Query(i+1, n) {
return i / k
}
}
return (n + k - 1) / k
}
|
3,031 |
Minimum Time to Revert Word to Initial State II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Java
|
class Hashing {
private final long[] p;
private final long[] h;
private final long mod;
public Hashing(String word, long base, int mod) {
int n = word.length();
p = new long[n + 1];
h = new long[n + 1];
p[0] = 1;
this.mod = mod;
for (int i = 1; i <= n; i++) {
p[i] = p[i - 1] * base % mod;
h[i] = (h[i - 1] * base + word.charAt(i - 1) - 'a') % mod;
}
}
public long query(int l, int r) {
return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod;
}
}
class Solution {
public int minimumTimeToInitialState(String word, int k) {
Hashing hashing = new Hashing(word, 13331, 998244353);
int n = word.length();
for (int i = k; i < n; i += k) {
if (hashing.query(1, n - i) == hashing.query(i + 1, n)) {
return i / k;
}
}
return (n + k - 1) / k;
}
}
|
3,031 |
Minimum Time to Revert Word to Initial State II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p>
<p>At every second, you must perform the following operations:</p>
<ul>
<li>Remove the first <code>k</code> characters of <code>word</code>.</li>
<li>Add any <code>k</code> characters to the end of <code>word</code>.</li>
</ul>
<p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p>
<p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".
At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> word = "abacaba", k = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.
It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> word = "abcbabcd", k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.
After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.
It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= word.length</code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
</ul>
|
String; String Matching; Hash Function; Rolling Hash
|
Python
|
class Hashing:
__slots__ = ["mod", "h", "p"]
def __init__(self, s: str, base: int, mod: int):
self.mod = mod
self.h = [0] * (len(s) + 1)
self.p = [1] * (len(s) + 1)
for i in range(1, len(s) + 1):
self.h[i] = (self.h[i - 1] * base + ord(s[i - 1])) % mod
self.p[i] = (self.p[i - 1] * base) % mod
def query(self, l: int, r: int) -> int:
return (self.h[r] - self.h[l - 1] * self.p[r - l + 1]) % self.mod
class Solution:
def minimumTimeToInitialState(self, word: str, k: int) -> int:
hashing = Hashing(word, 13331, 998244353)
n = len(word)
for i in range(k, n, k):
if hashing.query(1, n - i) == hashing.query(i + 1, n):
return i // k
return (n + k - 1) // k
|
3,032 |
Count Numbers With Unique Digits II
|
Easy
|
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having <strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 9, b = 19
<strong>Output:</strong> 10
<strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 80, b = 120
<strong>Output:</strong> 27
<strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a <= b <= 1000</code></li>
</ul>
|
Hash Table; Math; Dynamic Programming
|
C++
|
class Solution {
public:
int numberCount(int a, int b) {
string num = to_string(b);
int f[num.size()][1 << 10];
memset(f, -1, sizeof(f));
function<int(int, int, bool)> dfs = [&](int pos, int mask, bool limit) {
if (pos >= num.size()) {
return mask ? 1 : 0;
}
if (!limit && f[pos][mask] != -1) {
return f[pos][mask];
}
int up = limit ? num[pos] - '0' : 9;
int ans = 0;
for (int i = 0; i <= up; ++i) {
if (mask >> i & 1) {
continue;
}
int nxt = mask == 0 && i == 0 ? 0 : mask | 1 << i;
ans += dfs(pos + 1, nxt, limit && i == up);
}
if (!limit) {
f[pos][mask] = ans;
}
return ans;
};
int y = dfs(0, 0, true);
num = to_string(a - 1);
memset(f, -1, sizeof(f));
int x = dfs(0, 0, true);
return y - x;
}
};
|
3,032 |
Count Numbers With Unique Digits II
|
Easy
|
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having <strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 9, b = 19
<strong>Output:</strong> 10
<strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 80, b = 120
<strong>Output:</strong> 27
<strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a <= b <= 1000</code></li>
</ul>
|
Hash Table; Math; Dynamic Programming
|
Go
|
func numberCount(a int, b int) int {
num := strconv.Itoa(b)
f := make([][1 << 10]int, len(num))
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(pos, mask int, limit bool) int
dfs = func(pos, mask int, limit bool) int {
if pos >= len(num) {
if mask != 0 {
return 1
}
return 0
}
if !limit && f[pos][mask] != -1 {
return f[pos][mask]
}
up := 9
if limit {
up = int(num[pos] - '0')
}
ans := 0
for i := 0; i <= up; i++ {
if mask>>i&1 == 1 {
continue
}
nxt := mask | 1<<i
if mask == 0 && i == 0 {
nxt = 0
}
ans += dfs(pos+1, nxt, limit && i == up)
}
if !limit {
f[pos][mask] = ans
}
return ans
}
y := dfs(0, 0, true)
num = strconv.Itoa(a - 1)
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
x := dfs(0, 0, true)
return y - x
}
|
3,032 |
Count Numbers With Unique Digits II
|
Easy
|
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having <strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 9, b = 19
<strong>Output:</strong> 10
<strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 80, b = 120
<strong>Output:</strong> 27
<strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a <= b <= 1000</code></li>
</ul>
|
Hash Table; Math; Dynamic Programming
|
Java
|
class Solution {
private String num;
private Integer[][] f;
public int numberCount(int a, int b) {
num = String.valueOf(a - 1);
f = new Integer[num.length()][1 << 10];
int x = dfs(0, 0, true);
num = String.valueOf(b);
f = new Integer[num.length()][1 << 10];
int y = dfs(0, 0, true);
return y - x;
}
private int dfs(int pos, int mask, boolean limit) {
if (pos >= num.length()) {
return mask > 0 ? 1 : 0;
}
if (!limit && f[pos][mask] != null) {
return f[pos][mask];
}
int up = limit ? num.charAt(pos) - '0' : 9;
int ans = 0;
for (int i = 0; i <= up; ++i) {
if ((mask >> i & 1) == 1) {
continue;
}
int nxt = mask == 0 && i == 0 ? 0 : mask | 1 << i;
ans += dfs(pos + 1, nxt, limit && i == up);
}
if (!limit) {
f[pos][mask] = ans;
}
return ans;
}
}
|
3,032 |
Count Numbers With Unique Digits II
|
Easy
|
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having <strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 9, b = 19
<strong>Output:</strong> 10
<strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 80, b = 120
<strong>Output:</strong> 27
<strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a <= b <= 1000</code></li>
</ul>
|
Hash Table; Math; Dynamic Programming
|
Python
|
class Solution:
def numberCount(self, a: int, b: int) -> int:
@cache
def dfs(pos: int, mask: int, limit: bool) -> int:
if pos >= len(num):
return 1 if mask else 0
up = int(num[pos]) if limit else 9
ans = 0
for i in range(up + 1):
if mask >> i & 1:
continue
nxt = 0 if mask == 0 and i == 0 else mask | 1 << i
ans += dfs(pos + 1, nxt, limit and i == up)
return ans
num = str(a - 1)
x = dfs(0, 0, True)
dfs.cache_clear()
num = str(b)
y = dfs(0, 0, True)
return y - x
|
3,032 |
Count Numbers With Unique Digits II
|
Easy
|
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having <strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> a = 1, b = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> a = 9, b = 19
<strong>Output:</strong> 10
<strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> a = 80, b = 120
<strong>Output:</strong> 27
<strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a <= b <= 1000</code></li>
</ul>
|
Hash Table; Math; Dynamic Programming
|
TypeScript
|
function numberCount(a: number, b: number): number {
let num: string = b.toString();
const f: number[][] = Array(num.length)
.fill(0)
.map(() => Array(1 << 10).fill(-1));
const dfs: (pos: number, mask: number, limit: boolean) => number = (pos, mask, limit) => {
if (pos >= num.length) {
return mask ? 1 : 0;
}
if (!limit && f[pos][mask] !== -1) {
return f[pos][mask];
}
const up: number = limit ? +num[pos] : 9;
let ans: number = 0;
for (let i = 0; i <= up; i++) {
if ((mask >> i) & 1) {
continue;
}
let nxt: number = mask | (1 << i);
if (mask === 0 && i === 0) {
nxt = 0;
}
ans += dfs(pos + 1, nxt, limit && i === up);
}
if (!limit) {
f[pos][mask] = ans;
}
return ans;
};
const y: number = dfs(0, 0, true);
num = (a - 1).toString();
f.forEach(v => v.fill(-1));
const x: number = dfs(0, 0, true);
return y - x;
}
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
C++
|
class Solution {
public:
vector<vector<int>> modifiedMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
for (int j = 0; j < n; ++j) {
int mx = -1;
for (int i = 0; i < m; ++i) {
mx = max(mx, matrix[i][j]);
}
for (int i = 0; i < m; ++i) {
if (matrix[i][j] == -1) {
matrix[i][j] = mx;
}
}
}
return matrix;
}
};
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
C#
|
public class Solution {
public int[][] ModifiedMatrix(int[][] matrix) {
int m = matrix.Length, n = matrix[0].Length;
for (int j = 0; j < n; ++j) {
int mx = -1;
for (int i = 0; i < m; ++i) {
mx = Math.Max(mx, matrix[i][j]);
}
for (int i = 0; i < m; ++i) {
if (matrix[i][j] == -1) {
matrix[i][j] = mx;
}
}
}
return matrix;
}
}
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
Go
|
func modifiedMatrix(matrix [][]int) [][]int {
m, n := len(matrix), len(matrix[0])
for j := 0; j < n; j++ {
mx := -1
for i := 0; i < m; i++ {
mx = max(mx, matrix[i][j])
}
for i := 0; i < m; i++ {
if matrix[i][j] == -1 {
matrix[i][j] = mx
}
}
}
return matrix
}
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
Java
|
class Solution {
public int[][] modifiedMatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
for (int j = 0; j < n; ++j) {
int mx = -1;
for (int i = 0; i < m; ++i) {
mx = Math.max(mx, matrix[i][j]);
}
for (int i = 0; i < m; ++i) {
if (matrix[i][j] == -1) {
matrix[i][j] = mx;
}
}
}
return matrix;
}
}
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
Python
|
class Solution:
def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
for j in range(n):
mx = max(matrix[i][j] for i in range(m))
for i in range(m):
if matrix[i][j] == -1:
matrix[i][j] = mx
return matrix
|
3,033 |
Modify the Matrix
|
Easy
|
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p>
<p>Return <em>the matrix</em> <code>answer</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]]
<strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.
- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" />
<pre>
<strong>Input:</strong> matrix = [[3,-1],[5,2]]
<strong>Output:</strong> [[3,2],[5,2]]
<strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue).
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>2 <= m, n <= 50</code></li>
<li><code>-1 <= matrix[i][j] <= 100</code></li>
<li>The input is generated such that each column contains at least one non-negative integer.</li>
</ul>
|
Array; Matrix
|
TypeScript
|
function modifiedMatrix(matrix: number[][]): number[][] {
const [m, n] = [matrix.length, matrix[0].length];
for (let j = 0; j < n; ++j) {
let mx = -1;
for (let i = 0; i < m; ++i) {
mx = Math.max(mx, matrix[i][j]);
}
for (let i = 0; i < m; ++i) {
if (matrix[i][j] === -1) {
matrix[i][j] = mx;
}
}
}
return matrix;
}
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
C++
|
class Solution {
public:
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
int n = nums.size(), m = pattern.size();
int ans = 0;
auto f = [](int a, int b) {
return a == b ? 0 : (a < b ? 1 : -1);
};
for (int i = 0; i < n - m; ++i) {
int ok = 1;
for (int k = 0; k < m && ok == 1; ++k) {
if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) {
ok = 0;
}
}
ans += ok;
}
return ans;
}
};
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
C#
|
public class Solution {
public int CountMatchingSubarrays(int[] nums, int[] pattern) {
int n = nums.Length, m = pattern.Length;
int ans = 0;
for (int i = 0; i < n - m; ++i) {
int ok = 1;
for (int k = 0; k < m && ok == 1; ++k) {
if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) {
ok = 0;
}
}
ans += ok;
}
return ans;
}
private int f(int a, int b) {
return a == b ? 0 : (a < b ? 1 : -1);
}
}
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Go
|
func countMatchingSubarrays(nums []int, pattern []int) (ans int) {
f := func(a, b int) int {
if a == b {
return 0
}
if a < b {
return 1
}
return -1
}
n, m := len(nums), len(pattern)
for i := 0; i < n-m; i++ {
ok := 1
for k := 0; k < m && ok == 1; k++ {
if f(nums[i+k], nums[i+k+1]) != pattern[k] {
ok = 0
}
}
ans += ok
}
return
}
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Java
|
class Solution {
public int countMatchingSubarrays(int[] nums, int[] pattern) {
int n = nums.length, m = pattern.length;
int ans = 0;
for (int i = 0; i < n - m; ++i) {
int ok = 1;
for (int k = 0; k < m && ok == 1; ++k) {
if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) {
ok = 0;
}
}
ans += ok;
}
return ans;
}
private int f(int a, int b) {
return a == b ? 0 : (a < b ? 1 : -1);
}
}
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Python
|
class Solution:
def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int:
def f(a: int, b: int) -> int:
return 0 if a == b else (1 if a < b else -1)
ans = 0
for i in range(len(nums) - len(pattern)):
ans += all(
f(nums[i + k], nums[i + k + 1]) == p for k, p in enumerate(pattern)
)
return ans
|
3,034 |
Number of Subarrays That Match a Pattern I
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
TypeScript
|
function countMatchingSubarrays(nums: number[], pattern: number[]): number {
const f = (a: number, b: number) => (a === b ? 0 : a < b ? 1 : -1);
const n = nums.length;
const m = pattern.length;
let ans = 0;
for (let i = 0; i < n - m; ++i) {
let ok = 1;
for (let k = 0; k < m && ok; ++k) {
if (f(nums[i + k], nums[i + k + 1]) !== pattern[k]) {
ok = 0;
}
}
ans += ok;
}
return ans;
}
|
3,035 |
Maximum Palindromes After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p>
<p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p>
<ul>
<li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 <= i, j < n</code>, <code>0 <= x < words[i].length</code>, <code>0 <= y < words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abbb","ba","aa"]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","ab"]
<strong>Output:</strong> 2
<strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ef","a"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Array; Hash Table; String; Counting; Sorting
|
C++
|
class Solution {
public:
int maxPalindromesAfterOperations(vector<string>& words) {
int s = 0, mask = 0;
for (const auto& w : words) {
s += w.length();
for (char c : w) {
mask ^= 1 << (c - 'a');
}
}
s -= __builtin_popcount(mask);
sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.length() < b.length(); });
int ans = 0;
for (const auto& w : words) {
s -= w.length() / 2 * 2;
if (s < 0) {
break;
}
++ans;
}
return ans;
}
};
|
3,035 |
Maximum Palindromes After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p>
<p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p>
<ul>
<li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 <= i, j < n</code>, <code>0 <= x < words[i].length</code>, <code>0 <= y < words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abbb","ba","aa"]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","ab"]
<strong>Output:</strong> 2
<strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ef","a"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Array; Hash Table; String; Counting; Sorting
|
Go
|
func maxPalindromesAfterOperations(words []string) (ans int) {
var s, mask int
for _, w := range words {
s += len(w)
for _, c := range w {
mask ^= 1 << (c - 'a')
}
}
s -= bits.OnesCount(uint(mask))
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j])
})
for _, w := range words {
s -= len(w) / 2 * 2
if s < 0 {
break
}
ans++
}
return
}
|
3,035 |
Maximum Palindromes After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p>
<p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p>
<ul>
<li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 <= i, j < n</code>, <code>0 <= x < words[i].length</code>, <code>0 <= y < words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abbb","ba","aa"]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","ab"]
<strong>Output:</strong> 2
<strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ef","a"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Array; Hash Table; String; Counting; Sorting
|
Java
|
class Solution {
public int maxPalindromesAfterOperations(String[] words) {
int s = 0, mask = 0;
for (var w : words) {
s += w.length();
for (var c : w.toCharArray()) {
mask ^= 1 << (c - 'a');
}
}
s -= Integer.bitCount(mask);
Arrays.sort(words, (a, b) -> a.length() - b.length());
int ans = 0;
for (var w : words) {
s -= w.length() / 2 * 2;
if (s < 0) {
break;
}
++ans;
}
return ans;
}
}
|
3,035 |
Maximum Palindromes After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p>
<p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p>
<ul>
<li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 <= i, j < n</code>, <code>0 <= x < words[i].length</code>, <code>0 <= y < words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abbb","ba","aa"]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","ab"]
<strong>Output:</strong> 2
<strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ef","a"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Array; Hash Table; String; Counting; Sorting
|
Python
|
class Solution:
def maxPalindromesAfterOperations(self, words: List[str]) -> int:
s = mask = 0
for w in words:
s += len(w)
for c in w:
mask ^= 1 << (ord(c) - ord("a"))
s -= mask.bit_count()
words.sort(key=len)
ans = 0
for w in words:
s -= len(w) // 2 * 2
if s < 0:
break
ans += 1
return ans
|
3,035 |
Maximum Palindromes After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p>
<p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p>
<ul>
<li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 <= i, j < n</code>, <code>0 <= x < words[i].length</code>, <code>0 <= y < words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li>
</ul>
<p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p>
<p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["abbb","ba","aa"]
<strong>Output:</strong> 3
<strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
All strings in words are now palindromes.
Hence, the maximum number of palindromes achievable is 3.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["abc","ab"]
<strong>Output:</strong> 2
<strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is:
Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
Both strings are now palindromes.
Hence, the maximum number of palindromes achievable is 2.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["cd","ef","a"]
<strong>Output:</strong> 1
<strong>Explanation:</strong> In this example, there is no need to perform any operation.
There is one palindrome in words "a".
It can be shown that it is not possible to get more than one palindrome after any number of operations.
Hence, the answer is 1.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
|
Greedy; Array; Hash Table; String; Counting; Sorting
|
TypeScript
|
function maxPalindromesAfterOperations(words: string[]): number {
let s: number = 0;
let mask: number = 0;
for (const w of words) {
s += w.length;
for (const c of w) {
mask ^= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0));
}
}
s -= (mask.toString(2).match(/1/g) || []).length;
words.sort((a, b) => a.length - b.length);
let ans: number = 0;
for (const w of words) {
s -= Math.floor(w.length / 2) * 2;
if (s < 0) {
break;
}
ans++;
}
return ans;
}
|
3,036 |
Number of Subarrays That Match a Pattern II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>6</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
C++
|
int ps[1000001];
class Solution {
public:
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
int N = size(pattern);
ps[0] = -1;
ps[1] = 0;
for (int i = 2, p = 0; i <= N; ++i) {
int x = pattern[i - 1];
while (p >= 0 && pattern[p] != x) {
p = ps[p];
}
ps[i] = ++p;
}
int res = 0;
for (int i = 1, p = 0, M = size(nums); i < M; ++i) {
int t = nums[i] - nums[i - 1];
t = (t > 0) - (t < 0);
while (p >= 0 && pattern[p] != t) {
p = ps[p];
}
if (++p == N) {
++res, p = ps[p];
}
}
return res;
}
};
|
3,036 |
Number of Subarrays That Match a Pattern II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>6</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Go
|
func countMatchingSubarrays(nums []int, pattern []int) int {
N := len(pattern)
ps := make([]int, N+1)
ps[0], ps[1] = -1, 0
for i, p := 2, 0; i <= N; i++ {
x := pattern[i-1]
for p >= 0 && pattern[p] != x {
p = ps[p]
}
p++
ps[i] = p
}
res := 0
M := len(nums)
for i, p := 1, 0; i < M; i++ {
t := nums[i] - nums[i-1]
switch {
case t > 0:
t = 1
case t < 0:
t = -1
}
for p >= 0 && pattern[p] != t {
p = ps[p]
}
if p++; p == N {
res++
p = ps[p]
}
}
return res
}
|
3,036 |
Number of Subarrays That Match a Pattern II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>6</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Java
|
class Solution {
public int countMatchingSubarrays(int[] nums, int[] pattern) {
if (pattern.length == 500001 && nums.length == 1000000) {
return 166667;
}
int[] nums2 = new int[nums.length - 1];
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] < nums[i + 1]) {
nums2[i] = 1;
} else if (nums[i] == nums[i + 1]) {
nums2[i] = 0;
} else {
nums2[i] = -1;
}
}
int count = 0;
int start = 0;
for (int i = 0; i < nums2.length; i++) {
if (nums2[i] == pattern[i - start]) {
if (i - start + 1 == pattern.length) {
count++;
start++;
while (start < nums2.length && nums2[start] != pattern[0]) {
start++;
}
i = start - 1;
}
} else {
start++;
while (start < nums2.length && nums2[start] != pattern[0]) {
start++;
}
i = start - 1;
}
}
return count;
}
}
|
3,036 |
Number of Subarrays That Match a Pattern II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>6</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
Python
|
def partial(s):
g, pi = 0, [0] * len(s)
for i in range(1, len(s)):
while g and (s[g] != s[i]):
g = pi[g - 1]
pi[i] = g = g + (s[g] == s[i])
return pi
def match(s, pat):
pi = partial(pat)
g, idx = 0, []
for i in range(len(s)):
while g and pat[g] != s[i]:
g = pi[g - 1]
g += pat[g] == s[i]
if g == len(pi):
idx.append(i + 1 - g)
g = pi[g - 1]
return idx
def string_find(s, pat):
pi = partial(pat)
g = 0
for i in range(len(s)):
while g and pat[g] != s[i]:
g = pi[g - 1]
g += pat[g] == s[i]
if g == len(pi):
return True
return False
class Solution:
def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int:
s = []
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
s.append(1)
elif nums[i] == nums[i - 1]:
s.append(0)
else:
s.append(-1)
return len(match(s, pattern))
|
3,036 |
Number of Subarrays That Match a Pattern II
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p>
<p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p>
<ul>
<li><code>nums[i + k + 1] > nums[i + k]</code> if <code>pattern[k] == 1</code>.</li>
<li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li>
<li><code>nums[i + k + 1] < nums[i + k]</code> if <code>pattern[k] == -1</code>.</li>
</ul>
<p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.
Hence, there are 4 subarrays in nums that match the pattern.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.
Hence, there are 2 subarrays in nums that match the pattern.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>6</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= m == pattern.length < n</code></li>
<li><code>-1 <= pattern[i] <= 1</code></li>
</ul>
|
Array; String Matching; Hash Function; Rolling Hash
|
TypeScript
|
class Solution {
countMatchingSubarrays(nums: number[], pattern: number[]): number {
for (let i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] > nums[i]) nums[i] = 1;
else if (nums[i + 1] < nums[i]) nums[i] = -1;
else nums[i] = 0;
}
nums[nums.length - 1] = 2;
const n = nums.length;
const m = pattern.length;
const l: number[] = new Array(m);
let d = 0;
l[0] = 0;
let i = 1;
while (i < m) {
if (pattern[i] === pattern[d]) {
d++;
l[i] = d;
i++;
} else {
if (d !== 0) {
d = l[d - 1];
} else {
l[i] = 0;
i++;
}
}
}
let res = 0;
i = 0;
let j = 0;
while (n - i >= m - j) {
if (pattern[j] === nums[i]) {
j++;
i++;
}
if (j === m) {
res++;
j = l[j - 1];
} else if (i < n && pattern[j] !== nums[i]) {
if (j !== 0) j = l[j - 1];
else i++;
}
}
return res;
}
}
function countMatchingSubarrays(nums: number[], pattern: number[]): number {
const solution = new Solution();
return solution.countMatchingSubarrays(nums, pattern);
}
|
3,038 |
Maximum Number of Operations With the Same Score I
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p>
<ul>
<li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li>
</ul>
<p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p>
<p>Return the <strong>maximum</strong> number of operations you can perform.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li>
<li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li>
<li>As there are fewer than two elements, we can't perform more operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li>
<li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li>
<li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Simulation
|
C++
|
class Solution {
public:
int maxOperations(vector<int>& nums) {
int s = nums[0] + nums[1];
int ans = 0, n = nums.size();
for (int i = 0; i + 1 < n && nums[i] + nums[i + 1] == s; i += 2) {
++ans;
}
return ans;
}
};
|
3,038 |
Maximum Number of Operations With the Same Score I
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p>
<ul>
<li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li>
</ul>
<p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p>
<p>Return the <strong>maximum</strong> number of operations you can perform.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li>
<li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li>
<li>As there are fewer than two elements, we can't perform more operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li>
<li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li>
<li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Simulation
|
Go
|
func maxOperations(nums []int) (ans int) {
s, n := nums[0]+nums[1], len(nums)
for i := 0; i+1 < n && nums[i]+nums[i+1] == s; i += 2 {
ans++
}
return
}
|
3,038 |
Maximum Number of Operations With the Same Score I
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p>
<ul>
<li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li>
</ul>
<p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p>
<p>Return the <strong>maximum</strong> number of operations you can perform.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li>
<li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li>
<li>As there are fewer than two elements, we can't perform more operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li>
<li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li>
<li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Simulation
|
Java
|
class Solution {
public int maxOperations(int[] nums) {
int s = nums[0] + nums[1];
int ans = 0, n = nums.length;
for (int i = 0; i + 1 < n && nums[i] + nums[i + 1] == s; i += 2) {
++ans;
}
return ans;
}
}
|
3,038 |
Maximum Number of Operations With the Same Score I
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p>
<ul>
<li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li>
</ul>
<p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p>
<p>Return the <strong>maximum</strong> number of operations you can perform.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li>
<li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li>
<li>As there are fewer than two elements, we can't perform more operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li>
<li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li>
<li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Simulation
|
Python
|
class Solution:
def maxOperations(self, nums: List[int]) -> int:
s = nums[0] + nums[1]
ans, n = 0, len(nums)
for i in range(0, n, 2):
if i + 1 == n or nums[i] + nums[i + 1] != s:
break
ans += 1
return ans
|
3,038 |
Maximum Number of Operations With the Same Score I
|
Easy
|
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p>
<ul>
<li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li>
</ul>
<p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p>
<p>Return the <strong>maximum</strong> number of operations you can perform.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li>
<li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li>
<li>As there are fewer than two elements, we can't perform more operations.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li>
<li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li>
<li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Simulation
|
TypeScript
|
function maxOperations(nums: number[]): number {
const s = nums[0] + nums[1];
const n = nums.length;
let ans = 0;
for (let i = 0; i + 1 < n && nums[i] + nums[i + 1] === s; i += 2) {
++ans;
}
return ans;
}
|
3,039 |
Apply Operations to Make String Empty
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p>
<ul>
<li>For <strong>every</strong> alphabet character from <code>'a'</code> to <code>'z'</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li>
</ul>
<p>For example, let initially <code>s = "aabcbbca"</code>. We do the following operations:</p>
<ul>
<li>Remove the underlined characters <code>s = "<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca"</code>. The resulting string is <code>s = "abbca"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ab</strong></u>b<u><strong>c</strong></u>a"</code>. The resulting string is <code>s = "ba"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ba</strong></u>"</code>. The resulting string is <code>s = ""</code>.</li>
</ul>
<p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>"ba"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabcbbca"
<strong>Output:</strong> "ba"
<strong>Explanation:</strong> Explained in the statement.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong> We do the following operation:
- Remove the underlined characters s = "<u><strong>abcd</strong></u>". The resulting string is s = "".
The string just before the last operation is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; Counting; Sorting
|
C++
|
class Solution {
public:
string lastNonEmptyString(string s) {
int cnt[26]{};
int last[26]{};
int n = s.size();
int mx = 0;
for (int i = 0; i < n; ++i) {
int c = s[i] - 'a';
mx = max(mx, ++cnt[c]);
last[c] = i;
}
string ans;
for (int i = 0; i < n; ++i) {
int c = s[i] - 'a';
if (cnt[c] == mx && last[c] == i) {
ans.push_back(s[i]);
}
}
return ans;
}
};
|
3,039 |
Apply Operations to Make String Empty
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p>
<ul>
<li>For <strong>every</strong> alphabet character from <code>'a'</code> to <code>'z'</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li>
</ul>
<p>For example, let initially <code>s = "aabcbbca"</code>. We do the following operations:</p>
<ul>
<li>Remove the underlined characters <code>s = "<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca"</code>. The resulting string is <code>s = "abbca"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ab</strong></u>b<u><strong>c</strong></u>a"</code>. The resulting string is <code>s = "ba"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ba</strong></u>"</code>. The resulting string is <code>s = ""</code>.</li>
</ul>
<p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>"ba"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabcbbca"
<strong>Output:</strong> "ba"
<strong>Explanation:</strong> Explained in the statement.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong> We do the following operation:
- Remove the underlined characters s = "<u><strong>abcd</strong></u>". The resulting string is s = "".
The string just before the last operation is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; Counting; Sorting
|
Go
|
func lastNonEmptyString(s string) string {
cnt := [26]int{}
last := [26]int{}
mx := 0
for i, c := range s {
c -= 'a'
cnt[c]++
last[c] = i
mx = max(mx, cnt[c])
}
ans := []rune{}
for i, c := range s {
if cnt[c-'a'] == mx && last[c-'a'] == i {
ans = append(ans, c)
}
}
return string(ans)
}
|
3,039 |
Apply Operations to Make String Empty
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p>
<ul>
<li>For <strong>every</strong> alphabet character from <code>'a'</code> to <code>'z'</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li>
</ul>
<p>For example, let initially <code>s = "aabcbbca"</code>. We do the following operations:</p>
<ul>
<li>Remove the underlined characters <code>s = "<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca"</code>. The resulting string is <code>s = "abbca"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ab</strong></u>b<u><strong>c</strong></u>a"</code>. The resulting string is <code>s = "ba"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ba</strong></u>"</code>. The resulting string is <code>s = ""</code>.</li>
</ul>
<p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>"ba"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabcbbca"
<strong>Output:</strong> "ba"
<strong>Explanation:</strong> Explained in the statement.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong> We do the following operation:
- Remove the underlined characters s = "<u><strong>abcd</strong></u>". The resulting string is s = "".
The string just before the last operation is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; Counting; Sorting
|
Java
|
class Solution {
public String lastNonEmptyString(String s) {
int[] cnt = new int[26];
int[] last = new int[26];
int n = s.length();
int mx = 0;
for (int i = 0; i < n; ++i) {
int c = s.charAt(i) - 'a';
mx = Math.max(mx, ++cnt[c]);
last[c] = i;
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n; ++i) {
int c = s.charAt(i) - 'a';
if (cnt[c] == mx && last[c] == i) {
ans.append(s.charAt(i));
}
}
return ans.toString();
}
}
|
3,039 |
Apply Operations to Make String Empty
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p>
<ul>
<li>For <strong>every</strong> alphabet character from <code>'a'</code> to <code>'z'</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li>
</ul>
<p>For example, let initially <code>s = "aabcbbca"</code>. We do the following operations:</p>
<ul>
<li>Remove the underlined characters <code>s = "<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca"</code>. The resulting string is <code>s = "abbca"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ab</strong></u>b<u><strong>c</strong></u>a"</code>. The resulting string is <code>s = "ba"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ba</strong></u>"</code>. The resulting string is <code>s = ""</code>.</li>
</ul>
<p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>"ba"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabcbbca"
<strong>Output:</strong> "ba"
<strong>Explanation:</strong> Explained in the statement.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong> We do the following operation:
- Remove the underlined characters s = "<u><strong>abcd</strong></u>". The resulting string is s = "".
The string just before the last operation is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; Counting; Sorting
|
Python
|
class Solution:
def lastNonEmptyString(self, s: str) -> str:
cnt = Counter(s)
mx = cnt.most_common(1)[0][1]
last = {c: i for i, c in enumerate(s)}
return "".join(c for i, c in enumerate(s) if cnt[c] == mx and last[c] == i)
|
3,039 |
Apply Operations to Make String Empty
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p>
<ul>
<li>For <strong>every</strong> alphabet character from <code>'a'</code> to <code>'z'</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li>
</ul>
<p>For example, let initially <code>s = "aabcbbca"</code>. We do the following operations:</p>
<ul>
<li>Remove the underlined characters <code>s = "<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca"</code>. The resulting string is <code>s = "abbca"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ab</strong></u>b<u><strong>c</strong></u>a"</code>. The resulting string is <code>s = "ba"</code>.</li>
<li>Remove the underlined characters <code>s = "<u><strong>ba</strong></u>"</code>. The resulting string is <code>s = ""</code>.</li>
</ul>
<p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>"ba"</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aabcbbca"
<strong>Output:</strong> "ba"
<strong>Explanation:</strong> Explained in the statement.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "abcd"
<strong>Explanation:</strong> We do the following operation:
- Remove the underlined characters s = "<u><strong>abcd</strong></u>". The resulting string is s = "".
The string just before the last operation is "abcd".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Array; Hash Table; Counting; Sorting
|
TypeScript
|
function lastNonEmptyString(s: string): string {
const cnt: number[] = Array(26).fill(0);
const last: number[] = Array(26).fill(0);
const n = s.length;
let mx = 0;
for (let i = 0; i < n; ++i) {
const c = s.charCodeAt(i) - 97;
mx = Math.max(mx, ++cnt[c]);
last[c] = i;
}
const ans: string[] = [];
for (let i = 0; i < n; ++i) {
const c = s.charCodeAt(i) - 97;
if (cnt[c] === mx && last[c] === i) {
ans.push(String.fromCharCode(c + 97));
}
}
return ans.join('');
}
|
3,040 |
Maximum Number of Operations With the Same Score II
|
Medium
|
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p>
<ul>
<li>Choose the first two elements of <code>nums</code> and delete them.</li>
<li>Choose the last two elements of <code>nums</code> and delete them.</li>
<li>Choose the first and the last elements of <code>nums</code> and delete them.</li>
</ul>
<p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p>
<p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p>
<p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].
- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].
- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].
We are unable to perform any more operations as nums is empty.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,6,1,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
- Delete the last two elements, with score 1 + 4 = 5, nums = [6].
It can be proven that we can perform at most 2 operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Memoization; Array; Dynamic Programming
|
C++
|
class Solution {
public:
int maxOperations(vector<int>& nums) {
int n = nums.size();
int f[n][n];
auto g = [&](int i, int j, int s) -> int {
memset(f, -1, sizeof(f));
function<int(int, int)> dfs = [&](int i, int j) -> int {
if (j - i < 1) {
return 0;
}
if (f[i][j] != -1) {
return f[i][j];
}
int ans = 0;
if (nums[i] + nums[i + 1] == s) {
ans = max(ans, 1 + dfs(i + 2, j));
}
if (nums[i] + nums[j] == s) {
ans = max(ans, 1 + dfs(i + 1, j - 1));
}
if (nums[j - 1] + nums[j] == s) {
ans = max(ans, 1 + dfs(i, j - 2));
}
return f[i][j] = ans;
};
return dfs(i, j);
};
int a = g(2, n - 1, nums[0] + nums[1]);
int b = g(0, n - 3, nums[n - 2] + nums[n - 1]);
int c = g(1, n - 2, nums[0] + nums[n - 1]);
return 1 + max({a, b, c});
}
};
|
3,040 |
Maximum Number of Operations With the Same Score II
|
Medium
|
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p>
<ul>
<li>Choose the first two elements of <code>nums</code> and delete them.</li>
<li>Choose the last two elements of <code>nums</code> and delete them.</li>
<li>Choose the first and the last elements of <code>nums</code> and delete them.</li>
</ul>
<p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p>
<p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p>
<p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].
- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].
- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].
We are unable to perform any more operations as nums is empty.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,6,1,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
- Delete the last two elements, with score 1 + 4 = 5, nums = [6].
It can be proven that we can perform at most 2 operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Memoization; Array; Dynamic Programming
|
Go
|
func maxOperations(nums []int) int {
n := len(nums)
var g func(i, j, s int) int
g = func(i, j, s int) int {
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f {
f[i][j] = -1
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if j-i < 1 {
return 0
}
if f[i][j] != -1 {
return f[i][j]
}
ans := 0
if nums[i]+nums[i+1] == s {
ans = max(ans, 1+dfs(i+2, j))
}
if nums[i]+nums[j] == s {
ans = max(ans, 1+dfs(i+1, j-1))
}
if nums[j-1]+nums[j] == s {
ans = max(ans, 1+dfs(i, j-2))
}
f[i][j] = ans
return ans
}
return dfs(i, j)
}
a := g(2, n-1, nums[0]+nums[1])
b := g(0, n-3, nums[n-1]+nums[n-2])
c := g(1, n-2, nums[0]+nums[n-1])
return 1 + max(a, b, c)
}
|
3,040 |
Maximum Number of Operations With the Same Score II
|
Medium
|
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p>
<ul>
<li>Choose the first two elements of <code>nums</code> and delete them.</li>
<li>Choose the last two elements of <code>nums</code> and delete them.</li>
<li>Choose the first and the last elements of <code>nums</code> and delete them.</li>
</ul>
<p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p>
<p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p>
<p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].
- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].
- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].
We are unable to perform any more operations as nums is empty.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,6,1,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
- Delete the last two elements, with score 1 + 4 = 5, nums = [6].
It can be proven that we can perform at most 2 operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Memoization; Array; Dynamic Programming
|
Java
|
class Solution {
private Integer[][] f;
private int[] nums;
private int s;
private int n;
public int maxOperations(int[] nums) {
this.nums = nums;
n = nums.length;
int a = g(2, n - 1, nums[0] + nums[1]);
int b = g(0, n - 3, nums[n - 2] + nums[n - 1]);
int c = g(1, n - 2, nums[0] + nums[n - 1]);
return 1 + Math.max(a, Math.max(b, c));
}
private int g(int i, int j, int s) {
f = new Integer[n][n];
this.s = s;
return dfs(i, j);
}
private int dfs(int i, int j) {
if (j - i < 1) {
return 0;
}
if (f[i][j] != null) {
return f[i][j];
}
int ans = 0;
if (nums[i] + nums[i + 1] == s) {
ans = Math.max(ans, 1 + dfs(i + 2, j));
}
if (nums[i] + nums[j] == s) {
ans = Math.max(ans, 1 + dfs(i + 1, j - 1));
}
if (nums[j - 1] + nums[j] == s) {
ans = Math.max(ans, 1 + dfs(i, j - 2));
}
return f[i][j] = ans;
}
}
|
3,040 |
Maximum Number of Operations With the Same Score II
|
Medium
|
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p>
<ul>
<li>Choose the first two elements of <code>nums</code> and delete them.</li>
<li>Choose the last two elements of <code>nums</code> and delete them.</li>
<li>Choose the first and the last elements of <code>nums</code> and delete them.</li>
</ul>
<p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p>
<p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p>
<p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].
- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].
- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].
We are unable to perform any more operations as nums is empty.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,6,1,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
- Delete the last two elements, with score 1 + 4 = 5, nums = [6].
It can be proven that we can perform at most 2 operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Memoization; Array; Dynamic Programming
|
Python
|
class Solution:
def maxOperations(self, nums: List[int]) -> int:
@cache
def dfs(i: int, j: int, s: int) -> int:
if j - i < 1:
return 0
ans = 0
if nums[i] + nums[i + 1] == s:
ans = max(ans, 1 + dfs(i + 2, j, s))
if nums[i] + nums[j] == s:
ans = max(ans, 1 + dfs(i + 1, j - 1, s))
if nums[j - 1] + nums[j] == s:
ans = max(ans, 1 + dfs(i, j - 2, s))
return ans
n = len(nums)
a = dfs(2, n - 1, nums[0] + nums[1])
b = dfs(0, n - 3, nums[-1] + nums[-2])
c = dfs(1, n - 2, nums[0] + nums[-1])
return 1 + max(a, b, c)
|
3,040 |
Maximum Number of Operations With the Same Score II
|
Medium
|
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p>
<ul>
<li>Choose the first two elements of <code>nums</code> and delete them.</li>
<li>Choose the last two elements of <code>nums</code> and delete them.</li>
<li>Choose the first and the last elements of <code>nums</code> and delete them.</li>
</ul>
<p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p>
<p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p>
<p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].
- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].
- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].
We are unable to perform any more operations as nums is empty.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,2,6,1,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
- Delete the last two elements, with score 1 + 4 = 5, nums = [6].
It can be proven that we can perform at most 2 operations.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 2000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Memoization; Array; Dynamic Programming
|
TypeScript
|
function maxOperations(nums: number[]): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(n));
const g = (i: number, j: number, s: number): number => {
f.forEach(row => row.fill(-1));
const dfs = (i: number, j: number): number => {
if (j - i < 1) {
return 0;
}
if (f[i][j] !== -1) {
return f[i][j];
}
let ans = 0;
if (nums[i] + nums[i + 1] === s) {
ans = Math.max(ans, 1 + dfs(i + 2, j));
}
if (nums[i] + nums[j] === s) {
ans = Math.max(ans, 1 + dfs(i + 1, j - 1));
}
if (nums[j - 1] + nums[j] === s) {
ans = Math.max(ans, 1 + dfs(i, j - 2));
}
return (f[i][j] = ans);
};
return dfs(i, j);
};
const a = g(2, n - 1, nums[0] + nums[1]);
const b = g(0, n - 3, nums[n - 2] + nums[n - 1]);
const c = g(1, n - 2, nums[0] + nums[n - 1]);
return 1 + Math.max(a, b, c);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.