id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
3,205
|
Maximum Array Hopping Score I
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
|
C++
|
class Solution {
public:
int maxScore(vector<int>& nums) {
int n = nums.size();
vector<int> f(n);
auto dfs = [&](this auto&& dfs, int i) -> int {
if (f[i]) {
return f[i];
}
for (int j = i + 1; j < n; ++j) {
f[i] = max(f[i], (j - i) * nums[j] + dfs(j));
}
return f[i];
};
return dfs(0);
}
};
|
3,205
|
Maximum Array Hopping Score I
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
|
Go
|
func maxScore(nums []int) int {
n := len(nums)
f := make([]int, n)
var dfs func(int) int
dfs = func(i int) int {
if f[i] > 0 {
return f[i]
}
for j := i + 1; j < n; j++ {
f[i] = max(f[i], (j-i)*nums[j]+dfs(j))
}
return f[i]
}
return dfs(0)
}
|
3,205
|
Maximum Array Hopping Score I
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
|
Java
|
class Solution {
private Integer[] f;
private int[] nums;
private int n;
public int maxScore(int[] nums) {
n = nums.length;
f = new Integer[n];
this.nums = nums;
return dfs(0);
}
private int dfs(int i) {
if (f[i] != null) {
return f[i];
}
f[i] = 0;
for (int j = i + 1; j < n; ++j) {
f[i] = Math.max(f[i], (j - i) * nums[j] + dfs(j));
}
return f[i];
}
}
|
3,205
|
Maximum Array Hopping Score I
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
|
Python
|
class Solution:
def maxScore(self, nums: List[int]) -> int:
@cache
def dfs(i: int) -> int:
return max(
[(j - i) * nums[j] + dfs(j) for j in range(i + 1, len(nums))] or [0]
)
return dfs(0)
|
3,205
|
Maximum Array Hopping Score I
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Dynamic Programming; Monotonic Stack
|
TypeScript
|
function maxScore(nums: number[]): number {
const n = nums.length;
const f: number[] = Array(n).fill(0);
const dfs = (i: number): number => {
if (f[i]) {
return f[i];
}
for (let j = i + 1; j < n; ++j) {
f[i] = Math.max(f[i], (j - i) * nums[j] + dfs(j));
}
return f[i];
};
return dfs(0);
}
|
3,206
|
Alternating Groups I
|
Easy
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Alternating groups:</p>
<p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 100</code></li>
<li><code>0 <= colors[i] <= 1</code></li>
</ul>
|
Array; Sliding Window
|
C++
|
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& colors) {
int k = 3;
int n = colors.size();
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
};
|
3,206
|
Alternating Groups I
|
Easy
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Alternating groups:</p>
<p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 100</code></li>
<li><code>0 <= colors[i] <= 1</code></li>
</ul>
|
Array; Sliding Window
|
Go
|
func numberOfAlternatingGroups(colors []int) (ans int) {
k := 3
n := len(colors)
cnt := 0
for i := 0; i < n<<1; i++ {
if i > 0 && colors[i%n] == colors[(i-1)%n] {
cnt = 1
} else {
cnt++
}
if i >= n && cnt >= k {
ans++
}
}
return
}
|
3,206
|
Alternating Groups I
|
Easy
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Alternating groups:</p>
<p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 100</code></li>
<li><code>0 <= colors[i] <= 1</code></li>
</ul>
|
Array; Sliding Window
|
Java
|
class Solution {
public int numberOfAlternatingGroups(int[] colors) {
int k = 3;
int n = colors.length;
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i > 0 && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
}
|
3,206
|
Alternating Groups I
|
Easy
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Alternating groups:</p>
<p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 100</code></li>
<li><code>0 <= colors[i] <= 1</code></li>
</ul>
|
Array; Sliding Window
|
Python
|
class Solution:
def numberOfAlternatingGroups(self, colors: List[int]) -> int:
k = 3
n = len(colors)
ans = cnt = 0
for i in range(n << 1):
if i and colors[i % n] == colors[(i - 1) % n]:
cnt = 1
else:
cnt += 1
ans += i >= n and cnt >= k
return ans
|
3,206
|
Alternating Groups I
|
Easy
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>Every 3 contiguous tiles in the circle with <strong>alternating</strong> colors (the middle tile has a different color from its <strong>left</strong> and <strong>right</strong> tiles) is called an <strong>alternating</strong> group.</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-53-171.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1]</span></p>
<p><strong>Output:</strong> 3</p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-47-491.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></p>
<p>Alternating groups:</p>
<p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-50-441.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-48-211.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3206.Alternating%20Groups%20I/images/image_2024-05-16_23-49-351.png" style="width: 150px; height: 150px; padding: 10px; background: #fff; border-radius: .5rem;" /></strong></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 100</code></li>
<li><code>0 <= colors[i] <= 1</code></li>
</ul>
|
Array; Sliding Window
|
TypeScript
|
function numberOfAlternatingGroups(colors: number[]): number {
const k = 3;
const n = colors.length;
let [ans, cnt] = [0, 0];
for (let i = 0; i < n << 1; ++i) {
if (i && colors[i % n] === colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
|
3,207
|
Maximum Points After Enemy Battles
|
Medium
|
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p>
<p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p>
<p>You start with 0 points, and all the enemies are unmarked initially.</p>
<p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p>
<ul>
<li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy >= enemyEnergies[i]</code>. By choosing this option:
<ul>
<li>You gain 1 point.</li>
<li>Your energy is reduced by the enemy's energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li>
</ul>
</li>
<li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option:
<ul>
<li>Your energy increases by the enemy's energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li>
<li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li>
</ul>
</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The following operations can be performed to get 3 points, which is the maximum:</p>
<ul>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li>
<li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li>
<li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li>
<li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation: </strong></p>
<p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= enemyEnergies.length <= 10<sup>5</sup></code></li>
<li><code>1 <= enemyEnergies[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= currentEnergy <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array
|
C++
|
class Solution {
public:
long long maximumPoints(vector<int>& enemyEnergies, int currentEnergy) {
sort(enemyEnergies.begin(), enemyEnergies.end());
if (currentEnergy < enemyEnergies[0]) {
return 0;
}
long long ans = 0;
for (int i = enemyEnergies.size() - 1; i >= 0; --i) {
ans += currentEnergy / enemyEnergies[0];
currentEnergy %= enemyEnergies[0];
currentEnergy += enemyEnergies[i];
}
return ans;
}
};
|
3,207
|
Maximum Points After Enemy Battles
|
Medium
|
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p>
<p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p>
<p>You start with 0 points, and all the enemies are unmarked initially.</p>
<p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p>
<ul>
<li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy >= enemyEnergies[i]</code>. By choosing this option:
<ul>
<li>You gain 1 point.</li>
<li>Your energy is reduced by the enemy's energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li>
</ul>
</li>
<li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option:
<ul>
<li>Your energy increases by the enemy's energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li>
<li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li>
</ul>
</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The following operations can be performed to get 3 points, which is the maximum:</p>
<ul>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li>
<li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li>
<li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li>
<li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation: </strong></p>
<p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= enemyEnergies.length <= 10<sup>5</sup></code></li>
<li><code>1 <= enemyEnergies[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= currentEnergy <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array
|
Go
|
func maximumPoints(enemyEnergies []int, currentEnergy int) (ans int64) {
sort.Ints(enemyEnergies)
if currentEnergy < enemyEnergies[0] {
return 0
}
for i := len(enemyEnergies) - 1; i >= 0; i-- {
ans += int64(currentEnergy / enemyEnergies[0])
currentEnergy %= enemyEnergies[0]
currentEnergy += enemyEnergies[i]
}
return
}
|
3,207
|
Maximum Points After Enemy Battles
|
Medium
|
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p>
<p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p>
<p>You start with 0 points, and all the enemies are unmarked initially.</p>
<p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p>
<ul>
<li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy >= enemyEnergies[i]</code>. By choosing this option:
<ul>
<li>You gain 1 point.</li>
<li>Your energy is reduced by the enemy's energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li>
</ul>
</li>
<li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option:
<ul>
<li>Your energy increases by the enemy's energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li>
<li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li>
</ul>
</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The following operations can be performed to get 3 points, which is the maximum:</p>
<ul>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li>
<li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li>
<li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li>
<li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation: </strong></p>
<p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= enemyEnergies.length <= 10<sup>5</sup></code></li>
<li><code>1 <= enemyEnergies[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= currentEnergy <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array
|
Java
|
class Solution {
public long maximumPoints(int[] enemyEnergies, int currentEnergy) {
Arrays.sort(enemyEnergies);
if (currentEnergy < enemyEnergies[0]) {
return 0;
}
long ans = 0;
for (int i = enemyEnergies.length - 1; i >= 0; --i) {
ans += currentEnergy / enemyEnergies[0];
currentEnergy %= enemyEnergies[0];
currentEnergy += enemyEnergies[i];
}
return ans;
}
};
|
3,207
|
Maximum Points After Enemy Battles
|
Medium
|
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p>
<p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p>
<p>You start with 0 points, and all the enemies are unmarked initially.</p>
<p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p>
<ul>
<li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy >= enemyEnergies[i]</code>. By choosing this option:
<ul>
<li>You gain 1 point.</li>
<li>Your energy is reduced by the enemy's energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li>
</ul>
</li>
<li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option:
<ul>
<li>Your energy increases by the enemy's energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li>
<li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li>
</ul>
</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The following operations can be performed to get 3 points, which is the maximum:</p>
<ul>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li>
<li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li>
<li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li>
<li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation: </strong></p>
<p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= enemyEnergies.length <= 10<sup>5</sup></code></li>
<li><code>1 <= enemyEnergies[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= currentEnergy <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array
|
Python
|
class Solution:
def maximumPoints(self, enemyEnergies: List[int], currentEnergy: int) -> int:
enemyEnergies.sort()
if currentEnergy < enemyEnergies[0]:
return 0
ans = 0
for i in range(len(enemyEnergies) - 1, -1, -1):
ans += currentEnergy // enemyEnergies[0]
currentEnergy %= enemyEnergies[0]
currentEnergy += enemyEnergies[i]
return ans
|
3,207
|
Maximum Points After Enemy Battles
|
Medium
|
<p>You are given an integer array <code>enemyEnergies</code> denoting the energy values of various enemies.</p>
<p>You are also given an integer <code>currentEnergy</code> denoting the amount of energy you have initially.</p>
<p>You start with 0 points, and all the enemies are unmarked initially.</p>
<p>You can perform <strong>either</strong> of the following operations <strong>zero </strong>or multiple times to gain points:</p>
<ul>
<li>Choose an <strong>unmarked</strong> enemy, <code>i</code>, such that <code>currentEnergy >= enemyEnergies[i]</code>. By choosing this option:
<ul>
<li>You gain 1 point.</li>
<li>Your energy is reduced by the enemy's energy, i.e. <code>currentEnergy = currentEnergy - enemyEnergies[i]</code>.</li>
</ul>
</li>
<li>If you have <strong>at least</strong> 1 point, you can choose an <strong>unmarked</strong> enemy, <code>i</code>. By choosing this option:
<ul>
<li>Your energy increases by the enemy's energy, i.e. <code>currentEnergy = currentEnergy + enemyEnergies[i]</code>.</li>
<li>The <font face="monospace">e</font>nemy <code>i</code> is <strong>marked</strong>.</li>
</ul>
</li>
</ul>
<p>Return an integer denoting the <strong>maximum</strong> points you can get in the end by optimally performing operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = [3,2,2], currentEnergy = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>The following operations can be performed to get 3 points, which is the maximum:</p>
<ul>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 1</code>, and <code>currentEnergy = 0</code>.</li>
<li>Second operation on enemy 0: <code>currentEnergy</code> increases by 3, and enemy 0 is marked. So, <code>points = 1</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0]</code>.</li>
<li>First operation on enemy 2: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 2</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0]</code>.</li>
<li>Second operation on enemy 2: <code>currentEnergy</code> increases by 2, and enemy 2 is marked. So, <code>points = 2</code>, <code>currentEnergy = 3</code>, and marked enemies = <code>[0, 2]</code>.</li>
<li>First operation on enemy 1: <code>points</code> increases by 1, and <code>currentEnergy</code> decreases by 2. So, <code>points = 3</code>, <code>currentEnergy = 1</code>, and marked enemies = <code>[0, 2]</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">enemyEnergies = </span>[2]<span class="example-io">, currentEnergy = 10</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation: </strong></p>
<p>Performing the first operation 5 times on enemy 0 results in the maximum number of points.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= enemyEnergies.length <= 10<sup>5</sup></code></li>
<li><code>1 <= enemyEnergies[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= currentEnergy <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array
|
TypeScript
|
function maximumPoints(enemyEnergies: number[], currentEnergy: number): number {
enemyEnergies.sort((a, b) => a - b);
if (currentEnergy < enemyEnergies[0]) {
return 0;
}
let ans = 0;
for (let i = enemyEnergies.length - 1; ~i; --i) {
ans += Math.floor(currentEnergy / enemyEnergies[0]);
currentEnergy %= enemyEnergies[0];
currentEnergy += enemyEnergies[i];
}
return ans;
}
|
3,208
|
Alternating Groups II
|
Medium
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 10<sup>5</sup></code></li>
<li><code>0 <= colors[i] <= 1</code></li>
<li><code>3 <= k <= colors.length</code></li>
</ul>
|
Array; Sliding Window
|
C++
|
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& colors, int k) {
int n = colors.size();
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
};
|
3,208
|
Alternating Groups II
|
Medium
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 10<sup>5</sup></code></li>
<li><code>0 <= colors[i] <= 1</code></li>
<li><code>3 <= k <= colors.length</code></li>
</ul>
|
Array; Sliding Window
|
Go
|
func numberOfAlternatingGroups(colors []int, k int) (ans int) {
n := len(colors)
cnt := 0
for i := 0; i < n<<1; i++ {
if i > 0 && colors[i%n] == colors[(i-1)%n] {
cnt = 1
} else {
cnt++
}
if i >= n && cnt >= k {
ans++
}
}
return
}
|
3,208
|
Alternating Groups II
|
Medium
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 10<sup>5</sup></code></li>
<li><code>0 <= colors[i] <= 1</code></li>
<li><code>3 <= k <= colors.length</code></li>
</ul>
|
Array; Sliding Window
|
Java
|
class Solution {
public int numberOfAlternatingGroups(int[] colors, int k) {
int n = colors.length;
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i > 0 && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
}
|
3,208
|
Alternating Groups II
|
Medium
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 10<sup>5</sup></code></li>
<li><code>0 <= colors[i] <= 1</code></li>
<li><code>3 <= k <= colors.length</code></li>
</ul>
|
Array; Sliding Window
|
Python
|
class Solution:
def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int:
n = len(colors)
ans = cnt = 0
for i in range(n << 1):
if i and colors[i % n] == colors[(i - 1) % n]:
cnt = 1
else:
cnt += 1
ans += i >= n and cnt >= k
return ans
|
3,208
|
Alternating Groups II
|
Medium
|
<p>There is a circle of red and blue tiles. You are given an array of integers <code>colors</code> and an integer <code>k</code>. The color of tile <code>i</code> is represented by <code>colors[i]</code>:</p>
<ul>
<li><code>colors[i] == 0</code> means that tile <code>i</code> is <strong>red</strong>.</li>
<li><code>colors[i] == 1</code> means that tile <code>i</code> is <strong>blue</strong>.</li>
</ul>
<p>An <strong>alternating</strong> group is every <code>k</code> contiguous tiles in the circle with <strong>alternating</strong> colors (each tile in the group except the first and last one has a different color from its <strong>left</strong> and <strong>right</strong> tiles).</p>
<p>Return the number of <strong>alternating</strong> groups.</p>
<p><strong>Note</strong> that since <code>colors</code> represents a <strong>circle</strong>, the <strong>first</strong> and the <strong>last</strong> tiles are considered to be next to each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,1,0], k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183519.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182448.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-182844.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183057.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [0,1,0,0,1,0,1], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-183907.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></strong></p>
<p>Alternating groups:</p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184128.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184240.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">colors = [1,1,0,1], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" data-darkreader-inline-bgcolor="" data-darkreader-inline-bgimage="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3208.Alternating%20Groups%20II/images/screenshot-2024-05-28-184516.png" style="width: 150px; height: 150px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; --darkreader-inline-bgimage: initial; --darkreader-inline-bgcolor: #181a1b;" /></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= colors.length <= 10<sup>5</sup></code></li>
<li><code>0 <= colors[i] <= 1</code></li>
<li><code>3 <= k <= colors.length</code></li>
</ul>
|
Array; Sliding Window
|
TypeScript
|
function numberOfAlternatingGroups(colors: number[], k: number): number {
const n = colors.length;
let [ans, cnt] = [0, 0];
for (let i = 0; i < n << 1; ++i) {
if (i && colors[i % n] === colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
|
3,209
|
Number of Subarrays With AND Value of K
|
Hard
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>All subarrays contain only 1's.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
C++
|
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k) {
long long ans = 0;
unordered_map<int, int> pre;
for (int x : nums) {
unordered_map<int, int> cur;
for (auto& [y, v] : pre) {
cur[x & y] += v;
}
cur[x]++;
ans += cur[k];
pre = cur;
}
return ans;
}
};
|
3,209
|
Number of Subarrays With AND Value of K
|
Hard
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>All subarrays contain only 1's.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Go
|
func countSubarrays(nums []int, k int) (ans int64) {
pre := map[int]int{}
for _, x := range nums {
cur := map[int]int{}
for y, v := range pre {
cur[x&y] += v
}
cur[x]++
ans += int64(cur[k])
pre = cur
}
return
}
|
3,209
|
Number of Subarrays With AND Value of K
|
Hard
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>All subarrays contain only 1's.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Java
|
class Solution {
public long countSubarrays(int[] nums, int k) {
long ans = 0;
Map<Integer, Integer> pre = new HashMap<>();
for (int x : nums) {
Map<Integer, Integer> cur = new HashMap<>();
for (var e : pre.entrySet()) {
int y = e.getKey(), v = e.getValue();
cur.merge(x & y, v, Integer::sum);
}
cur.merge(x, 1, Integer::sum);
ans += cur.getOrDefault(k, 0);
pre = cur;
}
return ans;
}
}
|
3,209
|
Number of Subarrays With AND Value of K
|
Hard
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>All subarrays contain only 1's.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
Python
|
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
pre = Counter()
for x in nums:
cur = Counter()
for y, v in pre.items():
cur[x & y] += v
cur[x] += 1
ans += cur[k]
pre = cur
return ans
|
3,209
|
Number of Subarrays With AND Value of K
|
Hard
|
<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of <code>nums</code> where the bitwise <code>AND</code> of the elements of the subarray equals <code>k</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>All subarrays contain only 1's.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 1 are: <code>[<u><strong>1</strong></u>,1,2]</code>, <code>[1,<u><strong>1</strong></u>,2]</code>, <code>[<u><strong>1,1</strong></u>,2]</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>Subarrays having an <code>AND</code> value of 2 are: <code>[1,<b><u>2</u></b>,3]</code>, <code>[1,<u><strong>2,3</strong></u>]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i], k <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Segment Tree; Array; Binary Search
|
TypeScript
|
function countSubarrays(nums: number[], k: number): number {
let ans = 0;
let pre = new Map<number, number>();
for (const x of nums) {
const cur = new Map<number, number>();
for (const [y, v] of pre) {
const z = x & y;
cur.set(z, (cur.get(z) || 0) + v);
}
cur.set(x, (cur.get(x) || 0) + 1);
ans += cur.get(k) || 0;
pre = cur;
}
return ans;
}
|
3,210
|
Find the Encrypted String
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p>
<ul>
<li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li>
</ul>
<p>Return the <em>encrypted string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "dart", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"tdar"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>'d'</code> is <code>'t'</code>.</li>
<li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>'a'</code> is <code>'d'</code>.</li>
<li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>'r'</code> is <code>'a'</code>.</li>
<li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>'t'</code> is <code>'r'</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaa", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaa"</span></p>
<p><strong>Explanation:</strong></p>
<p>As all the characters are the same, the encrypted string will also be the same.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
string getEncryptedString(string s, int k) {
int n = s.length();
string cs(n, ' ');
for (int i = 0; i < n; ++i) {
cs[i] = s[(i + k) % n];
}
return cs;
}
};
|
3,210
|
Find the Encrypted String
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p>
<ul>
<li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li>
</ul>
<p>Return the <em>encrypted string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "dart", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"tdar"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>'d'</code> is <code>'t'</code>.</li>
<li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>'a'</code> is <code>'d'</code>.</li>
<li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>'r'</code> is <code>'a'</code>.</li>
<li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>'t'</code> is <code>'r'</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaa", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaa"</span></p>
<p><strong>Explanation:</strong></p>
<p>As all the characters are the same, the encrypted string will also be the same.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Go
|
func getEncryptedString(s string, k int) string {
cs := []byte(s)
for i := range s {
cs[i] = s[(i+k)%len(s)]
}
return string(cs)
}
|
3,210
|
Find the Encrypted String
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p>
<ul>
<li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li>
</ul>
<p>Return the <em>encrypted string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "dart", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"tdar"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>'d'</code> is <code>'t'</code>.</li>
<li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>'a'</code> is <code>'d'</code>.</li>
<li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>'r'</code> is <code>'a'</code>.</li>
<li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>'t'</code> is <code>'r'</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaa", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaa"</span></p>
<p><strong>Explanation:</strong></p>
<p>As all the characters are the same, the encrypted string will also be the same.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Java
|
class Solution {
public String getEncryptedString(String s, int k) {
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; ++i) {
cs[i] = s.charAt((i + k) % n);
}
return new String(cs);
}
}
|
3,210
|
Find the Encrypted String
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p>
<ul>
<li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li>
</ul>
<p>Return the <em>encrypted string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "dart", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"tdar"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>'d'</code> is <code>'t'</code>.</li>
<li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>'a'</code> is <code>'d'</code>.</li>
<li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>'r'</code> is <code>'a'</code>.</li>
<li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>'t'</code> is <code>'r'</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaa", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaa"</span></p>
<p><strong>Explanation:</strong></p>
<p>As all the characters are the same, the encrypted string will also be the same.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
Python
|
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
cs = list(s)
n = len(s)
for i in range(n):
cs[i] = s[(i + k) % n]
return "".join(cs)
|
3,210
|
Find the Encrypted String
|
Easy
|
<p>You are given a string <code>s</code> and an integer <code>k</code>. Encrypt the string using the following algorithm:</p>
<ul>
<li>For each character <code>c</code> in <code>s</code>, replace <code>c</code> with the <code>k<sup>th</sup></code> character after <code>c</code> in the string (in a cyclic manner).</li>
</ul>
<p>Return the <em>encrypted string</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "dart", k = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">"tdar"</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>For <code>i = 0</code>, the 3<sup>rd</sup> character after <code>'d'</code> is <code>'t'</code>.</li>
<li>For <code>i = 1</code>, the 3<sup>rd</sup> character after <code>'a'</code> is <code>'d'</code>.</li>
<li>For <code>i = 2</code>, the 3<sup>rd</sup> character after <code>'r'</code> is <code>'a'</code>.</li>
<li>For <code>i = 3</code>, the 3<sup>rd</sup> character after <code>'t'</code> is <code>'r'</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aaa", k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">"aaa"</span></p>
<p><strong>Explanation:</strong></p>
<p>As all the characters are the same, the encrypted string will also be the same.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>1 <= k <= 10<sup>4</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
String
|
TypeScript
|
function getEncryptedString(s: string, k: number): string {
const cs: string[] = [];
const n = s.length;
for (let i = 0; i < n; ++i) {
cs[i] = s[(i + k) % n];
}
return cs.join('');
}
|
3,211
|
Generate Binary Strings Without Adjacent Zeros
|
Medium
|
<p>You are given a positive integer <code>n</code>.</p>
<p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>"1"</code>.</p>
<p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">["010","011","101","110","111"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 3 are: <code>"010"</code>, <code>"011"</code>, <code>"101"</code>, <code>"110"</code>, and <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">["0","1"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 1 are: <code>"0"</code> and <code>"1"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 18</code></li>
</ul>
|
Bit Manipulation; String; Backtracking
|
C++
|
class Solution {
public:
vector<string> validStrings(int n) {
vector<string> ans;
string t;
auto dfs = [&](this auto&& dfs, int i) {
if (i >= n) {
ans.emplace_back(t);
return;
}
for (int j = 0; j < 2; ++j) {
if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) {
t.push_back('0' + j);
dfs(i + 1);
t.pop_back();
}
}
};
dfs(0);
return ans;
}
};
|
3,211
|
Generate Binary Strings Without Adjacent Zeros
|
Medium
|
<p>You are given a positive integer <code>n</code>.</p>
<p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>"1"</code>.</p>
<p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">["010","011","101","110","111"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 3 are: <code>"010"</code>, <code>"011"</code>, <code>"101"</code>, <code>"110"</code>, and <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">["0","1"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 1 are: <code>"0"</code> and <code>"1"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 18</code></li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Go
|
func validStrings(n int) (ans []string) {
t := []byte{}
var dfs func(int)
dfs = func(i int) {
if i >= n {
ans = append(ans, string(t))
return
}
for j := 0; j < 2; j++ {
if (j == 0 && (i == 0 || t[i-1] == '1')) || j == 1 {
t = append(t, byte('0'+j))
dfs(i + 1)
t = t[:len(t)-1]
}
}
}
dfs(0)
return
}
|
3,211
|
Generate Binary Strings Without Adjacent Zeros
|
Medium
|
<p>You are given a positive integer <code>n</code>.</p>
<p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>"1"</code>.</p>
<p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">["010","011","101","110","111"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 3 are: <code>"010"</code>, <code>"011"</code>, <code>"101"</code>, <code>"110"</code>, and <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">["0","1"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 1 are: <code>"0"</code> and <code>"1"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 18</code></li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Java
|
class Solution {
private List<String> ans = new ArrayList<>();
private StringBuilder t = new StringBuilder();
private int n;
public List<String> validStrings(int n) {
this.n = n;
dfs(0);
return ans;
}
private void dfs(int i) {
if (i >= n) {
ans.add(t.toString());
return;
}
for (int j = 0; j < 2; ++j) {
if ((j == 0 && (i == 0 || t.charAt(i - 1) == '1')) || j == 1) {
t.append(j);
dfs(i + 1);
t.deleteCharAt(t.length() - 1);
}
}
}
}
|
3,211
|
Generate Binary Strings Without Adjacent Zeros
|
Medium
|
<p>You are given a positive integer <code>n</code>.</p>
<p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>"1"</code>.</p>
<p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">["010","011","101","110","111"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 3 are: <code>"010"</code>, <code>"011"</code>, <code>"101"</code>, <code>"110"</code>, and <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">["0","1"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 1 are: <code>"0"</code> and <code>"1"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 18</code></li>
</ul>
|
Bit Manipulation; String; Backtracking
|
Python
|
class Solution:
def validStrings(self, n: int) -> List[str]:
def dfs(i: int):
if i >= n:
ans.append("".join(t))
return
for j in range(2):
if (j == 0 and (i == 0 or t[i - 1] == "1")) or j == 1:
t.append(str(j))
dfs(i + 1)
t.pop()
ans = []
t = []
dfs(0)
return ans
|
3,211
|
Generate Binary Strings Without Adjacent Zeros
|
Medium
|
<p>You are given a positive integer <code>n</code>.</p>
<p>A binary string <code>x</code> is <strong>valid</strong> if all <span data-keyword="substring-nonempty">substrings</span> of <code>x</code> of length 2 contain <strong>at least</strong> one <code>"1"</code>.</p>
<p>Return all <strong>valid</strong> strings with length <code>n</code><strong>, </strong>in <em>any</em> order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3</span></p>
<p><strong>Output:</strong> <span class="example-io">["010","011","101","110","111"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 3 are: <code>"010"</code>, <code>"011"</code>, <code>"101"</code>, <code>"110"</code>, and <code>"111"</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">["0","1"]</span></p>
<p><strong>Explanation:</strong></p>
<p>The valid strings of length 1 are: <code>"0"</code> and <code>"1"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 18</code></li>
</ul>
|
Bit Manipulation; String; Backtracking
|
TypeScript
|
function validStrings(n: number): string[] {
const ans: string[] = [];
const t: string[] = [];
const dfs = (i: number) => {
if (i >= n) {
ans.push(t.join(''));
return;
}
for (let j = 0; j < 2; ++j) {
if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) {
t.push(j.toString());
dfs(i + 1);
t.pop();
}
}
};
dfs(0);
return ans;
}
|
3,212
|
Count Submatrices With Equal Frequency of X and Y
|
Medium
|
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p>
<ul>
<li><code>grid[0][0]</code></li>
<li>an <strong>equal</strong> frequency of <code>'X'</code> and <code>'Y'</code>.</li>
<li><strong>at least</strong> one <code>'X'</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","Y","."],["Y",".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","X"],["X","Y"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has an equal frequency of <code>'X'</code> and <code>'Y'</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[".","."],[".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has at least one <code>'X'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[i].length <= 1000</code></li>
<li><code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>.</li>
</ul>
|
Array; Matrix; Prefix Sum
|
C++
|
class Solution {
public:
int numberOfSubmatrices(vector<vector<char>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<vector<int>>> s(m + 1, vector<vector<int>>(n + 1, vector<int>(2)));
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0]
+ (grid[i - 1][j - 1] == 'X' ? 1 : 0);
s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1]
+ (grid[i - 1][j - 1] == 'Y' ? 1 : 0);
if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) {
++ans;
}
}
}
return ans;
}
};
|
3,212
|
Count Submatrices With Equal Frequency of X and Y
|
Medium
|
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p>
<ul>
<li><code>grid[0][0]</code></li>
<li>an <strong>equal</strong> frequency of <code>'X'</code> and <code>'Y'</code>.</li>
<li><strong>at least</strong> one <code>'X'</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","Y","."],["Y",".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","X"],["X","Y"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has an equal frequency of <code>'X'</code> and <code>'Y'</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[".","."],[".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has at least one <code>'X'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[i].length <= 1000</code></li>
<li><code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>.</li>
</ul>
|
Array; Matrix; Prefix Sum
|
Go
|
func numberOfSubmatrices(grid [][]byte) (ans int) {
m, n := len(grid), len(grid[0])
s := make([][][]int, m+1)
for i := range s {
s[i] = make([][]int, n+1)
for j := range s[i] {
s[i][j] = make([]int, 2)
}
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
s[i][j][0] = s[i-1][j][0] + s[i][j-1][0] - s[i-1][j-1][0]
if grid[i-1][j-1] == 'X' {
s[i][j][0]++
}
s[i][j][1] = s[i-1][j][1] + s[i][j-1][1] - s[i-1][j-1][1]
if grid[i-1][j-1] == 'Y' {
s[i][j][1]++
}
if s[i][j][0] > 0 && s[i][j][0] == s[i][j][1] {
ans++
}
}
}
return
}
|
3,212
|
Count Submatrices With Equal Frequency of X and Y
|
Medium
|
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p>
<ul>
<li><code>grid[0][0]</code></li>
<li>an <strong>equal</strong> frequency of <code>'X'</code> and <code>'Y'</code>.</li>
<li><strong>at least</strong> one <code>'X'</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","Y","."],["Y",".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","X"],["X","Y"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has an equal frequency of <code>'X'</code> and <code>'Y'</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[".","."],[".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has at least one <code>'X'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[i].length <= 1000</code></li>
<li><code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>.</li>
</ul>
|
Array; Matrix; Prefix Sum
|
Java
|
class Solution {
public int numberOfSubmatrices(char[][] grid) {
int m = grid.length, n = grid[0].length;
int[][][] s = new int[m + 1][n + 1][2];
int ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0]
+ (grid[i - 1][j - 1] == 'X' ? 1 : 0);
s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1]
+ (grid[i - 1][j - 1] == 'Y' ? 1 : 0);
if (s[i][j][0] > 0 && s[i][j][0] == s[i][j][1]) {
++ans;
}
}
}
return ans;
}
}
|
3,212
|
Count Submatrices With Equal Frequency of X and Y
|
Medium
|
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p>
<ul>
<li><code>grid[0][0]</code></li>
<li>an <strong>equal</strong> frequency of <code>'X'</code> and <code>'Y'</code>.</li>
<li><strong>at least</strong> one <code>'X'</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","Y","."],["Y",".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","X"],["X","Y"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has an equal frequency of <code>'X'</code> and <code>'Y'</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[".","."],[".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has at least one <code>'X'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[i].length <= 1000</code></li>
<li><code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>.</li>
</ul>
|
Array; Matrix; Prefix Sum
|
Python
|
class Solution:
def numberOfSubmatrices(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
s = [[[0] * 2 for _ in range(n + 1)] for _ in range(m + 1)]
ans = 0
for i, row in enumerate(grid, 1):
for j, x in enumerate(row, 1):
s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0]
s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1]
if x != ".":
s[i][j][ord(x) & 1] += 1
if s[i][j][0] > 0 and s[i][j][0] == s[i][j][1]:
ans += 1
return ans
|
3,212
|
Count Submatrices With Equal Frequency of X and Y
|
Medium
|
<p>Given a 2D character matrix <code>grid</code>, where <code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>, return the number of <span data-keyword="submatrix">submatrices</span> that contain:</p>
<ul>
<li><code>grid[0][0]</code></li>
<li>an <strong>equal</strong> frequency of <code>'X'</code> and <code>'Y'</code>.</li>
<li><strong>at least</strong> one <code>'X'</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","Y","."],["Y",".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3212.Count%20Submatrices%20With%20Equal%20Frequency%20of%20X%20and%20Y/images/examplems.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 175px; height: 350px;" /></strong></p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [["X","X"],["X","Y"]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has an equal frequency of <code>'X'</code> and <code>'Y'</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[".","."],[".","."]]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>No submatrix has at least one <code>'X'</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length, grid[i].length <= 1000</code></li>
<li><code>grid[i][j]</code> is either <code>'X'</code>, <code>'Y'</code>, or <code>'.'</code>.</li>
</ul>
|
Array; Matrix; Prefix Sum
|
TypeScript
|
function numberOfSubmatrices(grid: string[][]): number {
const [m, n] = [grid.length, grid[0].length];
const s = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => [0, 0]));
let ans = 0;
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
s[i][j][0] =
s[i - 1][j][0] +
s[i][j - 1][0] -
s[i - 1][j - 1][0] +
(grid[i - 1][j - 1] === 'X' ? 1 : 0);
s[i][j][1] =
s[i - 1][j][1] +
s[i][j - 1][1] -
s[i - 1][j - 1][1] +
(grid[i - 1][j - 1] === 'Y' ? 1 : 0);
if (s[i][j][0] > 0 && s[i][j][0] === s[i][j][1]) {
++ans;
}
}
}
return ans;
}
|
3,213
|
Construct String with Minimum Cost
|
Hard
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words.length == costs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; String; Dynamic Programming; Suffix Array
|
C++
|
class Hashing {
private:
vector<long> p, h;
long mod;
public:
Hashing(const string& word, long base, long mod)
: p(word.size() + 1, 1)
, h(word.size() + 1, 0)
, mod(mod) {
for (int i = 1; i <= word.size(); ++i) {
p[i] = p[i - 1] * base % mod;
h[i] = (h[i - 1] * base + word[i - 1]) % mod;
}
}
long query(int l, int r) {
return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod;
}
};
class Solution {
public:
int minimumCost(string target, vector<string>& words, vector<int>& costs) {
const int base = 13331;
const int mod = 998244353;
const int inf = INT_MAX / 2;
int n = target.size();
Hashing hashing(target, base, mod);
vector<int> f(n + 1, inf);
f[0] = 0;
set<int> ss;
for (const string& w : words) {
ss.insert(w.size());
}
unordered_map<long, int> d;
for (int i = 0; i < words.size(); ++i) {
long x = 0;
for (char c : words[i]) {
x = (x * base + c) % mod;
}
d[x] = d.find(x) == d.end() ? costs[i] : min(d[x], costs[i]);
}
for (int i = 1; i <= n; ++i) {
for (int j : ss) {
if (j > i) {
break;
}
long x = hashing.query(i - j + 1, i);
if (d.contains(x)) {
f[i] = min(f[i], f[i - j] + d[x]);
}
}
}
return f[n] >= inf ? -1 : f[n];
}
};
|
3,213
|
Construct String with Minimum Cost
|
Hard
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words.length == costs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; String; Dynamic Programming; Suffix Array
|
Go
|
type Hashing struct {
p []int64
h []int64
mod int64
}
func NewHashing(word string, base, 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])) % mod
}
return &Hashing{p, h, mod}
}
func (hs *Hashing) query(l, r int) int64 {
return (hs.h[r] - hs.h[l-1]*hs.p[r-l+1]%hs.mod + hs.mod) % hs.mod
}
func minimumCost(target string, words []string, costs []int) int {
const base = 13331
const mod = 998244353
const inf = math.MaxInt32 / 2
n := len(target)
hashing := NewHashing(target, base, mod)
f := make([]int, n+1)
for i := range f {
f[i] = inf
}
f[0] = 0
ss := make(map[int]struct{})
for _, w := range words {
ss[len(w)] = struct{}{}
}
lengths := make([]int, 0, len(ss))
for length := range ss {
lengths = append(lengths, length)
}
sort.Ints(lengths)
d := make(map[int64]int)
for i, w := range words {
var x int64
for _, c := range w {
x = (x*base + int64(c)) % mod
}
if existingCost, exists := d[x]; exists {
if costs[i] < existingCost {
d[x] = costs[i]
}
} else {
d[x] = costs[i]
}
}
for i := 1; i <= n; i++ {
for _, j := range lengths {
if j > i {
break
}
x := hashing.query(i-j+1, i)
if cost, ok := d[x]; ok {
f[i] = min(f[i], f[i-j]+cost)
}
}
}
if f[n] >= inf {
return -1
}
return f[n]
}
|
3,213
|
Construct String with Minimum Cost
|
Hard
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words.length == costs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; String; Dynamic Programming; Suffix Array
|
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)) % 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 minimumCost(String target, String[] words, int[] costs) {
final int base = 13331;
final int mod = 998244353;
final int inf = Integer.MAX_VALUE / 2;
int n = target.length();
Hashing hashing = new Hashing(target, base, mod);
int[] f = new int[n + 1];
Arrays.fill(f, inf);
f[0] = 0;
TreeSet<Integer> ss = new TreeSet<>();
for (String w : words) {
ss.add(w.length());
}
Map<Long, Integer> d = new HashMap<>();
for (int i = 0; i < words.length; i++) {
long x = 0;
for (char c : words[i].toCharArray()) {
x = (x * base + c) % mod;
}
d.merge(x, costs[i], Integer::min);
}
for (int i = 1; i <= n; i++) {
for (int j : ss) {
if (j > i) {
break;
}
long x = hashing.query(i - j + 1, i);
f[i] = Math.min(f[i], f[i - j] + d.getOrDefault(x, inf));
}
}
return f[n] >= inf ? -1 : f[n];
}
}
|
3,213
|
Construct String with Minimum Cost
|
Hard
|
<p>You are given a string <code>target</code>, an array of strings <code>words</code>, and an integer array <code>costs</code>, both arrays of the same length.</p>
<p>Imagine an empty string <code>s</code>.</p>
<p>You can perform the following operation any number of times (including <strong>zero</strong>):</p>
<ul>
<li>Choose an index <code>i</code> in the range <code>[0, words.length - 1]</code>.</li>
<li>Append <code>words[i]</code> to <code>s</code>.</li>
<li>The cost of operation is <code>costs[i]</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> cost to make <code>s</code> equal to <code>target</code>. If it's not possible, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">7</span></p>
<p><strong>Explanation:</strong></p>
<p>The minimum cost can be achieved by performing the following operations:</p>
<ul>
<li>Select index 1 and append <code>"abc"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abc"</code>.</li>
<li>Select index 2 and append <code>"d"</code> to <code>s</code> at a cost of 1, resulting in <code>s = "abcd"</code>.</li>
<li>Select index 4 and append <code>"ef"</code> to <code>s</code> at a cost of 5, resulting in <code>s = "abcdef"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>It is impossible to make <code>s</code> equal to <code>target</code>, so we return -1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words.length == costs.length <= 5 * 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= target.length</code></li>
<li>The total sum of <code>words[i].length</code> is less than or equal to <code>5 * 10<sup>4</sup></code>.</li>
<li><code>target</code> and <code>words[i]</code> consist only of lowercase English letters.</li>
<li><code>1 <= costs[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; String; Dynamic Programming; Suffix Array
|
Python
|
class Solution:
def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
base, mod = 13331, 998244353
n = len(target)
h = [0] * (n + 1)
p = [1] * (n + 1)
for i, c in enumerate(target, 1):
h[i] = (h[i - 1] * base + ord(c)) % mod
p[i] = (p[i - 1] * base) % mod
f = [0] + [inf] * n
ss = sorted(set(map(len, words)))
d = defaultdict(lambda: inf)
min = lambda a, b: a if a < b else b
for w, c in zip(words, costs):
x = 0
for ch in w:
x = (x * base + ord(ch)) % mod
d[x] = min(d[x], c)
for i in range(1, n + 1):
for j in ss:
if j > i:
break
x = (h[i] - h[i - j] * p[j]) % mod
f[i] = min(f[i], f[i - j] + d[x])
return f[n] if f[n] < inf else -1
|
3,214
|
Year on Year Growth Rate
|
Hard
|
<p>Table: <code>user_transactions</code></p>
<pre>
+------------------+----------+
| Column Name | Type |
+------------------+----------+
| transaction_id | integer |
| product_id | integer |
| spend | decimal |
| transaction_date | datetime |
+------------------+----------+
The transaction_id column uniquely identifies each row in this table.
Each row of this table contains the transaction ID, product ID, the spend amount, and the transaction date.
</pre>
<p>Write a solution to calculate the <strong>year-on-year growth rate</strong> for the total spend <strong>for each product</strong>.</p>
<p>The result table should include the following columns:</p>
<ul>
<li><code>year</code>: The year of the transaction.</li>
<li><code>product_id</code>: The ID of the product.</li>
<li><code>curr_year_spend</code>: The total spend for the current year.</li>
<li><code>prev_year_spend</code>: The total spend for the previous year.</li>
<li><code>yoy_rate</code>: The year-on-year growth rate percentage, rounded to <code>2</code> decimal places.</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>product_id</code>,<code>year</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>user_transactions</code> table:</p>
<pre class="example-io">
+----------------+------------+---------+---------------------+
| transaction_id | product_id | spend | transaction_date |
+----------------+------------+---------+---------------------+
| 1341 | 123424 | 1500.60 | 2019-12-31 12:00:00 |
| 1423 | 123424 | 1000.20 | 2020-12-31 12:00:00 |
| 1623 | 123424 | 1246.44 | 2021-12-31 12:00:00 |
| 1322 | 123424 | 2145.32 | 2022-12-31 12:00:00 |
+----------------+------------+---------+---------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------+------------+----------------+----------------+----------+
| year | product_id | curr_year_spend| prev_year_spend| yoy_rate |
+------+------------+----------------+----------------+----------+
| 2019 | 123424 | 1500.60 | NULL | NULL |
| 2020 | 123424 | 1000.20 | 1500.60 | -33.35 |
| 2021 | 123424 | 1246.44 | 1000.20 | 24.62 |
| 2022 | 123424 | 2145.32 | 1246.44 | 72.12 |
+------+------------+----------------+----------------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For product ID 123424:
<ul>
<li>In 2019:
<ul>
<li>Current year's spend is 1500.60</li>
<li>No previous year's spend recorded</li>
<li>YoY growth rate: NULL</li>
</ul>
</li>
<li>In 2020:
<ul>
<li>Current year's spend is 1000.20</li>
<li>Previous year's spend is 1500.60</li>
<li>YoY growth rate: ((1000.20 - 1500.60) / 1500.60) * 100 = -33.35%</li>
</ul>
</li>
<li>In 2021:
<ul>
<li>Current year's spend is 1246.44</li>
<li>Previous year's spend is 1000.20</li>
<li>YoY growth rate: ((1246.44 - 1000.20) / 1000.20) * 100 = 24.62%</li>
</ul>
</li>
<li>In 2022:
<ul>
<li>Current year's spend is 2145.32</li>
<li>Previous year's spend is 1246.44</li>
<li>YoY growth rate: ((2145.32 - 1246.44) / 1246.44) * 100 = 72.12%</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong> Output table is ordered by <code>product_id</code> and <code>year</code> in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT product_id, YEAR(transaction_date) year, SUM(spend) curr_year_spend
FROM user_transactions
GROUP BY 1, 2
),
S AS (
SELECT t1.year, t1.product_id, t1.curr_year_spend, t2.curr_year_spend prev_year_spend
FROM
T t1
LEFT JOIN T t2 ON t1.product_id = t2.product_id AND t1.year = t2.year + 1
)
SELECT
*,
ROUND((curr_year_spend - prev_year_spend) / prev_year_spend * 100, 2) yoy_rate
FROM S
ORDER BY 2, 1;
|
3,215
|
Count Triplets with Even XOR Set Bits II
|
Medium
|
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Consider these four triplets:</p>
<ul>
<li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
<li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a[i], b[i], c[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
C++
|
class Solution {
public:
long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
int cnt1[2]{};
int cnt2[2]{};
int cnt3[2]{};
for (int x : a) {
++cnt1[__builtin_popcount(x) & 1];
}
for (int x : b) {
++cnt2[__builtin_popcount(x) & 1];
}
for (int x : c) {
++cnt3[__builtin_popcount(x) & 1];
}
long long ans = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
if ((i + j + k) % 2 == 0) {
ans += 1LL * cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
};
|
3,215
|
Count Triplets with Even XOR Set Bits II
|
Medium
|
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Consider these four triplets:</p>
<ul>
<li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
<li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a[i], b[i], c[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Go
|
func tripletCount(a []int, b []int, c []int) (ans int64) {
cnt1 := [2]int{}
cnt2 := [2]int{}
cnt3 := [2]int{}
for _, x := range a {
cnt1[bits.OnesCount(uint(x))%2]++
}
for _, x := range b {
cnt2[bits.OnesCount(uint(x))%2]++
}
for _, x := range c {
cnt3[bits.OnesCount(uint(x))%2]++
}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
for k := 0; k < 2; k++ {
if (i+j+k)%2 == 0 {
ans += int64(cnt1[i] * cnt2[j] * cnt3[k])
}
}
}
}
return
}
|
3,215
|
Count Triplets with Even XOR Set Bits II
|
Medium
|
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Consider these four triplets:</p>
<ul>
<li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
<li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a[i], b[i], c[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Java
|
class Solution {
public long tripletCount(int[] a, int[] b, int[] c) {
int[] cnt1 = new int[2];
int[] cnt2 = new int[2];
int[] cnt3 = new int[2];
for (int x : a) {
++cnt1[Integer.bitCount(x) & 1];
}
for (int x : b) {
++cnt2[Integer.bitCount(x) & 1];
}
for (int x : c) {
++cnt3[Integer.bitCount(x) & 1];
}
long ans = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
if ((i + j + k) % 2 == 0) {
ans += 1L * cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
}
|
3,215
|
Count Triplets with Even XOR Set Bits II
|
Medium
|
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Consider these four triplets:</p>
<ul>
<li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
<li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a[i], b[i], c[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
Python
|
class Solution:
def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int:
cnt1 = Counter(x.bit_count() & 1 for x in a)
cnt2 = Counter(x.bit_count() & 1 for x in b)
cnt3 = Counter(x.bit_count() & 1 for x in c)
ans = 0
for i in range(2):
for j in range(2):
for k in range(2):
if (i + j + k) & 1 ^ 1:
ans += cnt1[i] * cnt2[j] * cnt3[k]
return ans
|
3,215
|
Count Triplets with Even XOR Set Bits II
|
Medium
|
Given three integer arrays <code>a</code>, <code>b</code>, and <code>c</code>, return the number of triplets <code>(a[i], b[j], c[k])</code>, such that the bitwise <code>XOR</code> between the elements of each triplet has an <strong>even</strong> number of <span data-keyword="set-bit">set bits</span>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1], b = [2], c = [3]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>The only triplet is <code>(a[0], b[0], c[0])</code> and their <code>XOR</code> is: <code>1 XOR 2 XOR 3 = 00<sub>2</sub></code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">a = [1,1], b = [2,3], c = [1,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<p>Consider these four triplets:</p>
<ul>
<li><code>(a[0], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[1], b[1], c[0])</code>: <code>1 XOR 3 XOR 1 = 011<sub>2</sub></code></li>
<li><code>(a[0], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
<li><code>(a[1], b[0], c[1])</code>: <code>1 XOR 2 XOR 5 = 110<sub>2</sub></code></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= a.length, b.length, c.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a[i], b[i], c[i] <= 10<sup>9</sup></code></li>
</ul>
|
Bit Manipulation; Array
|
TypeScript
|
function tripletCount(a: number[], b: number[], c: number[]): number {
const cnt1: [number, number] = [0, 0];
const cnt2: [number, number] = [0, 0];
const cnt3: [number, number] = [0, 0];
for (const x of a) {
++cnt1[bitCount(x) & 1];
}
for (const x of b) {
++cnt2[bitCount(x) & 1];
}
for (const x of c) {
++cnt3[bitCount(x) & 1];
}
let ans = 0;
for (let i = 0; i < 2; ++i) {
for (let j = 0; j < 2; ++j) {
for (let k = 0; k < 2; ++k) {
if ((i + j + k) % 2 === 0) {
ans += cnt1[i] * cnt2[j] * cnt3[k];
}
}
}
}
return ans;
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
3,216
|
Lexicographically Smallest String After a Swap
|
Easy
|
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p>
<p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "45320"</span></p>
<p><strong>Output:</strong> <span class="example-io">"43520"</span></p>
<p><strong>Explanation: </strong></p>
<p><code>s[1] == '5'</code> and <code>s[2] == '3'</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "001"</span></p>
<p><strong>Output:</strong> <span class="example-io">"001"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of digits.</li>
</ul>
|
Greedy; String
|
C++
|
class Solution {
public:
string getSmallestString(string s) {
int n = s.length();
for (int i = 1; i < n; ++i) {
char a = s[i - 1], b = s[i];
if (a > b && a % 2 == b % 2) {
s[i - 1] = b;
s[i] = a;
break;
}
}
return s;
}
};
|
3,216
|
Lexicographically Smallest String After a Swap
|
Easy
|
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p>
<p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "45320"</span></p>
<p><strong>Output:</strong> <span class="example-io">"43520"</span></p>
<p><strong>Explanation: </strong></p>
<p><code>s[1] == '5'</code> and <code>s[2] == '3'</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "001"</span></p>
<p><strong>Output:</strong> <span class="example-io">"001"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of digits.</li>
</ul>
|
Greedy; String
|
Go
|
func getSmallestString(s string) string {
cs := []byte(s)
n := len(cs)
for i := 1; i < n; i++ {
a, b := cs[i-1], cs[i]
if a > b && a%2 == b%2 {
cs[i-1], cs[i] = b, a
return string(cs)
}
}
return s
}
|
3,216
|
Lexicographically Smallest String After a Swap
|
Easy
|
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p>
<p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "45320"</span></p>
<p><strong>Output:</strong> <span class="example-io">"43520"</span></p>
<p><strong>Explanation: </strong></p>
<p><code>s[1] == '5'</code> and <code>s[2] == '3'</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "001"</span></p>
<p><strong>Output:</strong> <span class="example-io">"001"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of digits.</li>
</ul>
|
Greedy; String
|
Java
|
class Solution {
public String getSmallestString(String s) {
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 1; i < n; ++i) {
char a = cs[i - 1], b = cs[i];
if (a > b && a % 2 == b % 2) {
cs[i] = a;
cs[i - 1] = b;
return new String(cs);
}
}
return s;
}
}
|
3,216
|
Lexicographically Smallest String After a Swap
|
Easy
|
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p>
<p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "45320"</span></p>
<p><strong>Output:</strong> <span class="example-io">"43520"</span></p>
<p><strong>Explanation: </strong></p>
<p><code>s[1] == '5'</code> and <code>s[2] == '3'</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "001"</span></p>
<p><strong>Output:</strong> <span class="example-io">"001"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of digits.</li>
</ul>
|
Greedy; String
|
Python
|
class Solution:
def getSmallestString(self, s: str) -> str:
for i, (a, b) in enumerate(pairwise(map(ord, s))):
if (a + b) % 2 == 0 and a > b:
return s[:i] + s[i + 1] + s[i] + s[i + 2 :]
return s
|
3,216
|
Lexicographically Smallest String After a Swap
|
Easy
|
<p>Given a string <code>s</code> containing only digits, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest string</span> that can be obtained after swapping <strong>adjacent</strong> digits in <code>s</code> with the same <strong>parity</strong> at most <strong>once</strong>.</p>
<p>Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "45320"</span></p>
<p><strong>Output:</strong> <span class="example-io">"43520"</span></p>
<p><strong>Explanation: </strong></p>
<p><code>s[1] == '5'</code> and <code>s[2] == '3'</code> both have the same parity, and swapping them results in the lexicographically smallest string.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "001"</span></p>
<p><strong>Output:</strong> <span class="example-io">"001"</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no need to perform a swap because <code>s</code> is already the lexicographically smallest.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= s.length <= 100</code></li>
<li><code>s</code> consists only of digits.</li>
</ul>
|
Greedy; String
|
TypeScript
|
function getSmallestString(s: string): string {
const n = s.length;
const cs: string[] = s.split('');
for (let i = 1; i < n; ++i) {
const a = cs[i - 1];
const b = cs[i];
if (a > b && +a % 2 === +b % 2) {
cs[i - 1] = b;
cs[i] = a;
return cs.join('');
}
}
return s;
}
|
3,217
|
Delete Nodes From Linked List Present in Array
|
Medium
|
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], head = [1,2,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,5]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p>
<p>Remove the nodes with values 1, 2, and 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p>
<p>Remove the nodes with value 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p>
<p>No node has value 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li>All elements in <code>nums</code> are unique.</li>
<li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Linked List
|
C++
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* modifiedList(vector<int>& nums, ListNode* head) {
unordered_set<int> s(nums.begin(), nums.end());
ListNode* dummy = new ListNode(0, head);
for (ListNode* pre = dummy; pre->next;) {
if (s.count(pre->next->val)) {
pre->next = pre->next->next;
} else {
pre = pre->next;
}
}
return dummy->next;
}
};
|
3,217
|
Delete Nodes From Linked List Present in Array
|
Medium
|
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], head = [1,2,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,5]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p>
<p>Remove the nodes with values 1, 2, and 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p>
<p>Remove the nodes with value 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p>
<p>No node has value 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li>All elements in <code>nums</code> are unique.</li>
<li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Linked List
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func modifiedList(nums []int, head *ListNode) *ListNode {
s := map[int]bool{}
for _, x := range nums {
s[x] = true
}
dummy := &ListNode{Next: head}
for pre := dummy; pre.Next != nil; {
if s[pre.Next.Val] {
pre.Next = pre.Next.Next
} else {
pre = pre.Next
}
}
return dummy.Next
}
|
3,217
|
Delete Nodes From Linked List Present in Array
|
Medium
|
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], head = [1,2,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,5]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p>
<p>Remove the nodes with values 1, 2, and 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p>
<p>Remove the nodes with value 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p>
<p>No node has value 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li>All elements in <code>nums</code> are unique.</li>
<li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Linked List
|
Java
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode modifiedList(int[] nums, ListNode head) {
Set<Integer> s = new HashSet<>();
for (int x : nums) {
s.add(x);
}
ListNode dummy = new ListNode(0, head);
for (ListNode pre = dummy; pre.next != null;) {
if (s.contains(pre.next.val)) {
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
return dummy.next;
}
}
|
3,217
|
Delete Nodes From Linked List Present in Array
|
Medium
|
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], head = [1,2,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,5]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p>
<p>Remove the nodes with values 1, 2, and 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p>
<p>Remove the nodes with value 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p>
<p>No node has value 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li>All elements in <code>nums</code> are unique.</li>
<li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Linked List
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def modifiedList(
self, nums: List[int], head: Optional[ListNode]
) -> Optional[ListNode]:
s = set(nums)
pre = dummy = ListNode(next=head)
while pre.next:
if pre.next.val in s:
pre.next = pre.next.next
else:
pre = pre.next
return dummy.next
|
3,217
|
Delete Nodes From Linked List Present in Array
|
Medium
|
<p>You are given an array of integers <code>nums</code> and the <code>head</code> of a linked list. Return the <code>head</code> of the modified linked list after <strong>removing</strong> all nodes from the linked list that have a value that exists in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], head = [1,2,3,4,5]</span></p>
<p><strong>Output:</strong> <span class="example-io">[4,5]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample0.png" style="width: 400px; height: 66px;" /></strong></p>
<p>Remove the nodes with values 1, 2, and 3.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1], head = [1,2,1,2,1,2]</span></p>
<p><strong>Output:</strong> <span class="example-io">[2,2,2]</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample1.png" style="height: 62px; width: 450px;" /></p>
<p>Remove the nodes with value 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [5], head = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2,3,4]</span></p>
<p><strong>Explanation:</strong></p>
<p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3217.Delete%20Nodes%20From%20Linked%20List%20Present%20in%20Array/images/linkedlistexample2.png" style="width: 400px; height: 83px;" /></strong></p>
<p>No node has value 5.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li>All elements in <code>nums</code> are unique.</li>
<li>The number of nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
<li><code>1 <= Node.val <= 10<sup>5</sup></code></li>
<li>The input is generated such that there is at least one node in the linked list that has a value not present in <code>nums</code>.</li>
</ul>
|
Array; Hash Table; Linked List
|
TypeScript
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function modifiedList(nums: number[], head: ListNode | null): ListNode | null {
const s: Set<number> = new Set(nums);
const dummy = new ListNode(0, head);
for (let pre = dummy; pre.next; ) {
if (s.has(pre.next.val)) {
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
return dummy.next;
}
|
3,218
|
Minimum Cost for Cutting Cake I
|
Medium
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 20</code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Dynamic Programming; Sorting
|
C++
|
class Solution {
public:
int minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) {
sort(horizontalCut.rbegin(), horizontalCut.rend());
sort(verticalCut.rbegin(), verticalCut.rend());
int ans = 0;
int i = 0, j = 0;
int h = 1, v = 1;
while (i < m - 1 || j < n - 1) {
if (j == n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) {
ans += horizontalCut[i++] * v;
h++;
} else {
ans += verticalCut[j++] * h;
v++;
}
}
return ans;
}
};
|
3,218
|
Minimum Cost for Cutting Cake I
|
Medium
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 20</code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Dynamic Programming; Sorting
|
Go
|
func minimumCost(m int, n int, horizontalCut []int, verticalCut []int) (ans int) {
sort.Sort(sort.Reverse(sort.IntSlice(horizontalCut)))
sort.Sort(sort.Reverse(sort.IntSlice(verticalCut)))
i, j := 0, 0
h, v := 1, 1
for i < m-1 || j < n-1 {
if j == n-1 || (i < m-1 && horizontalCut[i] > verticalCut[j]) {
ans += horizontalCut[i] * v
h++
i++
} else {
ans += verticalCut[j] * h
v++
j++
}
}
return
}
|
3,218
|
Minimum Cost for Cutting Cake I
|
Medium
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 20</code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Dynamic Programming; Sorting
|
Java
|
class Solution {
public int minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) {
Arrays.sort(horizontalCut);
Arrays.sort(verticalCut);
int ans = 0;
int i = m - 2, j = n - 2;
int h = 1, v = 1;
while (i >= 0 || j >= 0) {
if (j < 0 || (i >= 0 && horizontalCut[i] > verticalCut[j])) {
ans += horizontalCut[i--] * v;
++h;
} else {
ans += verticalCut[j--] * h;
++v;
}
}
return ans;
}
}
|
3,218
|
Minimum Cost for Cutting Cake I
|
Medium
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 20</code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Dynamic Programming; Sorting
|
Python
|
class Solution:
def minimumCost(
self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]
) -> int:
horizontalCut.sort(reverse=True)
verticalCut.sort(reverse=True)
ans = i = j = 0
h = v = 1
while i < m - 1 or j < n - 1:
if j == n - 1 or (i < m - 1 and horizontalCut[i] > verticalCut[j]):
ans += horizontalCut[i] * v
h, i = h + 1, i + 1
else:
ans += verticalCut[j] * h
v, j = v + 1, j + 1
return ans
|
3,218
|
Minimum Cost for Cutting Cake I
|
Medium
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3218.Minimum%20Cost%20for%20Cutting%20Cake%20I/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 20</code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Dynamic Programming; Sorting
|
TypeScript
|
function minimumCost(m: number, n: number, horizontalCut: number[], verticalCut: number[]): number {
horizontalCut.sort((a, b) => b - a);
verticalCut.sort((a, b) => b - a);
let ans = 0;
let [i, j] = [0, 0];
let [h, v] = [1, 1];
while (i < m - 1 || j < n - 1) {
if (j === n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) {
ans += horizontalCut[i] * v;
h++;
i++;
} else {
ans += verticalCut[j] * h;
v++;
j++;
}
}
return ans;
}
|
3,219
|
Minimum Cost for Cutting Cake II
|
Hard
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 10<sup>5</sup></code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
long long minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) {
sort(horizontalCut.rbegin(), horizontalCut.rend());
sort(verticalCut.rbegin(), verticalCut.rend());
long long ans = 0;
int i = 0, j = 0;
int h = 1, v = 1;
while (i < m - 1 || j < n - 1) {
if (j == n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) {
ans += 1LL * horizontalCut[i++] * v;
h++;
} else {
ans += 1LL * verticalCut[j++] * h;
v++;
}
}
return ans;
}
};
|
3,219
|
Minimum Cost for Cutting Cake II
|
Hard
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 10<sup>5</sup></code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func minimumCost(m int, n int, horizontalCut []int, verticalCut []int) (ans int64) {
sort.Sort(sort.Reverse(sort.IntSlice(horizontalCut)))
sort.Sort(sort.Reverse(sort.IntSlice(verticalCut)))
i, j := 0, 0
h, v := 1, 1
for i < m-1 || j < n-1 {
if j == n-1 || (i < m-1 && horizontalCut[i] > verticalCut[j]) {
ans += int64(horizontalCut[i] * v)
h++
i++
} else {
ans += int64(verticalCut[j] * h)
v++
j++
}
}
return
}
|
3,219
|
Minimum Cost for Cutting Cake II
|
Hard
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 10<sup>5</sup></code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public long minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) {
Arrays.sort(horizontalCut);
Arrays.sort(verticalCut);
long ans = 0;
int i = m - 2, j = n - 2;
int h = 1, v = 1;
while (i >= 0 || j >= 0) {
if (j < 0 || (i >= 0 && horizontalCut[i] > verticalCut[j])) {
ans += 1L * horizontalCut[i--] * v;
++h;
} else {
ans += 1L * verticalCut[j--] * h;
++v;
}
}
return ans;
}
}
|
3,219
|
Minimum Cost for Cutting Cake II
|
Hard
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 10<sup>5</sup></code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def minimumCost(
self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]
) -> int:
horizontalCut.sort(reverse=True)
verticalCut.sort(reverse=True)
ans = i = j = 0
h = v = 1
while i < m - 1 or j < n - 1:
if j == n - 1 or (i < m - 1 and horizontalCut[i] > verticalCut[j]):
ans += horizontalCut[i] * v
h, i = h + 1, i + 1
else:
ans += verticalCut[j] * h
v, j = v + 1, j + 1
return ans
|
3,219
|
Minimum Cost for Cutting Cake II
|
Hard
|
<p>There is an <code>m x n</code> cake that needs to be cut into <code>1 x 1</code> pieces.</p>
<p>You are given integers <code>m</code>, <code>n</code>, and two arrays:</p>
<ul>
<li><code>horizontalCut</code> of size <code>m - 1</code>, where <code>horizontalCut[i]</code> represents the cost to cut along the horizontal line <code>i</code>.</li>
<li><code>verticalCut</code> of size <code>n - 1</code>, where <code>verticalCut[j]</code> represents the cost to cut along the vertical line <code>j</code>.</li>
</ul>
<p>In one operation, you can choose any piece of cake that is not yet a <code>1 x 1</code> square and perform one of the following cuts:</p>
<ol>
<li>Cut along a horizontal line <code>i</code> at a cost of <code>horizontalCut[i]</code>.</li>
<li>Cut along a vertical line <code>j</code> at a cost of <code>verticalCut[j]</code>.</li>
</ol>
<p>After the cut, the piece of cake is divided into two distinct pieces.</p>
<p>The cost of a cut depends only on the initial cost of the line and does not change.</p>
<p>Return the <strong>minimum</strong> total cost to cut the entire cake into <code>1 x 1</code> pieces.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]</span></p>
<p><strong>Output:</strong> <span class="example-io">13</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3219.Minimum%20Cost%20for%20Cutting%20Cake%20II/images/ezgifcom-animated-gif-maker-1.gif" style="width: 280px; height: 320px;" /></p>
<ul>
<li>Perform a cut on the vertical line 0 with cost 5, current total cost is 5.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 0 on <code>3 x 1</code> subgrid with cost 1.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
<li>Perform a cut on the horizontal line 1 on <code>2 x 1</code> subgrid with cost 3.</li>
</ul>
<p>The total cost is <code>5 + 1 + 1 + 3 + 3 = 13</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">m = 2, n = 2, horizontalCut = [7], verticalCut = [4]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Perform a cut on the horizontal line 0 with cost 7.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
<li>Perform a cut on the vertical line 0 on <code>1 x 2</code> subgrid with cost 4.</li>
</ul>
<p>The total cost is <code>7 + 4 + 4 = 15</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= m, n <= 10<sup>5</sup></code></li>
<li><code>horizontalCut.length == m - 1</code></li>
<li><code>verticalCut.length == n - 1</code></li>
<li><code>1 <= horizontalCut[i], verticalCut[i] <= 10<sup>3</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function minimumCost(m: number, n: number, horizontalCut: number[], verticalCut: number[]): number {
horizontalCut.sort((a, b) => b - a);
verticalCut.sort((a, b) => b - a);
let ans = 0;
let [i, j] = [0, 0];
let [h, v] = [1, 1];
while (i < m - 1 || j < n - 1) {
if (j === n - 1 || (i < m - 1 && horizontalCut[i] > verticalCut[j])) {
ans += horizontalCut[i] * v;
h++;
i++;
} else {
ans += verticalCut[j] * h;
v++;
j++;
}
}
return ans;
}
|
3,220
|
Odd and Even Transactions
|
Medium
|
<p>Table: <code>transactions</code></p>
<pre>
+------------------+------+
| Column Name | Type |
+------------------+------+
| transaction_id | int |
| amount | int |
| transaction_date | date |
+------------------+------+
The transactions_id column uniquely identifies each row in this table.
Each row of this table contains the transaction id, amount and transaction date.
</pre>
<p>Write a solution to find the <strong>sum of amounts</strong> for <strong>odd</strong> and <strong>even</strong> transactions for each day. If there are no odd or even transactions for a specific date, display as <code>0</code>.</p>
<p>Return <em>the result table ordered by</em> <code>transaction_date</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>transactions</code> table:</p>
<pre class="example-io">
+----------------+--------+------------------+
| transaction_id | amount | transaction_date |
+----------------+--------+------------------+
| 1 | 150 | 2024-07-01 |
| 2 | 200 | 2024-07-01 |
| 3 | 75 | 2024-07-01 |
| 4 | 300 | 2024-07-02 |
| 5 | 50 | 2024-07-02 |
| 6 | 120 | 2024-07-03 |
+----------------+--------+------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------------+---------+----------+
| transaction_date | odd_sum | even_sum |
+------------------+---------+----------+
| 2024-07-01 | 75 | 350 |
| 2024-07-02 | 0 | 350 |
| 2024-07-03 | 0 | 120 |
+------------------+---------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For transaction dates:
<ul>
<li>2024-07-01:
<ul>
<li>Sum of amounts for odd transactions: 75</li>
<li>Sum of amounts for even transactions: 150 + 200 = 350</li>
</ul>
</li>
<li>2024-07-02:
<ul>
<li>Sum of amounts for odd transactions: 0</li>
<li>Sum of amounts for even transactions: 300 + 50 = 350</li>
</ul>
</li>
<li>2024-07-03:
<ul>
<li>Sum of amounts for odd transactions: 0</li>
<li>Sum of amounts for even transactions: 120</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong> The output table is ordered by <code>transaction_date</code> in ascending order.</p>
</div>
|
Database
|
Python
|
import pandas as pd
def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame:
transactions["odd_sum"] = transactions["amount"].where(
transactions["amount"] % 2 == 1, 0
)
transactions["even_sum"] = transactions["amount"].where(
transactions["amount"] % 2 == 0, 0
)
result = (
transactions.groupby("transaction_date")
.agg(odd_sum=("odd_sum", "sum"), even_sum=("even_sum", "sum"))
.reset_index()
)
result = result.sort_values("transaction_date")
return result
|
3,220
|
Odd and Even Transactions
|
Medium
|
<p>Table: <code>transactions</code></p>
<pre>
+------------------+------+
| Column Name | Type |
+------------------+------+
| transaction_id | int |
| amount | int |
| transaction_date | date |
+------------------+------+
The transactions_id column uniquely identifies each row in this table.
Each row of this table contains the transaction id, amount and transaction date.
</pre>
<p>Write a solution to find the <strong>sum of amounts</strong> for <strong>odd</strong> and <strong>even</strong> transactions for each day. If there are no odd or even transactions for a specific date, display as <code>0</code>.</p>
<p>Return <em>the result table ordered by</em> <code>transaction_date</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p><code>transactions</code> table:</p>
<pre class="example-io">
+----------------+--------+------------------+
| transaction_id | amount | transaction_date |
+----------------+--------+------------------+
| 1 | 150 | 2024-07-01 |
| 2 | 200 | 2024-07-01 |
| 3 | 75 | 2024-07-01 |
| 4 | 300 | 2024-07-02 |
| 5 | 50 | 2024-07-02 |
| 6 | 120 | 2024-07-03 |
+----------------+--------+------------------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+------------------+---------+----------+
| transaction_date | odd_sum | even_sum |
+------------------+---------+----------+
| 2024-07-01 | 75 | 350 |
| 2024-07-02 | 0 | 350 |
| 2024-07-03 | 0 | 120 |
+------------------+---------+----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>For transaction dates:
<ul>
<li>2024-07-01:
<ul>
<li>Sum of amounts for odd transactions: 75</li>
<li>Sum of amounts for even transactions: 150 + 200 = 350</li>
</ul>
</li>
<li>2024-07-02:
<ul>
<li>Sum of amounts for odd transactions: 0</li>
<li>Sum of amounts for even transactions: 300 + 50 = 350</li>
</ul>
</li>
<li>2024-07-03:
<ul>
<li>Sum of amounts for odd transactions: 0</li>
<li>Sum of amounts for even transactions: 120</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong> The output table is ordered by <code>transaction_date</code> in ascending order.</p>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
SELECT
transaction_date,
SUM(IF(amount % 2 = 1, amount, 0)) AS odd_sum,
SUM(IF(amount % 2 = 0, amount, 0)) AS even_sum
FROM transactions
GROUP BY 1
ORDER BY 1;
|
3,221
|
Maximum Array Hopping Score II
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<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>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
C++
|
class Solution {
public:
long long maxScore(vector<int>& nums) {
vector<int> stk;
for (int i = 0; i < nums.size(); ++i) {
while (stk.size() && nums[stk.back()] <= nums[i]) {
stk.pop_back();
}
stk.push_back(i);
}
long long ans = 0, i = 0;
for (int j : stk) {
ans += (j - i) * nums[j];
i = j;
}
return ans;
}
};
|
3,221
|
Maximum Array Hopping Score II
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<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>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Go
|
func maxScore(nums []int) (ans int64) {
stk := []int{}
for i, x := range nums {
for len(stk) > 0 && nums[stk[len(stk)-1]] <= x {
stk = stk[:len(stk)-1]
}
stk = append(stk, i)
}
i := 0
for _, j := range stk {
ans += int64((j - i) * nums[j])
i = j
}
return
}
|
3,221
|
Maximum Array Hopping Score II
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<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>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Java
|
class Solution {
public long maxScore(int[] nums) {
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0; i < nums.length; ++i) {
while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) {
stk.pop();
}
stk.push(i);
}
long ans = 0, i = 0;
while (!stk.isEmpty()) {
int j = stk.pollLast();
ans += (j - i) * nums[j];
i = j;
}
return ans;
}
}
|
3,221
|
Maximum Array Hopping Score II
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<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>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
Python
|
class Solution:
def maxScore(self, nums: List[int]) -> int:
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] <= x:
stk.pop()
stk.append(i)
ans = i = 0
for j in stk:
ans += nums[j] * (j - i)
i = j
return ans
|
3,221
|
Maximum Array Hopping Score II
|
Medium
|
<p>Given an array <code>nums</code>, you have to get the <strong>maximum</strong> score starting from index 0 and <strong>hopping</strong> until you reach the last element of the array.</p>
<p>In each <strong>hop</strong>, you can jump from index <code>i</code> to an index <code>j > i</code>, and you get a <strong>score</strong> of <code>(j - i) * nums[j]</code>.</p>
<p>Return the <em>maximum score</em> you can get.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,5,8]</span></p>
<p><strong>Output:</strong> <span class="example-io">16</span></p>
<p><strong>Explanation:</strong></p>
<p>There are two possible ways to reach the last element:</p>
<ul>
<li><code>0 -> 1 -> 2</code> with a score of <code>(1 - 0) * 5 + (2 - 1) * 8 = 13</code>.</li>
<li><code>0 -> 2</code> with a score of <code>(2 - 0) * 8 = 16</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,2,8,9,1,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">42</span></p>
<p><strong>Explanation:</strong></p>
<p>We can do the hopping <code>0 -> 4 -> 6</code> with a score of <code>(4 - 0) * 9 + (6 - 4) * 3 = 42</code>.</p>
</div>
<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>5</sup></code></li>
</ul>
|
Stack; Greedy; Array; Monotonic Stack
|
TypeScript
|
function maxScore(nums: number[]): number {
const stk: number[] = [];
for (let i = 0; i < nums.length; ++i) {
while (stk.length && nums[stk.at(-1)!] <= nums[i]) {
stk.pop();
}
stk.push(i);
}
let ans = 0;
let i = 0;
for (const j of stk) {
ans += (j - i) * nums[j];
i = j;
}
return ans;
}
|
3,222
|
Find the Winning Player in Coin Game
|
Easy
|
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p>
<p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p>
<p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">"Alice"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in a single turn:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">"Bob"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in 2 turns:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
<li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 100</code></li>
</ul>
|
Math; Game Theory; Simulation
|
C++
|
class Solution {
public:
string losingPlayer(int x, int y) {
int k = min(x / 2, y / 8);
x -= k * 2;
y -= k * 8;
return x && y >= 4 ? "Alice" : "Bob";
}
};
|
3,222
|
Find the Winning Player in Coin Game
|
Easy
|
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p>
<p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p>
<p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">"Alice"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in a single turn:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">"Bob"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in 2 turns:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
<li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 100</code></li>
</ul>
|
Math; Game Theory; Simulation
|
Go
|
func losingPlayer(x int, y int) string {
k := min(x/2, y/8)
x -= 2 * k
y -= 8 * k
if x > 0 && y >= 4 {
return "Alice"
}
return "Bob"
}
|
3,222
|
Find the Winning Player in Coin Game
|
Easy
|
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p>
<p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p>
<p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">"Alice"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in a single turn:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">"Bob"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in 2 turns:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
<li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 100</code></li>
</ul>
|
Math; Game Theory; Simulation
|
Java
|
class Solution {
public String losingPlayer(int x, int y) {
int k = Math.min(x / 2, y / 8);
x -= k * 2;
y -= k * 8;
return x > 0 && y >= 4 ? "Alice" : "Bob";
}
}
|
3,222
|
Find the Winning Player in Coin Game
|
Easy
|
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p>
<p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p>
<p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">"Alice"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in a single turn:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">"Bob"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in 2 turns:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
<li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 100</code></li>
</ul>
|
Math; Game Theory; Simulation
|
Python
|
class Solution:
def losingPlayer(self, x: int, y: int) -> str:
k = min(x // 2, y // 8)
x -= k * 2
y -= k * 8
return "Alice" if x and y >= 4 else "Bob"
|
3,222
|
Find the Winning Player in Coin Game
|
Easy
|
<p>You are given two <strong>positive</strong> integers <code>x</code> and <code>y</code>, denoting the number of coins with values 75 and 10 <em>respectively</em>.</p>
<p>Alice and Bob are playing a game. Each turn, starting with <strong>Alice</strong>, the player must pick up coins with a <strong>total</strong> value 115. If the player is unable to do so, they <strong>lose</strong> the game.</p>
<p>Return the <em>name</em> of the player who wins the game if both players play <strong>optimally</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 2, y = 7</span></p>
<p><strong>Output:</strong> <span class="example-io">"Alice"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in a single turn:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">x = 4, y = 11</span></p>
<p><strong>Output:</strong> <span class="example-io">"Bob"</span></p>
<p><strong>Explanation:</strong></p>
<p>The game ends in 2 turns:</p>
<ul>
<li>Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
<li>Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= x, y <= 100</code></li>
</ul>
|
Math; Game Theory; Simulation
|
TypeScript
|
function losingPlayer(x: number, y: number): string {
const k = Math.min((x / 2) | 0, (y / 8) | 0);
x -= k * 2;
y -= k * 8;
return x && y >= 4 ? 'Alice' : 'Bob';
}
|
3,223
|
Minimum Length of String After Operations
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>You can perform the following process on <code>s</code> <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> in the string such that there is <strong>at least</strong> one character to the left of index <code>i</code> that is equal to <code>s[i]</code>, and <strong>at least</strong> one character to the right that is also equal to <code>s[i]</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>left</strong> of <code>i</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>right</strong> of <code>i</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> length of the final string <code>s</code> that you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abaacbcbb"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong><br />
We do the following operations:</p>
<ul>
<li>Choose index 2, then remove the characters at indices 0 and 3. The resulting string is <code>s = "bacbcbb"</code>.</li>
<li>Choose index 3, then remove the characters at indices 0 and 5. The resulting string is <code>s = "acbcb"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We cannot perform any operations, so we return the length of the original string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
C++
|
class Solution {
public:
int minimumLength(string s) {
int cnt[26]{};
for (char& c : s) {
++cnt[c - 'a'];
}
int ans = 0;
for (int x : cnt) {
if (x) {
ans += x % 2 ? 1 : 2;
}
}
return ans;
}
};
|
3,223
|
Minimum Length of String After Operations
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>You can perform the following process on <code>s</code> <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> in the string such that there is <strong>at least</strong> one character to the left of index <code>i</code> that is equal to <code>s[i]</code>, and <strong>at least</strong> one character to the right that is also equal to <code>s[i]</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>left</strong> of <code>i</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>right</strong> of <code>i</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> length of the final string <code>s</code> that you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abaacbcbb"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong><br />
We do the following operations:</p>
<ul>
<li>Choose index 2, then remove the characters at indices 0 and 3. The resulting string is <code>s = "bacbcbb"</code>.</li>
<li>Choose index 3, then remove the characters at indices 0 and 5. The resulting string is <code>s = "acbcb"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We cannot perform any operations, so we return the length of the original string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Go
|
func minimumLength(s string) (ans int) {
cnt := [26]int{}
for _, c := range s {
cnt[c-'a']++
}
for _, x := range cnt {
if x > 0 {
if x&1 == 1 {
ans += 1
} else {
ans += 2
}
}
}
return
}
|
3,223
|
Minimum Length of String After Operations
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>You can perform the following process on <code>s</code> <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> in the string such that there is <strong>at least</strong> one character to the left of index <code>i</code> that is equal to <code>s[i]</code>, and <strong>at least</strong> one character to the right that is also equal to <code>s[i]</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>left</strong> of <code>i</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>right</strong> of <code>i</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> length of the final string <code>s</code> that you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abaacbcbb"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong><br />
We do the following operations:</p>
<ul>
<li>Choose index 2, then remove the characters at indices 0 and 3. The resulting string is <code>s = "bacbcbb"</code>.</li>
<li>Choose index 3, then remove the characters at indices 0 and 5. The resulting string is <code>s = "acbcb"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We cannot perform any operations, so we return the length of the original string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Java
|
class Solution {
public int minimumLength(String s) {
int[] cnt = new int[26];
for (int i = 0; i < s.length(); ++i) {
++cnt[s.charAt(i) - 'a'];
}
int ans = 0;
for (int x : cnt) {
if (x > 0) {
ans += x % 2 == 1 ? 1 : 2;
}
}
return ans;
}
}
|
3,223
|
Minimum Length of String After Operations
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>You can perform the following process on <code>s</code> <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> in the string such that there is <strong>at least</strong> one character to the left of index <code>i</code> that is equal to <code>s[i]</code>, and <strong>at least</strong> one character to the right that is also equal to <code>s[i]</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>left</strong> of <code>i</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>right</strong> of <code>i</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> length of the final string <code>s</code> that you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abaacbcbb"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong><br />
We do the following operations:</p>
<ul>
<li>Choose index 2, then remove the characters at indices 0 and 3. The resulting string is <code>s = "bacbcbb"</code>.</li>
<li>Choose index 3, then remove the characters at indices 0 and 5. The resulting string is <code>s = "acbcb"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We cannot perform any operations, so we return the length of the original string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
Python
|
class Solution:
def minimumLength(self, s: str) -> int:
cnt = Counter(s)
return sum(1 if x & 1 else 2 for x in cnt.values())
|
3,223
|
Minimum Length of String After Operations
|
Medium
|
<p>You are given a string <code>s</code>.</p>
<p>You can perform the following process on <code>s</code> <strong>any</strong> number of times:</p>
<ul>
<li>Choose an index <code>i</code> in the string such that there is <strong>at least</strong> one character to the left of index <code>i</code> that is equal to <code>s[i]</code>, and <strong>at least</strong> one character to the right that is also equal to <code>s[i]</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>left</strong> of <code>i</code>.</li>
<li>Delete the <strong>closest</strong> occurrence of <code>s[i]</code> located to the <strong>right</strong> of <code>i</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> length of the final string <code>s</code> that you can achieve.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "abaacbcbb"</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong><br />
We do the following operations:</p>
<ul>
<li>Choose index 2, then remove the characters at indices 0 and 3. The resulting string is <code>s = "bacbcbb"</code>.</li>
<li>Choose index 3, then remove the characters at indices 0 and 5. The resulting string is <code>s = "acbcb"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "aa"</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We cannot perform any operations, so we return the length of the original string.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 2 * 10<sup>5</sup></code></li>
<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
|
Hash Table; String; Counting
|
TypeScript
|
function minimumLength(s: string): number {
const cnt = new Map<string, number>();
for (const c of s) {
cnt.set(c, (cnt.get(c) || 0) + 1);
}
let ans = 0;
for (const x of cnt.values()) {
ans += x & 1 ? 1 : 2;
}
return ans;
}
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
C++
|
class Solution {
public:
int minChanges(vector<int>& nums, int k) {
int d[k + 2];
memset(d, 0, sizeof(d));
int n = nums.size();
for (int i = 0; i < n / 2; ++i) {
int x = min(nums[i], nums[n - i - 1]);
int y = max(nums[i], nums[n - i - 1]);
d[0] += 1;
d[y - x] -= 1;
d[y - x + 1] += 1;
d[max(y, k - x) + 1] -= 1;
d[max(y, k - x) + 1] += 2;
}
int ans = n, s = 0;
for (int x : d) {
s += x;
ans = min(ans, s);
}
return ans;
}
};
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Go
|
func minChanges(nums []int, k int) int {
d := make([]int, k+2)
n := len(nums)
for i := 0; i < n/2; i++ {
x, y := nums[i], nums[n-1-i]
if x > y {
x, y = y, x
}
d[0] += 1
d[y-x] -= 1
d[y-x+1] += 1
d[max(y, k-x)+1] -= 1
d[max(y, k-x)+1] += 2
}
ans, s := n, 0
for _, x := range d {
s += x
ans = min(ans, s)
}
return ans
}
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Java
|
class Solution {
public int minChanges(int[] nums, int k) {
int[] d = new int[k + 2];
int n = nums.length;
for (int i = 0; i < n / 2; ++i) {
int x = Math.min(nums[i], nums[n - i - 1]);
int y = Math.max(nums[i], nums[n - i - 1]);
d[0] += 1;
d[y - x] -= 1;
d[y - x + 1] += 1;
d[Math.max(y, k - x) + 1] -= 1;
d[Math.max(y, k - x) + 1] += 2;
}
int ans = n, s = 0;
for (int x : d) {
s += x;
ans = Math.min(ans, s);
}
return ans;
}
}
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Python
|
class Solution:
def minChanges(self, nums: List[int], k: int) -> int:
d = [0] * (k + 2)
n = len(nums)
for i in range(n // 2):
x, y = nums[i], nums[-i - 1]
if x > y:
x, y = y, x
d[0] += 1
d[y - x] -= 1
d[y - x + 1] += 1
d[max(y, k - x) + 1] -= 1
d[max(y, k - x) + 1] += 2
return min(accumulate(d))
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
Rust
|
impl Solution {
pub fn min_changes(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut d = vec![0; (k + 2) as usize];
for i in 0..n / 2 {
let x = nums[i].min(nums[n - i - 1]);
let y = nums[i].max(nums[n - i - 1]);
d[0] += 1;
d[(y - x) as usize] -= 1;
d[(y - x + 1) as usize] += 1;
let idx = (y.max(k - x) + 1) as usize;
d[idx] -= 1;
d[idx] += 2;
}
let mut ans = n as i32;
let mut s = 0;
for x in d {
s += x;
ans = ans.min(s);
}
ans
}
}
|
3,224
|
Minimum Array Changes to Make Differences Equal
|
Medium
|
<p>You are given an integer array <code>nums</code> of size <code>n</code> where <code>n</code> is <strong>even</strong>, and an integer <code>k</code>.</p>
<p>You can perform some changes on the array, where in one change you can replace <strong>any</strong> element in the array with <strong>any</strong> integer in the range from <code>0</code> to <code>k</code>.</p>
<p>You need to perform some changes (possibly none) such that the final array satisfies the following condition:</p>
<ul>
<li>There exists an integer <code>X</code> such that <code>abs(a[i] - a[n - i - 1]) = X</code> for all <code>(0 <= i < n)</code>.</li>
</ul>
<p>Return the <strong>minimum</strong> number of changes required to satisfy the above condition.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,2,4,3], k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following changes:</p>
<ul>
<li>Replace <code>nums[1]</code> by 2. The resulting array is <code>nums = [1,<u><strong>2</strong></u>,1,2,4,3]</code>.</li>
<li>Replace <code>nums[3]</code> by 3. The resulting array is <code>nums = [1,2,1,<u><strong>3</strong></u>,4,3]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [0,1,2,3,3,6,5,4], k = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
We can perform the following operations:</p>
<ul>
<li>Replace <code>nums[3]</code> by 0. The resulting array is <code>nums = [0,1,2,<u><strong>0</strong></u>,3,6,5,4]</code>.</li>
<li>Replace <code>nums[4]</code> by 4. The resulting array is <code>nums = [0,1,2,0,<strong><u>4</u></strong>,6,5,4]</code>.</li>
</ul>
<p>The integer <code>X</code> will be 4.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>n</code> is even.</li>
<li><code>0 <= nums[i] <= k <= 10<sup>5</sup></code></li>
</ul>
|
Array; Hash Table; Prefix Sum
|
TypeScript
|
function minChanges(nums: number[], k: number): number {
const d: number[] = Array(k + 2).fill(0);
const n = nums.length;
for (let i = 0; i < n >> 1; ++i) {
const x = Math.min(nums[i], nums[n - 1 - i]);
const y = Math.max(nums[i], nums[n - 1 - i]);
d[0] += 1;
d[y - x] -= 1;
d[y - x + 1] += 1;
d[Math.max(y, k - x) + 1] -= 1;
d[Math.max(y, k - x) + 1] += 2;
}
let [ans, s] = [n, 0];
for (const x of d) {
s += x;
ans = Math.min(ans, s);
}
return ans;
}
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
C++
|
class Solution {
public:
int minChanges(int n, int k) {
return (n & k) != k ? -1 : __builtin_popcount(n ^ k);
}
};
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
C#
|
public class Solution {
public int MinChanges(int n, int k) {
return (n & k) != k ? -1 : BitOperations.PopCount((uint)(n ^ k));
}
}
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
Go
|
func minChanges(n int, k int) int {
if n&k != k {
return -1
}
return bits.OnesCount(uint(n ^ k))
}
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
Java
|
class Solution {
public int minChanges(int n, int k) {
return (n & k) != k ? -1 : Integer.bitCount(n ^ k);
}
}
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
Python
|
class Solution:
def minChanges(self, n: int, k: int) -> int:
return -1 if n & k != k else (n ^ k).bit_count()
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
Rust
|
impl Solution {
pub fn min_changes(n: i32, k: i32) -> i32 {
if (n & k) != k {
-1
} else {
(n ^ k).count_ones() as i32
}
}
}
|
3,226
|
Number of Bit Changes to Make Two Integers Equal
|
Easy
|
<p>You are given two positive integers <code>n</code> and <code>k</code>.</p>
<p>You can choose <strong>any</strong> bit in the <strong>binary representation</strong> of <code>n</code> that is equal to 1 and change it to 0.</p>
<p>Return the <em>number of changes</em> needed to make <code>n</code> equal to <code>k</code>. If it is impossible, return -1.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 13, k = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong><br />
Initially, the binary representations of <code>n</code> and <code>k</code> are <code>n = (1101)<sub>2</sub></code> and <code>k = (0100)<sub>2</sub></code>.<br />
We can change the first and fourth bits of <code>n</code>. The resulting integer is <code>n = (<u><strong>0</strong></u>10<u><strong>0</strong></u>)<sub>2</sub> = k</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 21, k = 21</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong><br />
<code>n</code> and <code>k</code> are already equal, so no changes are needed.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 14, k = 13</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong><br />
It is not possible to make <code>n</code> equal to <code>k</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation
|
TypeScript
|
function minChanges(n: number, k: number): number {
return (n & k) !== k ? -1 : bitCount(n ^ k);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.