id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
2,807
|
Insert Greatest Common Divisors in Linked List
|
Medium
|
<p>Given the head of a linked list <code>head</code>, in which each node contains an integer value.</p>
<p>Between every pair of adjacent nodes, insert a new node with a value equal to the <strong>greatest common divisor</strong> of them.</p>
<p>Return <em>the linked list after insertion</em>.</p>
<p>The <strong>greatest common divisor</strong> of two numbers is the largest positive integer that evenly divides both numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex1_copy.png" style="width: 641px; height: 181px;" />
<pre>
<strong>Input:</strong> head = [18,6,10,3]
<strong>Output:</strong> [18,6,6,2,10,1,3]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
- We insert the greatest common divisor of 18 and 6 = 6 between the 1<sup>st</sup> and the 2<sup>nd</sup> nodes.
- We insert the greatest common divisor of 6 and 10 = 2 between the 2<sup>nd</sup> and the 3<sup>rd</sup> nodes.
- We insert the greatest common divisor of 10 and 3 = 1 between the 3<sup>rd</sup> and the 4<sup>th</sup> nodes.
There are no more adjacent nodes, so we return the linked list.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex2_copy1.png" style="width: 51px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [7]
<strong>Output:</strong> [7]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes.
There are no pairs of adjacent nodes, so we return the initial linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>
<li><code>1 <= Node.val <= 1000</code></li>
</ul>
|
Linked List; Math; Number Theory
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertGreatestCommonDivisors(
self, head: Optional[ListNode]
) -> Optional[ListNode]:
pre, cur = head, head.next
while cur:
x = gcd(pre.val, cur.val)
pre.next = ListNode(x, cur)
pre, cur = cur, cur.next
return head
|
2,807
|
Insert Greatest Common Divisors in Linked List
|
Medium
|
<p>Given the head of a linked list <code>head</code>, in which each node contains an integer value.</p>
<p>Between every pair of adjacent nodes, insert a new node with a value equal to the <strong>greatest common divisor</strong> of them.</p>
<p>Return <em>the linked list after insertion</em>.</p>
<p>The <strong>greatest common divisor</strong> of two numbers is the largest positive integer that evenly divides both numbers.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex1_copy.png" style="width: 641px; height: 181px;" />
<pre>
<strong>Input:</strong> head = [18,6,10,3]
<strong>Output:</strong> [18,6,6,2,10,1,3]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
- We insert the greatest common divisor of 18 and 6 = 6 between the 1<sup>st</sup> and the 2<sup>nd</sup> nodes.
- We insert the greatest common divisor of 6 and 10 = 2 between the 2<sup>nd</sup> and the 3<sup>rd</sup> nodes.
- We insert the greatest common divisor of 10 and 3 = 1 between the 3<sup>rd</sup> and the 4<sup>th</sup> nodes.
There are no more adjacent nodes, so we return the linked list.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2807.Insert%20Greatest%20Common%20Divisors%20in%20Linked%20List/images/ex2_copy1.png" style="width: 51px; height: 191px;" />
<pre>
<strong>Input:</strong> head = [7]
<strong>Output:</strong> [7]
<strong>Explanation:</strong> The 1<sup>st</sup> diagram denotes the initial linked list and the 2<sup>nd</sup> diagram denotes the linked list after inserting the new nodes.
There are no pairs of adjacent nodes, so we return the initial linked list.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>
<li><code>1 <= Node.val <= 1000</code></li>
</ul>
|
Linked List; Math; Number Theory
|
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 insertGreatestCommonDivisors(head: ListNode | null): ListNode | null {
for (let pre = head, cur = head.next; cur; cur = cur.next) {
const x = gcd(pre.val, cur.val);
pre.next = new ListNode(x, cur);
pre = cur;
}
return head;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
|
2,808
|
Minimum Seconds to Equalize a Circular Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> containing <code>n</code> integers.</p>
<p>At each second, you perform the following operation on the array:</p>
<ul>
<li>For every index <code>i</code> in the range <code>[0, n - 1]</code>, replace <code>nums[i]</code> with either <code>nums[i]</code>, <code>nums[(i - 1 + n) % n]</code>, or <code>nums[(i + 1) % n]</code>.</li>
</ul>
<p><strong>Note</strong> that all the elements get replaced simultaneously.</p>
<p>Return <em>the <strong>minimum</strong> number of seconds needed to make all elements in the array</em> <code>nums</code> <em>equal</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can equalize the array in 1 second in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can equalize the array in 2 seconds in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2<sup>nd</sup> second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to perform any operations as all elements in the initial array are the same.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int minimumSeconds(vector<int>& nums) {
unordered_map<int, vector<int>> d;
int n = nums.size();
for (int i = 0; i < n; ++i) {
d[nums[i]].push_back(i);
}
int ans = 1 << 30;
for (auto& [_, idx] : d) {
int m = idx.size();
int t = idx[0] + n - idx[m - 1];
for (int i = 1; i < m; ++i) {
t = max(t, idx[i] - idx[i - 1]);
}
ans = min(ans, t / 2);
}
return ans;
}
};
|
2,808
|
Minimum Seconds to Equalize a Circular Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> containing <code>n</code> integers.</p>
<p>At each second, you perform the following operation on the array:</p>
<ul>
<li>For every index <code>i</code> in the range <code>[0, n - 1]</code>, replace <code>nums[i]</code> with either <code>nums[i]</code>, <code>nums[(i - 1 + n) % n]</code>, or <code>nums[(i + 1) % n]</code>.</li>
</ul>
<p><strong>Note</strong> that all the elements get replaced simultaneously.</p>
<p>Return <em>the <strong>minimum</strong> number of seconds needed to make all elements in the array</em> <code>nums</code> <em>equal</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can equalize the array in 1 second in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can equalize the array in 2 seconds in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2<sup>nd</sup> second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to perform any operations as all elements in the initial array are the same.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func minimumSeconds(nums []int) int {
d := map[int][]int{}
for i, x := range nums {
d[x] = append(d[x], i)
}
ans := 1 << 30
n := len(nums)
for _, idx := range d {
m := len(idx)
t := idx[0] + n - idx[m-1]
for i := 1; i < m; i++ {
t = max(t, idx[i]-idx[i-1])
}
ans = min(ans, t/2)
}
return ans
}
|
2,808
|
Minimum Seconds to Equalize a Circular Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> containing <code>n</code> integers.</p>
<p>At each second, you perform the following operation on the array:</p>
<ul>
<li>For every index <code>i</code> in the range <code>[0, n - 1]</code>, replace <code>nums[i]</code> with either <code>nums[i]</code>, <code>nums[(i - 1 + n) % n]</code>, or <code>nums[(i + 1) % n]</code>.</li>
</ul>
<p><strong>Note</strong> that all the elements get replaced simultaneously.</p>
<p>Return <em>the <strong>minimum</strong> number of seconds needed to make all elements in the array</em> <code>nums</code> <em>equal</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can equalize the array in 1 second in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can equalize the array in 2 seconds in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2<sup>nd</sup> second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to perform any operations as all elements in the initial array are the same.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int minimumSeconds(List<Integer> nums) {
Map<Integer, List<Integer>> d = new HashMap<>();
int n = nums.size();
for (int i = 0; i < n; ++i) {
d.computeIfAbsent(nums.get(i), k -> new ArrayList<>()).add(i);
}
int ans = 1 << 30;
for (List<Integer> idx : d.values()) {
int m = idx.size();
int t = idx.get(0) + n - idx.get(m - 1);
for (int i = 1; i < m; ++i) {
t = Math.max(t, idx.get(i) - idx.get(i - 1));
}
ans = Math.min(ans, t / 2);
}
return ans;
}
}
|
2,808
|
Minimum Seconds to Equalize a Circular Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> containing <code>n</code> integers.</p>
<p>At each second, you perform the following operation on the array:</p>
<ul>
<li>For every index <code>i</code> in the range <code>[0, n - 1]</code>, replace <code>nums[i]</code> with either <code>nums[i]</code>, <code>nums[(i - 1 + n) % n]</code>, or <code>nums[(i + 1) % n]</code>.</li>
</ul>
<p><strong>Note</strong> that all the elements get replaced simultaneously.</p>
<p>Return <em>the <strong>minimum</strong> number of seconds needed to make all elements in the array</em> <code>nums</code> <em>equal</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can equalize the array in 1 second in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can equalize the array in 2 seconds in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2<sup>nd</sup> second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to perform any operations as all elements in the initial array are the same.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def minimumSeconds(self, nums: List[int]) -> int:
d = defaultdict(list)
for i, x in enumerate(nums):
d[x].append(i)
ans = inf
n = len(nums)
for idx in d.values():
t = idx[0] + n - idx[-1]
for i, j in pairwise(idx):
t = max(t, j - i)
ans = min(ans, t // 2)
return ans
|
2,808
|
Minimum Seconds to Equalize a Circular Array
|
Medium
|
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> containing <code>n</code> integers.</p>
<p>At each second, you perform the following operation on the array:</p>
<ul>
<li>For every index <code>i</code> in the range <code>[0, n - 1]</code>, replace <code>nums[i]</code> with either <code>nums[i]</code>, <code>nums[(i - 1 + n) % n]</code>, or <code>nums[(i + 1) % n]</code>.</li>
</ul>
<p><strong>Note</strong> that all the elements get replaced simultaneously.</p>
<p>Return <em>the <strong>minimum</strong> number of seconds needed to make all elements in the array</em> <code>nums</code> <em>equal</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can equalize the array in 1 second in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].
It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,3,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can equalize the array in 2 seconds in the following way:
- At 1<sup>st</sup> second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].
- At 2<sup>nd</sup> second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].
It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,5,5,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> We don't need to perform any operations as all elements in the initial array are the same.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function minimumSeconds(nums: number[]): number {
const d: Map<number, number[]> = new Map();
const n = nums.length;
for (let i = 0; i < n; ++i) {
if (!d.has(nums[i])) {
d.set(nums[i], []);
}
d.get(nums[i])!.push(i);
}
let ans = 1 << 30;
for (const [_, idx] of d) {
const m = idx.length;
let t = idx[0] + n - idx[m - 1];
for (let i = 1; i < m; ++i) {
t = Math.max(t, idx[i] - idx[i - 1]);
}
ans = Math.min(ans, t >> 1);
}
return ans;
}
|
2,809
|
Minimum Time to Make Array Sum At Most x
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length. Every second, for all indices <code>0 <= i < nums1.length</code>, value of <code>nums1[i]</code> is incremented by <code>nums2[i]</code>. <strong>After</strong> this is done, you can do the following operation:</p>
<ul>
<li>Choose an index <code>0 <= i < nums1.length</code> and make <code>nums1[i] = 0</code>.</li>
</ul>
<p>You are also given an integer <code>x</code>.</p>
<p>Return <em>the <strong>minimum</strong> time in which you can make the sum of all elements of </em><code>nums1</code><em> to be<strong> less than or equal</strong> to </em><code>x</code>, <em>or </em><code>-1</code><em> if this is not possible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [1,2,3], x = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [3,3,3], x = 4
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code><font face="monospace">1 <= nums1.length <= 10<sup>3</sup></font></code></li>
<li><code>1 <= nums1[i] <= 10<sup>3</sup></code></li>
<li><code>0 <= nums2[i] <= 10<sup>3</sup></code></li>
<li><code>nums1.length == nums2.length</code></li>
<li><code>0 <= x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
C++
|
class Solution {
public:
int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {
int n = nums1.size();
vector<pair<int, int>> nums;
for (int i = 0; i < n; ++i) {
nums.emplace_back(nums2[i], nums1[i]);
}
sort(nums.begin(), nums.end());
int f[n + 1][n + 1];
memset(f, 0, sizeof(f));
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j) {
auto [b, a] = nums[i - 1];
f[i][j] = max(f[i][j], f[i - 1][j - 1] + a + b * j);
}
}
}
int s1 = accumulate(nums1.begin(), nums1.end(), 0);
int s2 = accumulate(nums2.begin(), nums2.end(), 0);
for (int j = 0; j <= n; ++j) {
if (s1 + s2 * j - f[n][j] <= x) {
return j;
}
}
return -1;
}
};
|
2,809
|
Minimum Time to Make Array Sum At Most x
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length. Every second, for all indices <code>0 <= i < nums1.length</code>, value of <code>nums1[i]</code> is incremented by <code>nums2[i]</code>. <strong>After</strong> this is done, you can do the following operation:</p>
<ul>
<li>Choose an index <code>0 <= i < nums1.length</code> and make <code>nums1[i] = 0</code>.</li>
</ul>
<p>You are also given an integer <code>x</code>.</p>
<p>Return <em>the <strong>minimum</strong> time in which you can make the sum of all elements of </em><code>nums1</code><em> to be<strong> less than or equal</strong> to </em><code>x</code>, <em>or </em><code>-1</code><em> if this is not possible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [1,2,3], x = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [3,3,3], x = 4
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code><font face="monospace">1 <= nums1.length <= 10<sup>3</sup></font></code></li>
<li><code>1 <= nums1[i] <= 10<sup>3</sup></code></li>
<li><code>0 <= nums2[i] <= 10<sup>3</sup></code></li>
<li><code>nums1.length == nums2.length</code></li>
<li><code>0 <= x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Go
|
func minimumTime(nums1 []int, nums2 []int, x int) int {
n := len(nums1)
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, n+1)
}
type pair struct{ a, b int }
nums := make([]pair, n)
var s1, s2 int
for i := range nums {
s1 += nums1[i]
s2 += nums2[i]
nums[i] = pair{nums1[i], nums2[i]}
}
sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b })
for i := 1; i <= n; i++ {
for j := 0; j <= n; j++ {
f[i][j] = f[i-1][j]
if j > 0 {
a, b := nums[i-1].a, nums[i-1].b
f[i][j] = max(f[i][j], f[i-1][j-1]+a+b*j)
}
}
}
for j := 0; j <= n; j++ {
if s1+s2*j-f[n][j] <= x {
return j
}
}
return -1
}
|
2,809
|
Minimum Time to Make Array Sum At Most x
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length. Every second, for all indices <code>0 <= i < nums1.length</code>, value of <code>nums1[i]</code> is incremented by <code>nums2[i]</code>. <strong>After</strong> this is done, you can do the following operation:</p>
<ul>
<li>Choose an index <code>0 <= i < nums1.length</code> and make <code>nums1[i] = 0</code>.</li>
</ul>
<p>You are also given an integer <code>x</code>.</p>
<p>Return <em>the <strong>minimum</strong> time in which you can make the sum of all elements of </em><code>nums1</code><em> to be<strong> less than or equal</strong> to </em><code>x</code>, <em>or </em><code>-1</code><em> if this is not possible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [1,2,3], x = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [3,3,3], x = 4
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code><font face="monospace">1 <= nums1.length <= 10<sup>3</sup></font></code></li>
<li><code>1 <= nums1[i] <= 10<sup>3</sup></code></li>
<li><code>0 <= nums2[i] <= 10<sup>3</sup></code></li>
<li><code>nums1.length == nums2.length</code></li>
<li><code>0 <= x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Java
|
class Solution {
public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {
int n = nums1.size();
int[][] f = new int[n + 1][n + 1];
int[][] nums = new int[n][0];
for (int i = 0; i < n; ++i) {
nums[i] = new int[] {nums1.get(i), nums2.get(i)};
}
Arrays.sort(nums, Comparator.comparingInt(a -> a[1]));
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j > 0) {
int a = nums[i - 1][0], b = nums[i - 1][1];
f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + a + b * j);
}
}
}
int s1 = 0, s2 = 0;
for (int v : nums1) {
s1 += v;
}
for (int v : nums2) {
s2 += v;
}
for (int j = 0; j <= n; ++j) {
if (s1 + s2 * j - f[n][j] <= x) {
return j;
}
}
return -1;
}
}
|
2,809
|
Minimum Time to Make Array Sum At Most x
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length. Every second, for all indices <code>0 <= i < nums1.length</code>, value of <code>nums1[i]</code> is incremented by <code>nums2[i]</code>. <strong>After</strong> this is done, you can do the following operation:</p>
<ul>
<li>Choose an index <code>0 <= i < nums1.length</code> and make <code>nums1[i] = 0</code>.</li>
</ul>
<p>You are also given an integer <code>x</code>.</p>
<p>Return <em>the <strong>minimum</strong> time in which you can make the sum of all elements of </em><code>nums1</code><em> to be<strong> less than or equal</strong> to </em><code>x</code>, <em>or </em><code>-1</code><em> if this is not possible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [1,2,3], x = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [3,3,3], x = 4
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code><font face="monospace">1 <= nums1.length <= 10<sup>3</sup></font></code></li>
<li><code>1 <= nums1[i] <= 10<sup>3</sup></code></li>
<li><code>0 <= nums2[i] <= 10<sup>3</sup></code></li>
<li><code>nums1.length == nums2.length</code></li>
<li><code>0 <= x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
Python
|
class Solution:
def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:
n = len(nums1)
f = [[0] * (n + 1) for _ in range(n + 1)]
for i, (a, b) in enumerate(sorted(zip(nums1, nums2), key=lambda z: z[1]), 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j > 0:
f[i][j] = max(f[i][j], f[i - 1][j - 1] + a + b * j)
s1 = sum(nums1)
s2 = sum(nums2)
for j in range(n + 1):
if s1 + s2 * j - f[n][j] <= x:
return j
return -1
|
2,809
|
Minimum Time to Make Array Sum At Most x
|
Hard
|
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of equal length. Every second, for all indices <code>0 <= i < nums1.length</code>, value of <code>nums1[i]</code> is incremented by <code>nums2[i]</code>. <strong>After</strong> this is done, you can do the following operation:</p>
<ul>
<li>Choose an index <code>0 <= i < nums1.length</code> and make <code>nums1[i] = 0</code>.</li>
</ul>
<p>You are also given an integer <code>x</code>.</p>
<p>Return <em>the <strong>minimum</strong> time in which you can make the sum of all elements of </em><code>nums1</code><em> to be<strong> less than or equal</strong> to </em><code>x</code>, <em>or </em><code>-1</code><em> if this is not possible.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [1,2,3], x = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums1 = [1,2,3], nums2 = [3,3,3], x = 4
<strong>Output:</strong> -1
<strong>Explanation:</strong> It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code><font face="monospace">1 <= nums1.length <= 10<sup>3</sup></font></code></li>
<li><code>1 <= nums1[i] <= 10<sup>3</sup></code></li>
<li><code>0 <= nums2[i] <= 10<sup>3</sup></code></li>
<li><code>nums1.length == nums2.length</code></li>
<li><code>0 <= x <= 10<sup>6</sup></code></li>
</ul>
|
Array; Dynamic Programming; Sorting
|
TypeScript
|
function minimumTime(nums1: number[], nums2: number[], x: number): number {
const n = nums1.length;
const f: number[][] = Array(n + 1)
.fill(0)
.map(() => Array(n + 1).fill(0));
const nums: number[][] = [];
for (let i = 0; i < n; ++i) {
nums.push([nums1[i], nums2[i]]);
}
nums.sort((a, b) => a[1] - b[1]);
for (let i = 1; i <= n; ++i) {
for (let j = 0; j <= n; ++j) {
f[i][j] = f[i - 1][j];
if (j > 0) {
const [a, b] = nums[i - 1];
f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + a + b * j);
}
}
}
const s1 = nums1.reduce((a, b) => a + b, 0);
const s2 = nums2.reduce((a, b) => a + b, 0);
for (let j = 0; j <= n; ++j) {
if (s1 + s2 * j - f[n][j] <= x) {
return j;
}
}
return -1;
}
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
C++
|
class Solution {
public:
string finalString(string s) {
string t;
for (char c : s) {
if (c == 'i') {
reverse(t.begin(), t.end());
} else {
t.push_back(c);
}
}
return t;
}
};
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
Go
|
func finalString(s string) string {
t := []rune{}
for _, c := range s {
if c == 'i' {
for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 {
t[i], t[j] = t[j], t[i]
}
} else {
t = append(t, c)
}
}
return string(t)
}
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
Java
|
class Solution {
public String finalString(String s) {
StringBuilder t = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == 'i') {
t.reverse();
} else {
t.append(c);
}
}
return t.toString();
}
}
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
Python
|
class Solution:
def finalString(self, s: str) -> str:
t = []
for c in s:
if c == "i":
t = t[::-1]
else:
t.append(c)
return "".join(t)
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
Rust
|
impl Solution {
pub fn final_string(s: String) -> String {
let mut t = Vec::new();
for c in s.chars() {
if c == 'i' {
t.reverse();
} else {
t.push(c);
}
}
t.into_iter().collect()
}
}
|
2,810
|
Faulty Keyboard
|
Easy
|
<p>Your laptop keyboard is faulty, and whenever you type a character <code>'i'</code> on it, it reverses the string that you have written. Typing other characters works as expected.</p>
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and you type each character of <code>s</code> using your faulty keyboard.</p>
<p>Return <em>the final string that will be present on your laptop screen.</em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "string"
<strong>Output:</strong> "rtsng"
<strong>Explanation:</strong>
After typing first character, the text on the screen is "s".
After the second character, the text is "st".
After the third character, the text is "str".
Since the fourth character is an 'i', the text gets reversed and becomes "rts".
After the fifth character, the text is "rtsn".
After the sixth character, the text is "rtsng".
Therefore, we return "rtsng".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "poiinter"
<strong>Output:</strong> "ponter"
<strong>Explanation:</strong>
After the first character, the text on the screen is "p".
After the second character, the text is "po".
Since the third character you type is an 'i', the text gets reversed and becomes "op".
Since the fourth character you type is an 'i', the text gets reversed and becomes "po".
After the fifth character, the text is "pon".
After the sixth character, the text is "pont".
After the seventh character, the text is "ponte".
After the eighth character, the text is "ponter".
Therefore, we return "ponter".</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 100</code></li>
<li><code>s</code> consists of lowercase English letters.</li>
<li><code>s[0] != 'i'</code></li>
</ul>
|
String; Simulation
|
TypeScript
|
function finalString(s: string): string {
const t: string[] = [];
for (const c of s) {
if (c === 'i') {
t.reverse();
} else {
t.push(c);
}
}
return t.join('');
}
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
C++
|
class Solution {
public:
bool canSplitArray(vector<int>& nums, int m) {
int n = nums.size();
vector<int> s(n + 1);
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums[i - 1];
}
int f[n][n];
memset(f, -1, sizeof f);
function<bool(int, int)> dfs = [&](int i, int j) {
if (i == j) {
return true;
}
if (f[i][j] != -1) {
return f[i][j] == 1;
}
for (int k = i; k < j; ++k) {
bool a = k == i || s[k + 1] - s[i] >= m;
bool b = k == j - 1 || s[j + 1] - s[k + 1] >= m;
if (a && b && dfs(i, k) && dfs(k + 1, j)) {
f[i][j] = 1;
return true;
}
}
f[i][j] = 0;
return false;
};
return dfs(0, n - 1);
}
};
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
Go
|
func canSplitArray(nums []int, m int) bool {
n := len(nums)
f := make([][]int, n)
s := make([]int, n+1)
for i, x := range nums {
s[i+1] = s[i] + x
}
for i := range f {
f[i] = make([]int, n)
}
var dfs func(i, j int) bool
dfs = func(i, j int) bool {
if i == j {
return true
}
if f[i][j] != 0 {
return f[i][j] == 1
}
for k := i; k < j; k++ {
a := k == i || s[k+1]-s[i] >= m
b := k == j-1 || s[j+1]-s[k+1] >= m
if a && b && dfs(i, k) && dfs(k+1, j) {
f[i][j] = 1
return true
}
}
f[i][j] = -1
return false
}
return dfs(0, n-1)
}
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
Java
|
class Solution {
private Boolean[][] f;
private int[] s;
private int m;
public boolean canSplitArray(List<Integer> nums, int m) {
int n = nums.size();
f = new Boolean[n][n];
s = new int[n + 1];
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums.get(i - 1);
}
this.m = m;
return dfs(0, n - 1);
}
private boolean dfs(int i, int j) {
if (i == j) {
return true;
}
if (f[i][j] != null) {
return f[i][j];
}
for (int k = i; k < j; ++k) {
boolean a = k == i || s[k + 1] - s[i] >= m;
boolean b = k == j - 1 || s[j + 1] - s[k + 1] >= m;
if (a && b && dfs(i, k) && dfs(k + 1, j)) {
return f[i][j] = true;
}
}
return f[i][j] = false;
}
}
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
Python
|
class Solution:
def canSplitArray(self, nums: List[int], m: int) -> bool:
@cache
def dfs(i: int, j: int) -> bool:
if i == j:
return True
for k in range(i, j):
a = k == i or s[k + 1] - s[i] >= m
b = k == j - 1 or s[j + 1] - s[k + 1] >= m
if a and b and dfs(i, k) and dfs(k + 1, j):
return True
return False
s = list(accumulate(nums, initial=0))
return dfs(0, len(nums) - 1)
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
Rust
|
impl Solution {
pub fn can_split_array(nums: Vec<i32>, m: i32) -> bool {
let n = nums.len();
if n <= 2 {
return true;
}
for i in 1..n {
if nums[i - 1] + nums[i] >= m {
return true;
}
}
false
}
}
|
2,811
|
Check if it is Possible to Split Array
|
Medium
|
<p>You are given an array <code>nums</code> of length <code>n</code> and an integer <code>m</code>. You need to determine if it is possible to split the array into <code>n</code> arrays of size 1 by performing a series of steps.</p>
<p>An array is called <strong>good</strong> if:</p>
<ul>
<li>The length of the array is <strong>one</strong>, or</li>
<li>The sum of the elements of the array is <strong>greater than or equal</strong> to <code>m</code>.</li>
</ul>
<p>In each step, you can select an existing array (which may be the result of previous steps) with a length of <strong>at least two</strong> and split it into <strong>two </strong>arrays, if both resulting arrays are good.</p>
<p>Return true if you can split the given array into <code>n</code> arrays, otherwise return false.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 2, 1], m = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Split <code>[2, 2, 1]</code> to <code>[2, 2]</code> and <code>[1]</code>. The array <code>[1]</code> has a length of one, and the array <code>[2, 2]</code> has the sum of its elements equal to <code>4 >= m</code>, so both are good arrays.</li>
<li>Split <code>[2, 2]</code> to <code>[2]</code> and <code>[2]</code>. both arrays have the length of one, so both are good arrays.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 1, 3], m = 5</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>The first move has to be either of the following:</p>
<ul>
<li>Split <code>[2, 1, 3]</code> to <code>[2, 1]</code> and <code>[3]</code>. The array <code>[2, 1]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
<li>Split <code>[2, 1, 3]</code> to <code>[2]</code> and <code>[1, 3]</code>. The array <code>[1, 3]</code> has neither length of one nor sum of elements greater than or equal to <code>m</code>.</li>
</ul>
<p>So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split <code>nums</code> into <code>n</code> arrays of size 1.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2, 3, 3, 2, 3], m = 6</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li><span class="example-io">Split <code>[2, 3, 3, 2, 3]</code> to <code>[2]</code> and <code>[3, 3, 2, 3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2, 3]</code> to <code>[3, 3, 2]</code> and <code>[3]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3, 2]</code> to <code>[3, 3]</code> and <code>[2]</code>.</span></li>
<li><span class="example-io">Split <code>[3, 3]</code> to <code>[3]</code> and <code>[3]</code>.</span></li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
<li><code>1 <= m <= 200</code></li>
</ul>
|
Greedy; Array; Dynamic Programming
|
TypeScript
|
function canSplitArray(nums: number[], m: number): boolean {
const n = nums.length;
const s: number[] = new Array(n + 1).fill(0);
for (let i = 1; i <= n; ++i) {
s[i] = s[i - 1] + nums[i - 1];
}
const f: number[][] = Array(n)
.fill(0)
.map(() => Array(n).fill(-1));
const dfs = (i: number, j: number): boolean => {
if (i === j) {
return true;
}
if (f[i][j] !== -1) {
return f[i][j] === 1;
}
for (let k = i; k < j; ++k) {
const a = k === i || s[k + 1] - s[i] >= m;
const b = k === j - 1 || s[j + 1] - s[k + 1] >= m;
if (a && b && dfs(i, k) && dfs(k + 1, j)) {
f[i][j] = 1;
return true;
}
}
f[i][j] = 0;
return false;
};
return dfs(0, n - 1);
}
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
C++
|
class UnionFind {
public:
vector<int> p;
int n;
UnionFind(int _n)
: n(_n)
, p(_n) {
iota(p.begin(), p.end(), 0);
}
bool unite(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) return false;
p[pa] = pb;
--n;
return true;
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
};
class Solution {
public:
int maximumSafenessFactor(vector<vector<int>>& grid) {
int n = grid.size();
if (grid[0][0] || grid[n - 1][n - 1]) {
return 0;
}
queue<pair<int, int>> q;
int dist[n][n];
memset(dist, 0x3f, sizeof(dist));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j]) {
dist[i][j] = 0;
q.emplace(i, j);
}
}
}
int dirs[5] = {-1, 0, 1, 0, -1};
while (!q.empty()) {
auto [i, j] = q.front();
q.pop();
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == 0x3f3f3f3f) {
dist[x][y] = dist[i][j] + 1;
q.emplace(x, y);
}
}
}
vector<tuple<int, int, int>> t;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
t.emplace_back(dist[i][j], i, j);
}
}
sort(t.begin(), t.end());
reverse(t.begin(), t.end());
UnionFind uf(n * n);
for (auto [d, i, j] : t) {
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) {
uf.unite(i * n + j, x * n + y);
}
}
if (uf.find(0) == uf.find(n * n - 1)) {
return d;
}
}
return 0;
}
};
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
Go
|
type unionFind struct {
p []int
n int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
for i := range p {
p[i] = i
}
return &unionFind{p, n}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
if uf.find(a) == uf.find(b) {
return false
}
uf.p[uf.find(a)] = uf.find(b)
uf.n--
return true
}
func maximumSafenessFactor(grid [][]int) int {
n := len(grid)
if grid[0][0] == 1 || grid[n-1][n-1] == 1 {
return 0
}
q := [][2]int{}
dist := make([][]int, n)
const inf = 1 << 30
for i := range dist {
dist[i] = make([]int, n)
for j := range dist[i] {
dist[i][j] = inf
}
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
dist[i][j] = 0
q = append(q, [2]int{i, j})
}
}
}
dirs := [5]int{-1, 0, 1, 0, -1}
for len(q) > 0 {
p := q[0]
q = q[1:]
i, j := p[0], p[1]
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == inf {
dist[x][y] = dist[i][j] + 1
q = append(q, [2]int{x, y})
}
}
}
t := [][3]int{}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
t = append(t, [3]int{dist[i][j], i, j})
}
}
sort.Slice(t, func(i, j int) bool {
return t[i][0] > t[j][0]
})
uf := newUnionFind(n * n)
for _, p := range t {
d, i, j := p[0], p[1], p[2]
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d {
uf.union(i*n+j, x*n+y)
}
}
if uf.find(0) == uf.find(n*n-1) {
return d
}
}
return 0
}
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
Java
|
class Solution {
public int maximumSafenessFactor(List<List<Integer>> grid) {
int n = grid.size();
if (grid.get(0).get(0) == 1 || grid.get(n - 1).get(n - 1) == 1) {
return 0;
}
Deque<int[]> q = new ArrayDeque<>();
int[][] dist = new int[n][n];
final int inf = 1 << 30;
for (int[] d : dist) {
Arrays.fill(d, inf);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid.get(i).get(j) == 1) {
dist[i][j] = 0;
q.offer(new int[] {i, j});
}
}
}
int[] dirs = {-1, 0, 1, 0, -1};
while (!q.isEmpty()) {
int[] p = q.poll();
int i = p[0], j = p[1];
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] == inf) {
dist[x][y] = dist[i][j] + 1;
q.offer(new int[] {x, y});
}
}
}
List<int[]> t = new ArrayList<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
t.add(new int[] {dist[i][j], i, j});
}
}
t.sort((a, b) -> Integer.compare(b[0], a[0]));
UnionFind uf = new UnionFind(n * n);
for (int[] p : t) {
int d = p[0], i = p[1], j = p[2];
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) {
uf.union(i * n + j, x * n + y);
}
}
if (uf.find(0) == uf.find(n * n - 1)) {
return d;
}
}
return 0;
}
}
class UnionFind {
public int[] p;
public int n;
public UnionFind(int n) {
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
this.n = n;
}
public boolean union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa == pb) {
return false;
}
p[pa] = pb;
--n;
return true;
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
Python
|
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def maximumSafenessFactor(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] or grid[n - 1][n - 1]:
return 0
q = deque()
dist = [[inf] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if grid[i][j]:
q.append((i, j))
dist[i][j] = 0
dirs = (-1, 0, 1, 0, -1)
while q:
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and dist[x][y] == inf:
dist[x][y] = dist[i][j] + 1
q.append((x, y))
q = ((dist[i][j], i, j) for i in range(n) for j in range(n))
q = sorted(q, reverse=True)
uf = UnionFind(n * n)
for d, i, j in q:
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and dist[x][y] >= d:
uf.union(i * n + j, x * n + y)
if uf.find(0) == uf.find(n * n - 1):
return int(d)
return 0
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
Rust
|
use std::collections::VecDeque;
impl Solution {
fn dfs(i: usize, j: usize, v: i32, g: &Vec<Vec<i32>>, vis: &mut Vec<Vec<bool>>) -> bool {
if vis[i][j] || g[i][j] <= v {
return false;
}
vis[i][j] = true;
let n = g.len();
(i == n - 1 && j == n - 1)
|| (i != 0 && Self::dfs(i - 1, j, v, g, vis))
|| (i != n - 1 && Self::dfs(i + 1, j, v, g, vis))
|| (j != 0 && Self::dfs(i, j - 1, v, g, vis))
|| (j != n - 1 && Self::dfs(i, j + 1, v, g, vis))
}
pub fn maximum_safeness_factor(grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let mut g = vec![vec![-1; n]; n];
let mut q = VecDeque::new();
for i in 0..n {
for j in 0..n {
if grid[i][j] == 1 {
q.push_back((i, j));
}
}
}
let mut level = 0;
while !q.is_empty() {
let m = q.len();
for _ in 0..m {
let (i, j) = q.pop_front().unwrap();
if g[i][j] != -1 {
continue;
}
g[i][j] = level;
if i != n - 1 {
q.push_back((i + 1, j));
}
if i != 0 {
q.push_back((i - 1, j));
}
if j != n - 1 {
q.push_back((i, j + 1));
}
if j != 0 {
q.push_back((i, j - 1));
}
}
level += 1;
}
let mut left = 0;
let mut right = level;
while left < right {
let mid = (left + right) >> 1;
if Self::dfs(0, 0, mid, &g, &mut vec![vec![false; n]; n]) {
left = mid + 1;
} else {
right = mid;
}
}
right
}
}
|
2,812
|
Find the Safest Path in a Grid
|
Medium
|
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>
<ul>
<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>
<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>
<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>
<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>
<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>
<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2812.Find%20the%20Safest%20Path%20in%20a%20Grid/images/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= grid.length == n <= 400</code></li>
<li><code>grid[i].length == n</code></li>
<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
<li>There is at least one thief in the <code>grid</code>.</li>
</ul>
|
Breadth-First Search; Union Find; Array; Binary Search; Matrix; Heap (Priority Queue)
|
TypeScript
|
class UnionFind {
private p: number[];
private n: number;
constructor(n: number) {
this.n = n;
this.p = Array(n)
.fill(0)
.map((_, i) => i);
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
const pa = this.find(a);
const pb = this.find(b);
if (pa !== pb) {
this.p[pa] = pb;
this.n--;
return true;
}
return false;
}
}
function maximumSafenessFactor(grid: number[][]): number {
const n = grid.length;
if (grid[0][0] === 1 || grid[n - 1][n - 1] === 1) {
return 0;
}
const q: number[][] = [];
const inf = 1 << 30;
const dist: number[][] = Array(n)
.fill(0)
.map(() => Array(n).fill(inf));
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
if (grid[i][j] === 1) {
dist[i][j] = 0;
q.push([i, j]);
}
}
}
const dirs = [-1, 0, 1, 0, -1];
while (q.length) {
const [i, j] = q.shift()!;
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] === inf) {
dist[x][y] = dist[i][j] + 1;
q.push([x, y]);
}
}
}
const t: number[][] = [];
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
t.push([dist[i][j], i, j]);
}
}
t.sort((a, b) => b[0] - a[0]);
const uf = new UnionFind(n * n);
for (const [d, i, j] of t) {
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x >= 0 && x < n && y >= 0 && y < n && dist[x][y] >= d) {
uf.union(i * n + j, x * n + y);
}
}
if (uf.find(0) == uf.find(n * n - 1)) {
return d;
}
}
return 0;
}
|
2,813
|
Maximum Elegance of a K-Length Subsequence
|
Hard
|
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>items</code> of length <code>n</code> and an integer <code>k</code>.</p>
<p><code>items[i] = [profit<sub>i</sub>, category<sub>i</sub>]</code>, where <code>profit<sub>i</sub></code> and <code>category<sub>i</sub></code> denote the profit and category of the <code>i<sup>th</sup></code> item respectively.</p>
<p>Let's define the <strong>elegance</strong> of a <strong>subsequence</strong> of <code>items</code> as <code>total_profit + distinct_categories<sup>2</sup></code>, where <code>total_profit</code> is the sum of all profits in the subsequence, and <code>distinct_categories</code> is the number of <strong>distinct</strong> categories from all the categories in the selected subsequence.</p>
<p>Your task is to find the <strong>maximum elegance</strong> from all subsequences of size <code>k</code> in <code>items</code>.</p>
<p>Return <em>an integer denoting the maximum elegance of a subsequence of </em><code>items</code><em> with size exactly </em><code>k</code>.</p>
<p><strong>Note:</strong> A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,2],[5,1],[10,1]], k = 2
<strong>Output:</strong> 17
<strong>Explanation: </strong>In this example, we have to select a subsequence of size 2.
We can select items[0] = [3,2] and items[2] = [10,1].
The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].
Hence, the elegance is 13 + 2<sup>2</sup> = 17, and we can show that it is the maximum achievable elegance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,1],[3,1],[2,2],[5,3]], k = 3
<strong>Output:</strong> 19
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3].
The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3].
Hence, the elegance is 10 + 3<sup>2</sup> = 19, and we can show that it is the maximum achievable elegance.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> items = [[1,1],[2,1],[3,1]], k = 3
<strong>Output:</strong> 7
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We should select all the items.
The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1].
Hence, the maximum elegance is 6 + 1<sup>2</sup> = 7. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= items.length == n <= 10<sup>5</sup></code></li>
<li><code>items[i].length == 2</code></li>
<li><code>items[i][0] == profit<sub>i</sub></code></li>
<li><code>items[i][1] == category<sub>i</sub></code></li>
<li><code>1 <= profit<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= category<sub>i</sub> <= n </code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Stack; Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long findMaximumElegance(vector<vector<int>>& items, int k) {
sort(items.begin(), items.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] > b[0];
});
long long tot = 0;
unordered_set<int> vis;
stack<int> dup;
for (int i = 0; i < k; ++i) {
int p = items[i][0], c = items[i][1];
tot += p;
if (vis.count(c)) {
dup.push(p);
} else {
vis.insert(c);
}
}
int n = items.size();
long long ans = tot + 1LL * vis.size() * vis.size();
for (int i = k; i < n; ++i) {
int p = items[i][0], c = items[i][1];
if (vis.count(c) || dup.empty()) {
continue;
}
vis.insert(c);
tot += p - dup.top();
dup.pop();
ans = max(ans, tot + (long long) (1LL * vis.size() * vis.size()));
}
return ans;
}
};
|
2,813
|
Maximum Elegance of a K-Length Subsequence
|
Hard
|
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>items</code> of length <code>n</code> and an integer <code>k</code>.</p>
<p><code>items[i] = [profit<sub>i</sub>, category<sub>i</sub>]</code>, where <code>profit<sub>i</sub></code> and <code>category<sub>i</sub></code> denote the profit and category of the <code>i<sup>th</sup></code> item respectively.</p>
<p>Let's define the <strong>elegance</strong> of a <strong>subsequence</strong> of <code>items</code> as <code>total_profit + distinct_categories<sup>2</sup></code>, where <code>total_profit</code> is the sum of all profits in the subsequence, and <code>distinct_categories</code> is the number of <strong>distinct</strong> categories from all the categories in the selected subsequence.</p>
<p>Your task is to find the <strong>maximum elegance</strong> from all subsequences of size <code>k</code> in <code>items</code>.</p>
<p>Return <em>an integer denoting the maximum elegance of a subsequence of </em><code>items</code><em> with size exactly </em><code>k</code>.</p>
<p><strong>Note:</strong> A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,2],[5,1],[10,1]], k = 2
<strong>Output:</strong> 17
<strong>Explanation: </strong>In this example, we have to select a subsequence of size 2.
We can select items[0] = [3,2] and items[2] = [10,1].
The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].
Hence, the elegance is 13 + 2<sup>2</sup> = 17, and we can show that it is the maximum achievable elegance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,1],[3,1],[2,2],[5,3]], k = 3
<strong>Output:</strong> 19
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3].
The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3].
Hence, the elegance is 10 + 3<sup>2</sup> = 19, and we can show that it is the maximum achievable elegance.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> items = [[1,1],[2,1],[3,1]], k = 3
<strong>Output:</strong> 7
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We should select all the items.
The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1].
Hence, the maximum elegance is 6 + 1<sup>2</sup> = 7. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= items.length == n <= 10<sup>5</sup></code></li>
<li><code>items[i].length == 2</code></li>
<li><code>items[i][0] == profit<sub>i</sub></code></li>
<li><code>items[i][1] == category<sub>i</sub></code></li>
<li><code>1 <= profit<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= category<sub>i</sub> <= n </code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Stack; Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
|
Go
|
func findMaximumElegance(items [][]int, k int) int64 {
sort.Slice(items, func(i, j int) bool { return items[i][0] > items[j][0] })
tot := 0
vis := map[int]bool{}
dup := []int{}
for _, item := range items[:k] {
p, c := item[0], item[1]
tot += p
if vis[c] {
dup = append(dup, p)
} else {
vis[c] = true
}
}
ans := tot + len(vis)*len(vis)
for _, item := range items[k:] {
p, c := item[0], item[1]
if vis[c] || len(dup) == 0 {
continue
}
vis[c] = true
tot += p - dup[len(dup)-1]
dup = dup[:len(dup)-1]
ans = max(ans, tot+len(vis)*len(vis))
}
return int64(ans)
}
|
2,813
|
Maximum Elegance of a K-Length Subsequence
|
Hard
|
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>items</code> of length <code>n</code> and an integer <code>k</code>.</p>
<p><code>items[i] = [profit<sub>i</sub>, category<sub>i</sub>]</code>, where <code>profit<sub>i</sub></code> and <code>category<sub>i</sub></code> denote the profit and category of the <code>i<sup>th</sup></code> item respectively.</p>
<p>Let's define the <strong>elegance</strong> of a <strong>subsequence</strong> of <code>items</code> as <code>total_profit + distinct_categories<sup>2</sup></code>, where <code>total_profit</code> is the sum of all profits in the subsequence, and <code>distinct_categories</code> is the number of <strong>distinct</strong> categories from all the categories in the selected subsequence.</p>
<p>Your task is to find the <strong>maximum elegance</strong> from all subsequences of size <code>k</code> in <code>items</code>.</p>
<p>Return <em>an integer denoting the maximum elegance of a subsequence of </em><code>items</code><em> with size exactly </em><code>k</code>.</p>
<p><strong>Note:</strong> A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,2],[5,1],[10,1]], k = 2
<strong>Output:</strong> 17
<strong>Explanation: </strong>In this example, we have to select a subsequence of size 2.
We can select items[0] = [3,2] and items[2] = [10,1].
The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].
Hence, the elegance is 13 + 2<sup>2</sup> = 17, and we can show that it is the maximum achievable elegance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,1],[3,1],[2,2],[5,3]], k = 3
<strong>Output:</strong> 19
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3].
The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3].
Hence, the elegance is 10 + 3<sup>2</sup> = 19, and we can show that it is the maximum achievable elegance.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> items = [[1,1],[2,1],[3,1]], k = 3
<strong>Output:</strong> 7
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We should select all the items.
The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1].
Hence, the maximum elegance is 6 + 1<sup>2</sup> = 7. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= items.length == n <= 10<sup>5</sup></code></li>
<li><code>items[i].length == 2</code></li>
<li><code>items[i][0] == profit<sub>i</sub></code></li>
<li><code>items[i][1] == category<sub>i</sub></code></li>
<li><code>1 <= profit<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= category<sub>i</sub> <= n </code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Stack; Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
|
Java
|
class Solution {
public long findMaximumElegance(int[][] items, int k) {
Arrays.sort(items, (a, b) -> b[0] - a[0]);
int n = items.length;
long tot = 0;
Set<Integer> vis = new HashSet<>();
Deque<Integer> dup = new ArrayDeque<>();
for (int i = 0; i < k; ++i) {
int p = items[i][0], c = items[i][1];
tot += p;
if (!vis.add(c)) {
dup.push(p);
}
}
long ans = tot + (long) vis.size() * vis.size();
for (int i = k; i < n; ++i) {
int p = items[i][0], c = items[i][1];
if (vis.contains(c) || dup.isEmpty()) {
continue;
}
vis.add(c);
tot += p - dup.pop();
ans = Math.max(ans, tot + (long) vis.size() * vis.size());
}
return ans;
}
}
|
2,813
|
Maximum Elegance of a K-Length Subsequence
|
Hard
|
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>items</code> of length <code>n</code> and an integer <code>k</code>.</p>
<p><code>items[i] = [profit<sub>i</sub>, category<sub>i</sub>]</code>, where <code>profit<sub>i</sub></code> and <code>category<sub>i</sub></code> denote the profit and category of the <code>i<sup>th</sup></code> item respectively.</p>
<p>Let's define the <strong>elegance</strong> of a <strong>subsequence</strong> of <code>items</code> as <code>total_profit + distinct_categories<sup>2</sup></code>, where <code>total_profit</code> is the sum of all profits in the subsequence, and <code>distinct_categories</code> is the number of <strong>distinct</strong> categories from all the categories in the selected subsequence.</p>
<p>Your task is to find the <strong>maximum elegance</strong> from all subsequences of size <code>k</code> in <code>items</code>.</p>
<p>Return <em>an integer denoting the maximum elegance of a subsequence of </em><code>items</code><em> with size exactly </em><code>k</code>.</p>
<p><strong>Note:</strong> A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,2],[5,1],[10,1]], k = 2
<strong>Output:</strong> 17
<strong>Explanation: </strong>In this example, we have to select a subsequence of size 2.
We can select items[0] = [3,2] and items[2] = [10,1].
The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].
Hence, the elegance is 13 + 2<sup>2</sup> = 17, and we can show that it is the maximum achievable elegance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,1],[3,1],[2,2],[5,3]], k = 3
<strong>Output:</strong> 19
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3].
The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3].
Hence, the elegance is 10 + 3<sup>2</sup> = 19, and we can show that it is the maximum achievable elegance.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> items = [[1,1],[2,1],[3,1]], k = 3
<strong>Output:</strong> 7
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We should select all the items.
The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1].
Hence, the maximum elegance is 6 + 1<sup>2</sup> = 7. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= items.length == n <= 10<sup>5</sup></code></li>
<li><code>items[i].length == 2</code></li>
<li><code>items[i][0] == profit<sub>i</sub></code></li>
<li><code>items[i][1] == category<sub>i</sub></code></li>
<li><code>1 <= profit<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= category<sub>i</sub> <= n </code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Stack; Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
|
Python
|
class Solution:
def findMaximumElegance(self, items: List[List[int]], k: int) -> int:
items.sort(key=lambda x: -x[0])
tot = 0
vis = set()
dup = []
for p, c in items[:k]:
tot += p
if c not in vis:
vis.add(c)
else:
dup.append(p)
ans = tot + len(vis) ** 2
for p, c in items[k:]:
if c in vis or not dup:
continue
vis.add(c)
tot += p - dup.pop()
ans = max(ans, tot + len(vis) ** 2)
return ans
|
2,813
|
Maximum Elegance of a K-Length Subsequence
|
Hard
|
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>items</code> of length <code>n</code> and an integer <code>k</code>.</p>
<p><code>items[i] = [profit<sub>i</sub>, category<sub>i</sub>]</code>, where <code>profit<sub>i</sub></code> and <code>category<sub>i</sub></code> denote the profit and category of the <code>i<sup>th</sup></code> item respectively.</p>
<p>Let's define the <strong>elegance</strong> of a <strong>subsequence</strong> of <code>items</code> as <code>total_profit + distinct_categories<sup>2</sup></code>, where <code>total_profit</code> is the sum of all profits in the subsequence, and <code>distinct_categories</code> is the number of <strong>distinct</strong> categories from all the categories in the selected subsequence.</p>
<p>Your task is to find the <strong>maximum elegance</strong> from all subsequences of size <code>k</code> in <code>items</code>.</p>
<p>Return <em>an integer denoting the maximum elegance of a subsequence of </em><code>items</code><em> with size exactly </em><code>k</code>.</p>
<p><strong>Note:</strong> A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,2],[5,1],[10,1]], k = 2
<strong>Output:</strong> 17
<strong>Explanation: </strong>In this example, we have to select a subsequence of size 2.
We can select items[0] = [3,2] and items[2] = [10,1].
The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].
Hence, the elegance is 13 + 2<sup>2</sup> = 17, and we can show that it is the maximum achievable elegance.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> items = [[3,1],[3,1],[2,2],[5,3]], k = 3
<strong>Output:</strong> 19
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3].
The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3].
Hence, the elegance is 10 + 3<sup>2</sup> = 19, and we can show that it is the maximum achievable elegance.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> items = [[1,1],[2,1],[3,1]], k = 3
<strong>Output:</strong> 7
<strong>Explanation:</strong> In this example, we have to select a subsequence of size 3.
We should select all the items.
The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1].
Hence, the maximum elegance is 6 + 1<sup>2</sup> = 7. </pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= items.length == n <= 10<sup>5</sup></code></li>
<li><code>items[i].length == 2</code></li>
<li><code>items[i][0] == profit<sub>i</sub></code></li>
<li><code>items[i][1] == category<sub>i</sub></code></li>
<li><code>1 <= profit<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= category<sub>i</sub> <= n </code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Stack; Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
|
TypeScript
|
function findMaximumElegance(items: number[][], k: number): number {
items.sort((a, b) => b[0] - a[0]);
let tot = 0;
const vis: Set<number> = new Set();
const dup: number[] = [];
for (const [p, c] of items.slice(0, k)) {
tot += p;
if (vis.has(c)) {
dup.push(p);
} else {
vis.add(c);
}
}
let ans = tot + vis.size ** 2;
for (const [p, c] of items.slice(k)) {
if (vis.has(c) || dup.length === 0) {
continue;
}
tot += p - dup.pop()!;
vis.add(c);
ans = Math.max(ans, tot + vis.size ** 2);
}
return ans;
}
|
2,814
|
Minimum Time Takes to Reach Destination Without Drowning
|
Hard
|
<p>You are given an <code>n * m</code> <strong>0-indexed</strong> grid of string <code>land</code>. Right now, you are standing at the cell that contains <code>"S"</code>, and you want to get to the cell containing <code>"D"</code>. There are three other types of cells in this land:</p>
<ul>
<li><code>"."</code>: These cells are empty.</li>
<li><code>"X"</code>: These cells are stone.</li>
<li><code>"*"</code>: These cells are flooded.</li>
</ul>
<p>At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every <strong>empty cell</strong> that shares a side with a flooded cell becomes flooded as well.<br />
There are two problems ahead of your journey:</p>
<ul>
<li>You can't step on stone cells.</li>
<li>You can't step on flooded cells since you will drown (also, you can't step on a cell that will be flooded at the same time as you step on it).</li>
</ul>
<p>Return<em> the <strong>minimum</strong> time it takes you to reach the destination in seconds, or </em><code>-1</code><em> if it is impossible.</em></p>
<p><strong>Note</strong> that the destination will never be flooded.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".","*"],[".",".","."],[".","S","."]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state and picture (3) shows the final state when we reach destination. As you see, it takes us 3 second to reach destination and the answer would be 3.
It can be shown that 3 is the minimum time needed to reach from S to D.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex1.png" style="padding: 5px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 111px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> land = [["D","X","*"],[".",".","."],[".",".","S"]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state. As you see, no matter which paths we choose, we will drown at the 3<sup>rd</sup> second. Also the minimum path takes us 4 seconds to reach from S to D.
So the answer would be -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex2-2.png" style="padding: 7px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 107px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".",".",".","*","."],[".","X",".","X",".","."],[".",".",".",".","S","."]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> It can be shown that we can reach destination in 6 seconds. Also it can be shown that 6 is the minimum seconds one need to reach from S to D.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 100</code></li>
<li><code>land</code> consists only of <code>"S"</code>, <code>"D"</code>, <code>"."</code>, <code>"*"</code> and <code>"X"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"S"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"D"</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
C++
|
class Solution {
public:
int minimumSeconds(vector<vector<string>>& land) {
int m = land.size(), n = land[0].size();
bool vis[m][n];
int g[m][n];
memset(vis, false, sizeof(vis));
memset(g, 0x3f, sizeof(g));
queue<pair<int, int>> q;
int si = 0, sj = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
auto c = land[i][j];
if (c == "*") {
q.emplace(i, j);
} else if (c == "S") {
si = i;
sj = j;
}
}
}
int dirs[5] = {-1, 0, 1, 0, -1};
for (int t = 0; !q.empty(); ++t) {
for (int k = q.size(); k; --k) {
auto [i, j] = q.front();
q.pop();
g[i][j] = t;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
bool empty = land[x][y] == ".";
bool start = land[x][y] == "S";
if (empty || start) {
vis[x][y] = true;
q.emplace(x, y);
}
}
}
}
}
q.emplace(si, sj);
memset(vis, false, sizeof(vis));
vis[si][sj] = true;
for (int t = 0; !q.empty(); ++t) {
for (int k = q.size(); k; --k) {
auto [i, j] = q.front();
q.pop();
if (land[i][j] == "D") {
return t;
}
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && g[x][y] > t + 1) {
bool empty = land[x][y] == ".";
bool dest = land[x][y] == "D";
if (empty || dest) {
vis[x][y] = true;
q.emplace(x, y);
}
}
}
}
}
return -1;
}
};
|
2,814
|
Minimum Time Takes to Reach Destination Without Drowning
|
Hard
|
<p>You are given an <code>n * m</code> <strong>0-indexed</strong> grid of string <code>land</code>. Right now, you are standing at the cell that contains <code>"S"</code>, and you want to get to the cell containing <code>"D"</code>. There are three other types of cells in this land:</p>
<ul>
<li><code>"."</code>: These cells are empty.</li>
<li><code>"X"</code>: These cells are stone.</li>
<li><code>"*"</code>: These cells are flooded.</li>
</ul>
<p>At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every <strong>empty cell</strong> that shares a side with a flooded cell becomes flooded as well.<br />
There are two problems ahead of your journey:</p>
<ul>
<li>You can't step on stone cells.</li>
<li>You can't step on flooded cells since you will drown (also, you can't step on a cell that will be flooded at the same time as you step on it).</li>
</ul>
<p>Return<em> the <strong>minimum</strong> time it takes you to reach the destination in seconds, or </em><code>-1</code><em> if it is impossible.</em></p>
<p><strong>Note</strong> that the destination will never be flooded.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".","*"],[".",".","."],[".","S","."]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state and picture (3) shows the final state when we reach destination. As you see, it takes us 3 second to reach destination and the answer would be 3.
It can be shown that 3 is the minimum time needed to reach from S to D.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex1.png" style="padding: 5px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 111px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> land = [["D","X","*"],[".",".","."],[".",".","S"]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state. As you see, no matter which paths we choose, we will drown at the 3<sup>rd</sup> second. Also the minimum path takes us 4 seconds to reach from S to D.
So the answer would be -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex2-2.png" style="padding: 7px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 107px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".",".",".","*","."],[".","X",".","X",".","."],[".",".",".",".","S","."]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> It can be shown that we can reach destination in 6 seconds. Also it can be shown that 6 is the minimum seconds one need to reach from S to D.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 100</code></li>
<li><code>land</code> consists only of <code>"S"</code>, <code>"D"</code>, <code>"."</code>, <code>"*"</code> and <code>"X"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"S"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"D"</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Go
|
func minimumSeconds(land [][]string) int {
m, n := len(land), len(land[0])
vis := make([][]bool, m)
g := make([][]int, m)
q := [][2]int{}
var si, sj int
for i, row := range land {
vis[i] = make([]bool, n)
g[i] = make([]int, n)
for j := range g[i] {
g[i][j] = 1 << 30
}
for j, c := range row {
if c == "*" {
q = append(q, [2]int{i, j})
} else if c == "S" {
si, sj = i, j
}
}
}
dirs := [5]int{-1, 0, 1, 0, -1}
for t := 0; len(q) > 0; t++ {
for k := len(q); k > 0; k-- {
p := q[0]
q = q[1:]
i, j := p[0], p[1]
g[i][j] = t
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] {
empty := land[x][y] == "."
start := land[x][y] == "S"
if empty || start {
vis[x][y] = true
q = append(q, [2]int{x, y})
}
}
}
}
}
q = append(q, [2]int{si, sj})
vis = make([][]bool, m)
for i := range vis {
vis[i] = make([]bool, n)
}
vis[si][sj] = true
for t := 0; len(q) > 0; t++ {
for k := len(q); k > 0; k-- {
p := q[0]
q = q[1:]
i, j := p[0], p[1]
if land[i][j] == "D" {
return t
}
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && g[x][y] > t+1 {
empty := land[x][y] == "."
dest := land[x][y] == "D"
if empty || dest {
vis[x][y] = true
q = append(q, [2]int{x, y})
}
}
}
}
}
return -1
}
|
2,814
|
Minimum Time Takes to Reach Destination Without Drowning
|
Hard
|
<p>You are given an <code>n * m</code> <strong>0-indexed</strong> grid of string <code>land</code>. Right now, you are standing at the cell that contains <code>"S"</code>, and you want to get to the cell containing <code>"D"</code>. There are three other types of cells in this land:</p>
<ul>
<li><code>"."</code>: These cells are empty.</li>
<li><code>"X"</code>: These cells are stone.</li>
<li><code>"*"</code>: These cells are flooded.</li>
</ul>
<p>At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every <strong>empty cell</strong> that shares a side with a flooded cell becomes flooded as well.<br />
There are two problems ahead of your journey:</p>
<ul>
<li>You can't step on stone cells.</li>
<li>You can't step on flooded cells since you will drown (also, you can't step on a cell that will be flooded at the same time as you step on it).</li>
</ul>
<p>Return<em> the <strong>minimum</strong> time it takes you to reach the destination in seconds, or </em><code>-1</code><em> if it is impossible.</em></p>
<p><strong>Note</strong> that the destination will never be flooded.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".","*"],[".",".","."],[".","S","."]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state and picture (3) shows the final state when we reach destination. As you see, it takes us 3 second to reach destination and the answer would be 3.
It can be shown that 3 is the minimum time needed to reach from S to D.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex1.png" style="padding: 5px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 111px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> land = [["D","X","*"],[".",".","."],[".",".","S"]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state. As you see, no matter which paths we choose, we will drown at the 3<sup>rd</sup> second. Also the minimum path takes us 4 seconds to reach from S to D.
So the answer would be -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex2-2.png" style="padding: 7px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 107px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".",".",".","*","."],[".","X",".","X",".","."],[".",".",".",".","S","."]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> It can be shown that we can reach destination in 6 seconds. Also it can be shown that 6 is the minimum seconds one need to reach from S to D.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 100</code></li>
<li><code>land</code> consists only of <code>"S"</code>, <code>"D"</code>, <code>"."</code>, <code>"*"</code> and <code>"X"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"S"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"D"</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Java
|
class Solution {
public int minimumSeconds(List<List<String>> land) {
int m = land.size(), n = land.get(0).size();
boolean[][] vis = new boolean[m][n];
int[][] g = new int[m][n];
Deque<int[]> q = new ArrayDeque<>();
int si = 0, sj = 0;
for (int i = 0; i < m; ++i) {
Arrays.fill(g[i], 1 << 30);
for (int j = 0; j < n; ++j) {
String c = land.get(i).get(j);
if ("*".equals(c)) {
q.offer(new int[] {i, j});
} else if ("S".equals(c)) {
si = i;
sj = j;
}
}
}
int[] dirs = {-1, 0, 1, 0, -1};
for (int t = 0; !q.isEmpty(); ++t) {
for (int k = q.size(); k > 0; --k) {
int[] p = q.poll();
int i = p[0], j = p[1];
g[i][j] = t;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
boolean empty = ".".equals(land.get(x).get(y));
boolean start = "S".equals(land.get(x).get(y));
if (empty || start) {
vis[x][y] = true;
q.offer(new int[] {x, y});
}
}
}
}
}
q.offer(new int[] {si, sj});
vis = new boolean[m][n];
vis[si][sj] = true;
for (int t = 0; !q.isEmpty(); ++t) {
for (int k = q.size(); k > 0; --k) {
int[] p = q.poll();
int i = p[0], j = p[1];
if ("D".equals(land.get(i).get(j))) {
return t;
}
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && g[x][y] > t + 1) {
boolean empty = ".".equals(land.get(x).get(y));
boolean dest = "D".equals(land.get(x).get(y));
if (empty || dest) {
vis[x][y] = true;
q.offer(new int[] {x, y});
}
}
}
}
}
return -1;
}
}
|
2,814
|
Minimum Time Takes to Reach Destination Without Drowning
|
Hard
|
<p>You are given an <code>n * m</code> <strong>0-indexed</strong> grid of string <code>land</code>. Right now, you are standing at the cell that contains <code>"S"</code>, and you want to get to the cell containing <code>"D"</code>. There are three other types of cells in this land:</p>
<ul>
<li><code>"."</code>: These cells are empty.</li>
<li><code>"X"</code>: These cells are stone.</li>
<li><code>"*"</code>: These cells are flooded.</li>
</ul>
<p>At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every <strong>empty cell</strong> that shares a side with a flooded cell becomes flooded as well.<br />
There are two problems ahead of your journey:</p>
<ul>
<li>You can't step on stone cells.</li>
<li>You can't step on flooded cells since you will drown (also, you can't step on a cell that will be flooded at the same time as you step on it).</li>
</ul>
<p>Return<em> the <strong>minimum</strong> time it takes you to reach the destination in seconds, or </em><code>-1</code><em> if it is impossible.</em></p>
<p><strong>Note</strong> that the destination will never be flooded.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".","*"],[".",".","."],[".","S","."]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state and picture (3) shows the final state when we reach destination. As you see, it takes us 3 second to reach destination and the answer would be 3.
It can be shown that 3 is the minimum time needed to reach from S to D.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex1.png" style="padding: 5px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 111px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> land = [["D","X","*"],[".",".","."],[".",".","S"]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state. As you see, no matter which paths we choose, we will drown at the 3<sup>rd</sup> second. Also the minimum path takes us 4 seconds to reach from S to D.
So the answer would be -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex2-2.png" style="padding: 7px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 107px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".",".",".","*","."],[".","X",".","X",".","."],[".",".",".",".","S","."]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> It can be shown that we can reach destination in 6 seconds. Also it can be shown that 6 is the minimum seconds one need to reach from S to D.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 100</code></li>
<li><code>land</code> consists only of <code>"S"</code>, <code>"D"</code>, <code>"."</code>, <code>"*"</code> and <code>"X"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"S"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"D"</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
Python
|
class Solution:
def minimumSeconds(self, land: List[List[str]]) -> int:
m, n = len(land), len(land[0])
vis = [[False] * n for _ in range(m)]
g = [[inf] * n for _ in range(m)]
q = deque()
si = sj = 0
for i, row in enumerate(land):
for j, c in enumerate(row):
match c:
case "*":
q.append((i, j))
case "S":
si, sj = i, j
dirs = (-1, 0, 1, 0, -1)
t = 0
while q:
for _ in range(len(q)):
i, j = q.popleft()
g[i][j] = t
for a, b in pairwise(dirs):
x, y = i + a, j + b
if (
0 <= x < m
and 0 <= y < n
and not vis[x][y]
and land[x][y] in ".S"
):
vis[x][y] = True
q.append((x, y))
t += 1
t = 0
q = deque([(si, sj)])
vis = [[False] * n for _ in range(m)]
vis[si][sj] = True
while q:
for _ in range(len(q)):
i, j = q.popleft()
if land[i][j] == "D":
return t
for a, b in pairwise(dirs):
x, y = i + a, j + b
if (
0 <= x < m
and 0 <= y < n
and g[x][y] > t + 1
and not vis[x][y]
and land[x][y] in ".D"
):
vis[x][y] = True
q.append((x, y))
t += 1
return -1
|
2,814
|
Minimum Time Takes to Reach Destination Without Drowning
|
Hard
|
<p>You are given an <code>n * m</code> <strong>0-indexed</strong> grid of string <code>land</code>. Right now, you are standing at the cell that contains <code>"S"</code>, and you want to get to the cell containing <code>"D"</code>. There are three other types of cells in this land:</p>
<ul>
<li><code>"."</code>: These cells are empty.</li>
<li><code>"X"</code>: These cells are stone.</li>
<li><code>"*"</code>: These cells are flooded.</li>
</ul>
<p>At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every <strong>empty cell</strong> that shares a side with a flooded cell becomes flooded as well.<br />
There are two problems ahead of your journey:</p>
<ul>
<li>You can't step on stone cells.</li>
<li>You can't step on flooded cells since you will drown (also, you can't step on a cell that will be flooded at the same time as you step on it).</li>
</ul>
<p>Return<em> the <strong>minimum</strong> time it takes you to reach the destination in seconds, or </em><code>-1</code><em> if it is impossible.</em></p>
<p><strong>Note</strong> that the destination will never be flooded.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".","*"],[".",".","."],[".","S","."]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state and picture (3) shows the final state when we reach destination. As you see, it takes us 3 second to reach destination and the answer would be 3.
It can be shown that 3 is the minimum time needed to reach from S to D.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex1.png" style="padding: 5px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 111px;" /></p>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> land = [["D","X","*"],[".",".","."],[".",".","S"]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The picture below shows the simulation of the land second by second. The blue cells are flooded, and the gray cells are stone.
Picture (0) shows the initial state. As you see, no matter which paths we choose, we will drown at the 3<sup>rd</sup> second. Also the minimum path takes us 4 seconds to reach from S to D.
So the answer would be -1.
</pre>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2814.Minimum%20Time%20Takes%20to%20Reach%20Destination%20Without%20Drowning/images/ex2-2.png" style="padding: 7px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 600px; height: 107px;" /></p>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> land = [["D",".",".",".","*","."],[".","X",".","X",".","."],[".",".",".",".","S","."]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> It can be shown that we can reach destination in 6 seconds. Also it can be shown that 6 is the minimum seconds one need to reach from S to D.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n, m <= 100</code></li>
<li><code>land</code> consists only of <code>"S"</code>, <code>"D"</code>, <code>"."</code>, <code>"*"</code> and <code>"X"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"S"</code>.</li>
<li><strong>Exactly</strong> one of the cells is equal to <code>"D"</code>.</li>
</ul>
|
Breadth-First Search; Array; Matrix
|
TypeScript
|
function minimumSeconds(land: string[][]): number {
const m = land.length;
const n = land[0].length;
const g: number[][] = Array(m)
.fill(0)
.map(() => Array(n).fill(1 << 30));
const vis: boolean[][] = Array(m)
.fill(0)
.map(() => Array(n).fill(false));
const q: number[][] = [];
let [si, sj] = [0, 0];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
const c = land[i][j];
if (c === '*') {
q.push([i, j]);
} else if (c === 'S') {
[si, sj] = [i, j];
}
}
}
const dirs = [-1, 0, 1, 0, -1];
for (let t = 0; q.length; ++t) {
for (let k = q.length; k; --k) {
const [i, j] = q.shift()!;
g[i][j] = t;
for (let d = 0; d < 4; ++d) {
const [x, y] = [i + dirs[d], j + dirs[d + 1]];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && 'S.'.includes(land[x][y])) {
vis[x][y] = true;
q.push([x, y]);
}
}
}
}
q.push([si, sj]);
for (let i = 0; i < m; ++i) {
vis[i].fill(false);
}
vis[si][sj] = true;
for (let t = 0; q.length; ++t) {
for (let k = q.length; k; --k) {
const [i, j] = q.shift()!;
if (land[i][j] === 'D') {
return t;
}
for (let d = 0; d < 4; ++d) {
const [x, y] = [i + dirs[d], j + dirs[d + 1]];
if (
x >= 0 &&
x < m &&
y >= 0 &&
y < n &&
!vis[x][y] &&
g[x][y] > t + 1 &&
'D.'.includes(land[x][y]) &&
t + 1 < g[x][y]
) {
vis[x][y] = true;
q.push([x, y]);
}
}
}
}
return -1;
}
|
2,815
|
Max Pair Sum in an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>. You have to find the <strong>maximum</strong> sum of a pair of numbers from <code>nums</code> such that the <strong>largest digit </strong>in both numbers is equal.</p>
<p>For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.</p>
<p>Return the <strong>maximum</strong> sum or -1 if no such pair exists.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [112,131,411]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>Each numbers largest digit in order is [2,3,4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2536,1613,3366,162]</span></p>
<p><strong>Output:</strong> <span class="example-io">5902</span></p>
<p><strong>Explanation:</strong></p>
<p>All the numbers have 6 as their largest digit, so the answer is <span class="example-io">2536 + 3366 = 5902.</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [51,71,17,24,42]</span></p>
<p><strong>Output:</strong> <span class="example-io">88</span></p>
<p><strong>Explanation:</strong></p>
<p>Each number's largest digit in order is [5,7,7,4,4].</p>
<p>So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int maxSum(vector<int>& nums) {
int ans = -1;
int n = nums.size();
auto f = [](int x) {
int y = 0;
for (; x; x /= 10) {
y = max(y, x % 10);
}
return y;
};
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int v = nums[i] + nums[j];
if (ans < v && f(nums[i]) == f(nums[j])) {
ans = v;
}
}
}
return ans;
}
};
|
2,815
|
Max Pair Sum in an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>. You have to find the <strong>maximum</strong> sum of a pair of numbers from <code>nums</code> such that the <strong>largest digit </strong>in both numbers is equal.</p>
<p>For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.</p>
<p>Return the <strong>maximum</strong> sum or -1 if no such pair exists.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [112,131,411]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>Each numbers largest digit in order is [2,3,4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2536,1613,3366,162]</span></p>
<p><strong>Output:</strong> <span class="example-io">5902</span></p>
<p><strong>Explanation:</strong></p>
<p>All the numbers have 6 as their largest digit, so the answer is <span class="example-io">2536 + 3366 = 5902.</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [51,71,17,24,42]</span></p>
<p><strong>Output:</strong> <span class="example-io">88</span></p>
<p><strong>Explanation:</strong></p>
<p>Each number's largest digit in order is [5,7,7,4,4].</p>
<p>So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Go
|
func maxSum(nums []int) int {
ans := -1
f := func(x int) int {
y := 0
for ; x > 0; x /= 10 {
y = max(y, x%10)
}
return y
}
for i, x := range nums {
for _, y := range nums[i+1:] {
if v := x + y; ans < v && f(x) == f(y) {
ans = v
}
}
}
return ans
}
|
2,815
|
Max Pair Sum in an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>. You have to find the <strong>maximum</strong> sum of a pair of numbers from <code>nums</code> such that the <strong>largest digit </strong>in both numbers is equal.</p>
<p>For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.</p>
<p>Return the <strong>maximum</strong> sum or -1 if no such pair exists.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [112,131,411]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>Each numbers largest digit in order is [2,3,4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2536,1613,3366,162]</span></p>
<p><strong>Output:</strong> <span class="example-io">5902</span></p>
<p><strong>Explanation:</strong></p>
<p>All the numbers have 6 as their largest digit, so the answer is <span class="example-io">2536 + 3366 = 5902.</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [51,71,17,24,42]</span></p>
<p><strong>Output:</strong> <span class="example-io">88</span></p>
<p><strong>Explanation:</strong></p>
<p>Each number's largest digit in order is [5,7,7,4,4].</p>
<p>So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int maxSum(int[] nums) {
int ans = -1;
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int v = nums[i] + nums[j];
if (ans < v && f(nums[i]) == f(nums[j])) {
ans = v;
}
}
}
return ans;
}
private int f(int x) {
int y = 0;
for (; x > 0; x /= 10) {
y = Math.max(y, x % 10);
}
return y;
}
}
|
2,815
|
Max Pair Sum in an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>. You have to find the <strong>maximum</strong> sum of a pair of numbers from <code>nums</code> such that the <strong>largest digit </strong>in both numbers is equal.</p>
<p>For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.</p>
<p>Return the <strong>maximum</strong> sum or -1 if no such pair exists.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [112,131,411]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>Each numbers largest digit in order is [2,3,4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2536,1613,3366,162]</span></p>
<p><strong>Output:</strong> <span class="example-io">5902</span></p>
<p><strong>Explanation:</strong></p>
<p>All the numbers have 6 as their largest digit, so the answer is <span class="example-io">2536 + 3366 = 5902.</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [51,71,17,24,42]</span></p>
<p><strong>Output:</strong> <span class="example-io">88</span></p>
<p><strong>Explanation:</strong></p>
<p>Each number's largest digit in order is [5,7,7,4,4].</p>
<p>So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def maxSum(self, nums: List[int]) -> int:
ans = -1
for i, x in enumerate(nums):
for y in nums[i + 1 :]:
v = x + y
if ans < v and max(str(x)) == max(str(y)):
ans = v
return ans
|
2,815
|
Max Pair Sum in an Array
|
Easy
|
<p>You are given an integer array <code>nums</code>. You have to find the <strong>maximum</strong> sum of a pair of numbers from <code>nums</code> such that the <strong>largest digit </strong>in both numbers is equal.</p>
<p>For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.</p>
<p>Return the <strong>maximum</strong> sum or -1 if no such pair exists.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [112,131,411]</span></p>
<p><strong>Output:</strong> <span class="example-io">-1</span></p>
<p><strong>Explanation:</strong></p>
<p>Each numbers largest digit in order is [2,3,4].</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2536,1613,3366,162]</span></p>
<p><strong>Output:</strong> <span class="example-io">5902</span></p>
<p><strong>Explanation:</strong></p>
<p>All the numbers have 6 as their largest digit, so the answer is <span class="example-io">2536 + 3366 = 5902.</span></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [51,71,17,24,42]</span></p>
<p><strong>Output:</strong> <span class="example-io">88</span></p>
<p><strong>Explanation:</strong></p>
<p>Each number's largest digit in order is [5,7,7,4,4].</p>
<p>So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10<sup>4</sup></code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function maxSum(nums: number[]): number {
const n = nums.length;
let ans = -1;
const f = (x: number): number => {
let y = 0;
for (; x > 0; x = Math.floor(x / 10)) {
y = Math.max(y, x % 10);
}
return y;
};
for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
const v = nums[i] + nums[j];
if (ans < v && f(nums[i]) === f(nums[j])) {
ans = v;
}
}
}
return ans;
}
|
2,816
|
Double a Number Represented as a Linked List
|
Medium
|
<p>You are given the <code>head</code> of a <strong>non-empty</strong> linked list representing a non-negative integer without leading zeroes.</p>
<p>Return <em>the </em><code>head</code><em> of the linked list after <strong>doubling</strong> it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [1,8,9]
<strong>Output:</strong> [3,7,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example2.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [9,9,9]
<strong>Output:</strong> [1,9,9,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>4</sup>]</code></li>
<li><font face="monospace"><code>0 <= Node.val <= 9</code></font></li>
<li>The input is generated such that the list represents a number that does not have leading zeros, except the number <code>0</code> itself.</li>
</ul>
|
Stack; Linked List; Math
|
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* doubleIt(ListNode* head) {
head = reverse(head);
ListNode* dummy = new ListNode();
ListNode* cur = dummy;
int mul = 2, carry = 0;
while (head) {
int x = head->val * mul + carry;
carry = x / 10;
cur->next = new ListNode(x % 10);
cur = cur->next;
head = head->next;
}
if (carry) {
cur->next = new ListNode(carry);
}
return reverse(dummy->next);
}
ListNode* reverse(ListNode* head) {
ListNode* dummy = new ListNode();
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = dummy->next;
dummy->next = cur;
cur = next;
}
return dummy->next;
}
};
|
2,816
|
Double a Number Represented as a Linked List
|
Medium
|
<p>You are given the <code>head</code> of a <strong>non-empty</strong> linked list representing a non-negative integer without leading zeroes.</p>
<p>Return <em>the </em><code>head</code><em> of the linked list after <strong>doubling</strong> it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [1,8,9]
<strong>Output:</strong> [3,7,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example2.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [9,9,9]
<strong>Output:</strong> [1,9,9,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>4</sup>]</code></li>
<li><font face="monospace"><code>0 <= Node.val <= 9</code></font></li>
<li>The input is generated such that the list represents a number that does not have leading zeros, except the number <code>0</code> itself.</li>
</ul>
|
Stack; Linked List; Math
|
Go
|
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func doubleIt(head *ListNode) *ListNode {
head = reverse(head)
dummy := &ListNode{}
cur := dummy
mul, carry := 2, 0
for head != nil {
x := head.Val*mul + carry
carry = x / 10
cur.Next = &ListNode{Val: x % 10}
cur = cur.Next
head = head.Next
}
if carry > 0 {
cur.Next = &ListNode{Val: carry}
}
return reverse(dummy.Next)
}
func reverse(head *ListNode) *ListNode {
dummy := &ListNode{}
cur := head
for cur != nil {
next := cur.Next
cur.Next = dummy.Next
dummy.Next = cur
cur = next
}
return dummy.Next
}
|
2,816
|
Double a Number Represented as a Linked List
|
Medium
|
<p>You are given the <code>head</code> of a <strong>non-empty</strong> linked list representing a non-negative integer without leading zeroes.</p>
<p>Return <em>the </em><code>head</code><em> of the linked list after <strong>doubling</strong> it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [1,8,9]
<strong>Output:</strong> [3,7,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example2.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [9,9,9]
<strong>Output:</strong> [1,9,9,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>4</sup>]</code></li>
<li><font face="monospace"><code>0 <= Node.val <= 9</code></font></li>
<li>The input is generated such that the list represents a number that does not have leading zeros, except the number <code>0</code> itself.</li>
</ul>
|
Stack; Linked List; Math
|
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 doubleIt(ListNode head) {
head = reverse(head);
ListNode dummy = new ListNode();
ListNode cur = dummy;
int mul = 2, carry = 0;
while (head != null) {
int x = head.val * mul + carry;
carry = x / 10;
cur.next = new ListNode(x % 10);
cur = cur.next;
head = head.next;
}
if (carry > 0) {
cur.next = new ListNode(carry);
}
return reverse(dummy.next);
}
private ListNode reverse(ListNode head) {
ListNode dummy = new ListNode();
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = next;
}
return dummy.next;
}
}
|
2,816
|
Double a Number Represented as a Linked List
|
Medium
|
<p>You are given the <code>head</code> of a <strong>non-empty</strong> linked list representing a non-negative integer without leading zeroes.</p>
<p>Return <em>the </em><code>head</code><em> of the linked list after <strong>doubling</strong> it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [1,8,9]
<strong>Output:</strong> [3,7,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example2.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [9,9,9]
<strong>Output:</strong> [1,9,9,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>4</sup>]</code></li>
<li><font face="monospace"><code>0 <= Node.val <= 9</code></font></li>
<li>The input is generated such that the list represents a number that does not have leading zeros, except the number <code>0</code> itself.</li>
</ul>
|
Stack; Linked List; Math
|
Python
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(head):
dummy = ListNode()
cur = head
while cur:
next = cur.next
cur.next = dummy.next
dummy.next = cur
cur = next
return dummy.next
head = reverse(head)
dummy = cur = ListNode()
mul, carry = 2, 0
while head:
x = head.val * mul + carry
carry = x // 10
cur.next = ListNode(x % 10)
cur = cur.next
head = head.next
if carry:
cur.next = ListNode(carry)
return reverse(dummy.next)
|
2,816
|
Double a Number Represented as a Linked List
|
Medium
|
<p>You are given the <code>head</code> of a <strong>non-empty</strong> linked list representing a non-negative integer without leading zeroes.</p>
<p>Return <em>the </em><code>head</code><em> of the linked list after <strong>doubling</strong> it</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [1,8,9]
<strong>Output:</strong> [3,7,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/images/example2.png" style="width: 401px; height: 81px;" />
<pre>
<strong>Input:</strong> head = [9,9,9]
<strong>Output:</strong> [1,9,9,8]
<strong>Explanation:</strong> The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the list is in the range <code>[1, 10<sup>4</sup>]</code></li>
<li><font face="monospace"><code>0 <= Node.val <= 9</code></font></li>
<li>The input is generated such that the list represents a number that does not have leading zeros, except the number <code>0</code> itself.</li>
</ul>
|
Stack; Linked List; Math
|
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 doubleIt(head: ListNode | null): ListNode | null {
head = reverse(head);
const dummy = new ListNode();
let cur = dummy;
let mul = 2;
let carry = 0;
while (head) {
const x = head.val * mul + carry;
carry = Math.floor(x / 10);
cur.next = new ListNode(x % 10);
cur = cur.next;
head = head.next;
}
if (carry) {
cur.next = new ListNode(carry);
}
return reverse(dummy.next);
}
function reverse(head: ListNode | null): ListNode | null {
const dummy = new ListNode();
let cur = head;
while (cur) {
const next = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = next;
}
return dummy.next;
}
|
2,817
|
Minimum Absolute Difference Between Elements With Constraint
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>x</code>.</p>
<p>Find the <strong>minimum absolute difference</strong> between two elements in the array that are at least <code>x</code> indices apart.</p>
<p>In other words, find two indices <code>i</code> and <code>j</code> such that <code>abs(i - j) >= x</code> and <code>abs(nums[i] - nums[j])</code> is minimized.</p>
<p>Return<em> an integer denoting the <strong>minimum</strong> absolute difference between two elements that are at least</em> <code>x</code> <em>indices apart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,2,4], x = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,2,10,15], x = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4], x = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= x < nums.length</code></li>
</ul>
|
Array; Binary Search; Ordered Set
|
C++
|
class Solution {
public:
int minAbsoluteDifference(vector<int>& nums, int x) {
int ans = 1 << 30;
multiset<int> s;
for (int i = x; i < nums.size(); ++i) {
s.insert(nums[i - x]);
auto it = s.lower_bound(nums[i]);
if (it != s.end()) {
ans = min(ans, *it - nums[i]);
}
if (it != s.begin()) {
--it;
ans = min(ans, nums[i] - *it);
}
}
return ans;
}
};
|
2,817
|
Minimum Absolute Difference Between Elements With Constraint
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>x</code>.</p>
<p>Find the <strong>minimum absolute difference</strong> between two elements in the array that are at least <code>x</code> indices apart.</p>
<p>In other words, find two indices <code>i</code> and <code>j</code> such that <code>abs(i - j) >= x</code> and <code>abs(nums[i] - nums[j])</code> is minimized.</p>
<p>Return<em> an integer denoting the <strong>minimum</strong> absolute difference between two elements that are at least</em> <code>x</code> <em>indices apart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,2,4], x = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,2,10,15], x = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4], x = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= x < nums.length</code></li>
</ul>
|
Array; Binary Search; Ordered Set
|
Go
|
func minAbsoluteDifference(nums []int, x int) int {
rbt := redblacktree.NewWithIntComparator()
ans := 1 << 30
for i := x; i < len(nums); i++ {
rbt.Put(nums[i-x], nil)
c, _ := rbt.Ceiling(nums[i])
f, _ := rbt.Floor(nums[i])
if c != nil {
ans = min(ans, c.Key.(int)-nums[i])
}
if f != nil {
ans = min(ans, nums[i]-f.Key.(int))
}
}
return ans
}
|
2,817
|
Minimum Absolute Difference Between Elements With Constraint
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>x</code>.</p>
<p>Find the <strong>minimum absolute difference</strong> between two elements in the array that are at least <code>x</code> indices apart.</p>
<p>In other words, find two indices <code>i</code> and <code>j</code> such that <code>abs(i - j) >= x</code> and <code>abs(nums[i] - nums[j])</code> is minimized.</p>
<p>Return<em> an integer denoting the <strong>minimum</strong> absolute difference between two elements that are at least</em> <code>x</code> <em>indices apart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,2,4], x = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,2,10,15], x = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4], x = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= x < nums.length</code></li>
</ul>
|
Array; Binary Search; Ordered Set
|
Java
|
class Solution {
public int minAbsoluteDifference(List<Integer> nums, int x) {
TreeMap<Integer, Integer> tm = new TreeMap<>();
int ans = 1 << 30;
for (int i = x; i < nums.size(); ++i) {
tm.merge(nums.get(i - x), 1, Integer::sum);
Integer key = tm.ceilingKey(nums.get(i));
if (key != null) {
ans = Math.min(ans, key - nums.get(i));
}
key = tm.floorKey(nums.get(i));
if (key != null) {
ans = Math.min(ans, nums.get(i) - key);
}
}
return ans;
}
}
|
2,817
|
Minimum Absolute Difference Between Elements With Constraint
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>x</code>.</p>
<p>Find the <strong>minimum absolute difference</strong> between two elements in the array that are at least <code>x</code> indices apart.</p>
<p>In other words, find two indices <code>i</code> and <code>j</code> such that <code>abs(i - j) >= x</code> and <code>abs(nums[i] - nums[j])</code> is minimized.</p>
<p>Return<em> an integer denoting the <strong>minimum</strong> absolute difference between two elements that are at least</em> <code>x</code> <em>indices apart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,2,4], x = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,2,10,15], x = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4], x = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= x < nums.length</code></li>
</ul>
|
Array; Binary Search; Ordered Set
|
Python
|
class Solution:
def minAbsoluteDifference(self, nums: List[int], x: int) -> int:
sl = SortedList()
ans = inf
for i in range(x, len(nums)):
sl.add(nums[i - x])
j = bisect_left(sl, nums[i])
if j < len(sl):
ans = min(ans, sl[j] - nums[i])
if j:
ans = min(ans, nums[i] - sl[j - 1])
return ans
|
2,817
|
Minimum Absolute Difference Between Elements With Constraint
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>x</code>.</p>
<p>Find the <strong>minimum absolute difference</strong> between two elements in the array that are at least <code>x</code> indices apart.</p>
<p>In other words, find two indices <code>i</code> and <code>j</code> such that <code>abs(i - j) >= x</code> and <code>abs(nums[i] - nums[j])</code> is minimized.</p>
<p>Return<em> an integer denoting the <strong>minimum</strong> absolute difference between two elements that are at least</em> <code>x</code> <em>indices apart</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,2,4], x = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> We can select nums[0] = 4 and nums[3] = 4.
They are at least 2 indices apart, and their absolute difference is the minimum, 0.
It can be shown that 0 is the optimal answer.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [5,3,2,10,15], x = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4], x = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= x < nums.length</code></li>
</ul>
|
Array; Binary Search; Ordered Set
|
TypeScript
|
function minAbsoluteDifference(nums: number[], x: number): number {
const s = new TreeMultiSet<number>();
const inf = 1 << 30;
let ans = inf;
for (let i = x; i < nums.length; ++i) {
s.add(nums[i - x]);
const c = s.ceil(nums[i]);
const f = s.floor(nums[i]);
if (c) {
ans = Math.min(ans, c - nums[i]);
}
if (f) {
ans = Math.min(ans, nums[i] - f);
}
}
return ans;
}
type Compare<T> = (lhs: T, rhs: T) => number;
class RBTreeNode<T = number> {
data: T;
count: number;
left: RBTreeNode<T> | null;
right: RBTreeNode<T> | null;
parent: RBTreeNode<T> | null;
color: number;
constructor(data: T) {
this.data = data;
this.left = this.right = this.parent = null;
this.color = 0;
this.count = 1;
}
sibling(): RBTreeNode<T> | null {
if (!this.parent) return null; // sibling null if no parent
return this.isOnLeft() ? this.parent.right : this.parent.left;
}
isOnLeft(): boolean {
return this === this.parent!.left;
}
hasRedChild(): boolean {
return (
Boolean(this.left && this.left.color === 0) ||
Boolean(this.right && this.right.color === 0)
);
}
}
class RBTree<T> {
root: RBTreeNode<T> | null;
lt: (l: T, r: T) => boolean;
constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) {
this.root = null;
this.lt = (l: T, r: T) => compare(l, r) < 0;
}
rotateLeft(pt: RBTreeNode<T>): void {
const right = pt.right!;
pt.right = right.left;
if (pt.right) pt.right.parent = pt;
right.parent = pt.parent;
if (!pt.parent) this.root = right;
else if (pt === pt.parent.left) pt.parent.left = right;
else pt.parent.right = right;
right.left = pt;
pt.parent = right;
}
rotateRight(pt: RBTreeNode<T>): void {
const left = pt.left!;
pt.left = left.right;
if (pt.left) pt.left.parent = pt;
left.parent = pt.parent;
if (!pt.parent) this.root = left;
else if (pt === pt.parent.left) pt.parent.left = left;
else pt.parent.right = left;
left.right = pt;
pt.parent = left;
}
swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void {
const tmp = p1.color;
p1.color = p2.color;
p2.color = tmp;
}
swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void {
const tmp = p1.data;
p1.data = p2.data;
p2.data = tmp;
}
fixAfterInsert(pt: RBTreeNode<T>): void {
let parent = null;
let grandParent = null;
while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) {
parent = pt.parent;
grandParent = pt.parent.parent;
/* Case : A
Parent of pt is left child of Grand-parent of pt */
if (parent === grandParent?.left) {
const uncle = grandParent.right;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle && uncle.color === 0) {
grandParent.color = 0;
parent.color = 1;
uncle.color = 1;
pt = grandParent;
} else {
/* Case : 2
pt is right child of its parent
Left-rotation required */
if (pt === parent.right) {
this.rotateLeft(parent);
pt = parent;
parent = pt.parent;
}
/* Case : 3
pt is left child of its parent
Right-rotation required */
this.rotateRight(grandParent);
this.swapColor(parent!, grandParent);
pt = parent!;
}
} else {
/* Case : B
Parent of pt is right child of Grand-parent of pt */
const uncle = grandParent!.left;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle != null && uncle.color === 0) {
grandParent!.color = 0;
parent.color = 1;
uncle.color = 1;
pt = grandParent!;
} else {
/* Case : 2
pt is left child of its parent
Right-rotation required */
if (pt === parent.left) {
this.rotateRight(parent);
pt = parent;
parent = pt.parent;
}
/* Case : 3
pt is right child of its parent
Left-rotation required */
this.rotateLeft(grandParent!);
this.swapColor(parent!, grandParent!);
pt = parent!;
}
}
}
this.root!.color = 1;
}
delete(val: T): boolean {
const node = this.find(val);
if (!node) return false;
node.count--;
if (!node.count) this.deleteNode(node);
return true;
}
deleteAll(val: T): boolean {
const node = this.find(val);
if (!node) return false;
this.deleteNode(node);
return true;
}
deleteNode(v: RBTreeNode<T>): void {
const u = BSTreplace(v);
// True when u and v are both black
const uvBlack = (u === null || u.color === 1) && v.color === 1;
const parent = v.parent!;
if (!u) {
// u is null therefore v is leaf
if (v === this.root) this.root = null;
// v is root, making root null
else {
if (uvBlack) {
// u and v both black
// v is leaf, fix double black at v
this.fixDoubleBlack(v);
} else {
// u or v is red
if (v.sibling()) {
// sibling is not null, make it red"
v.sibling()!.color = 0;
}
}
// delete v from the tree
if (v.isOnLeft()) parent.left = null;
else parent.right = null;
}
return;
}
if (!v.left || !v.right) {
// v has 1 child
if (v === this.root) {
// v is root, assign the value of u to v, and delete u
v.data = u.data;
v.left = v.right = null;
} else {
// Detach v from tree and move u up
if (v.isOnLeft()) parent.left = u;
else parent.right = u;
u.parent = parent;
if (uvBlack) this.fixDoubleBlack(u);
// u and v both black, fix double black at u
else u.color = 1; // u or v red, color u black
}
return;
}
// v has 2 children, swap data with successor and recurse
this.swapData(u, v);
this.deleteNode(u);
// find node that replaces a deleted node in BST
function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null {
// when node have 2 children
if (x.left && x.right) return successor(x.right);
// when leaf
if (!x.left && !x.right) return null;
// when single child
return x.left ?? x.right;
}
// find node that do not have a left child
// in the subtree of the given node
function successor(x: RBTreeNode<T>): RBTreeNode<T> {
let temp = x;
while (temp.left) temp = temp.left;
return temp;
}
}
fixDoubleBlack(x: RBTreeNode<T>): void {
if (x === this.root) return; // Reached root
const sibling = x.sibling();
const parent = x.parent!;
if (!sibling) {
// No sibiling, double black pushed up
this.fixDoubleBlack(parent);
} else {
if (sibling.color === 0) {
// Sibling red
parent.color = 0;
sibling.color = 1;
if (sibling.isOnLeft()) this.rotateRight(parent);
// left case
else this.rotateLeft(parent); // right case
this.fixDoubleBlack(x);
} else {
// Sibling black
if (sibling.hasRedChild()) {
// at least 1 red children
if (sibling.left && sibling.left.color === 0) {
if (sibling.isOnLeft()) {
// left left
sibling.left.color = sibling.color;
sibling.color = parent.color;
this.rotateRight(parent);
} else {
// right left
sibling.left.color = parent.color;
this.rotateRight(sibling);
this.rotateLeft(parent);
}
} else {
if (sibling.isOnLeft()) {
// left right
sibling.right!.color = parent.color;
this.rotateLeft(sibling);
this.rotateRight(parent);
} else {
// right right
sibling.right!.color = sibling.color;
sibling.color = parent.color;
this.rotateLeft(parent);
}
}
parent.color = 1;
} else {
// 2 black children
sibling.color = 0;
if (parent.color === 1) this.fixDoubleBlack(parent);
else parent.color = 1;
}
}
}
}
insert(data: T): boolean {
// search for a position to insert
let parent = this.root;
while (parent) {
if (this.lt(data, parent.data)) {
if (!parent.left) break;
else parent = parent.left;
} else if (this.lt(parent.data, data)) {
if (!parent.right) break;
else parent = parent.right;
} else break;
}
// insert node into parent
const node = new RBTreeNode(data);
if (!parent) this.root = node;
else if (this.lt(node.data, parent.data)) parent.left = node;
else if (this.lt(parent.data, node.data)) parent.right = node;
else {
parent.count++;
return false;
}
node.parent = parent;
this.fixAfterInsert(node);
return true;
}
find(data: T): RBTreeNode<T> | null {
let p = this.root;
while (p) {
if (this.lt(data, p.data)) {
p = p.left;
} else if (this.lt(p.data, data)) {
p = p.right;
} else break;
}
return p ?? null;
}
*inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> {
if (!root) return;
for (const v of this.inOrder(root.left!)) yield v;
yield root.data;
for (const v of this.inOrder(root.right!)) yield v;
}
*reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> {
if (!root) return;
for (const v of this.reverseInOrder(root.right!)) yield v;
yield root.data;
for (const v of this.reverseInOrder(root.left!)) yield v;
}
}
class TreeMultiSet<T = number> {
_size: number;
tree: RBTree<T>;
compare: Compare<T>;
constructor(
collection: T[] | Compare<T> = [],
compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0),
) {
if (typeof collection === 'function') {
compare = collection;
collection = [];
}
this._size = 0;
this.compare = compare;
this.tree = new RBTree(compare);
for (const val of collection) this.add(val);
}
size(): number {
return this._size;
}
has(val: T): boolean {
return !!this.tree.find(val);
}
add(val: T): boolean {
const successful = this.tree.insert(val);
this._size++;
return successful;
}
delete(val: T): boolean {
const successful = this.tree.delete(val);
if (!successful) return false;
this._size--;
return true;
}
count(val: T): number {
const node = this.tree.find(val);
return node ? node.count : 0;
}
ceil(val: T): T | undefined {
let p = this.tree.root;
let higher = null;
while (p) {
if (this.compare(p.data, val) >= 0) {
higher = p;
p = p.left;
} else {
p = p.right;
}
}
return higher?.data;
}
floor(val: T): T | undefined {
let p = this.tree.root;
let lower = null;
while (p) {
if (this.compare(val, p.data) >= 0) {
lower = p;
p = p.right;
} else {
p = p.left;
}
}
return lower?.data;
}
higher(val: T): T | undefined {
let p = this.tree.root;
let higher = null;
while (p) {
if (this.compare(val, p.data) < 0) {
higher = p;
p = p.left;
} else {
p = p.right;
}
}
return higher?.data;
}
lower(val: T): T | undefined {
let p = this.tree.root;
let lower = null;
while (p) {
if (this.compare(p.data, val) < 0) {
lower = p;
p = p.right;
} else {
p = p.left;
}
}
return lower?.data;
}
first(): T | undefined {
return this.tree.inOrder().next().value;
}
last(): T | undefined {
return this.tree.reverseInOrder().next().value;
}
shift(): T | undefined {
const first = this.first();
if (first === undefined) return undefined;
this.delete(first);
return first;
}
pop(): T | undefined {
const last = this.last();
if (last === undefined) return undefined;
this.delete(last);
return last;
}
*[Symbol.iterator](): Generator<T, void, void> {
yield* this.values();
}
*keys(): Generator<T, void, void> {
for (const val of this.values()) yield val;
}
*values(): Generator<T, undefined, void> {
for (const val of this.tree.inOrder()) {
let count = this.count(val);
while (count--) yield val;
}
return undefined;
}
/**
* Return a generator for reverse order traversing the multi-set
*/
*rvalues(): Generator<T, undefined, void> {
for (const val of this.tree.reverseInOrder()) {
let count = this.count(val);
while (count--) yield val;
}
return undefined;
}
}
|
2,818
|
Apply Operations to Maximize Score
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p>
<p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p>
<ul>
<li>Choose any <strong>non-empty</strong> subarray <code>nums[l, ..., r]</code> that you haven't chosen previously.</li>
<li>Choose an element <code>x</code> of <code>nums[l, ..., r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li>
<li>Multiply your score by <code>x</code>.</li>
</ul>
<p>Here, <code>nums[l, ..., r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p>
<p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p>
<p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p>
<p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,3,9,3,8], k = 2
<strong>Output:</strong> 81
<strong>Explanation:</strong> To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [19,12,14,6,10,18], k = 3
<strong>Output:</strong> 4788
<strong>Explanation:</strong> To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= min(n * (n + 1) / 2, 10<sup>9</sup>)</code></li>
</ul>
|
Stack; Greedy; Array; Math; Number Theory; Sorting; Monotonic Stack
|
C++
|
class Solution {
public:
int maximumScore(vector<int>& nums, int k) {
const int mod = 1e9 + 7;
int n = nums.size();
vector<tuple<int, int, int>> arr(n);
for (int i = 0; i < n; ++i) {
arr[i] = {i, primeFactors(nums[i]), nums[i]};
}
vector<int> left(n, -1);
vector<int> right(n, n);
stack<int> stk;
for (auto [i, f, _] : arr) {
while (!stk.empty() && get<1>(arr[stk.top()]) < f) {
stk.pop();
}
if (!stk.empty()) {
left[i] = stk.top();
}
stk.push(i);
}
stk = stack<int>();
for (int i = n - 1; ~i; --i) {
int f = get<1>(arr[i]);
while (!stk.empty() && get<1>(arr[stk.top()]) <= f) {
stk.pop();
}
if (!stk.empty()) {
right[i] = stk.top();
}
stk.push(i);
}
sort(arr.begin(), arr.end(), [](const auto& lhs, const auto& rhs) {
return get<2>(rhs) < get<2>(lhs);
});
long long ans = 1;
auto qpow = [&](long long a, int n) {
long long ans = 1;
for (; n; n >>= 1) {
if (n & 1) {
ans = ans * a % mod;
}
a = a * a % mod;
}
return ans;
};
for (auto [i, _, x] : arr) {
int l = left[i], r = right[i];
long long cnt = 1LL * (i - l) * (r - i);
if (cnt <= k) {
ans = ans * qpow(x, cnt) % mod;
k -= cnt;
} else {
ans = ans * qpow(x, k) % mod;
break;
}
}
return ans;
}
int primeFactors(int n) {
int i = 2;
unordered_set<int> ans;
while (i <= n / i) {
while (n % i == 0) {
ans.insert(i);
n /= i;
}
++i;
}
if (n > 1) {
ans.insert(n);
}
return ans.size();
}
};
|
2,818
|
Apply Operations to Maximize Score
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p>
<p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p>
<ul>
<li>Choose any <strong>non-empty</strong> subarray <code>nums[l, ..., r]</code> that you haven't chosen previously.</li>
<li>Choose an element <code>x</code> of <code>nums[l, ..., r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li>
<li>Multiply your score by <code>x</code>.</li>
</ul>
<p>Here, <code>nums[l, ..., r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p>
<p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p>
<p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p>
<p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,3,9,3,8], k = 2
<strong>Output:</strong> 81
<strong>Explanation:</strong> To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [19,12,14,6,10,18], k = 3
<strong>Output:</strong> 4788
<strong>Explanation:</strong> To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= min(n * (n + 1) / 2, 10<sup>9</sup>)</code></li>
</ul>
|
Stack; Greedy; Array; Math; Number Theory; Sorting; Monotonic Stack
|
Go
|
func maximumScore(nums []int, k int) int {
n := len(nums)
const mod = 1e9 + 7
qpow := func(a, n int) int {
ans := 1
for ; n > 0; n >>= 1 {
if n&1 == 1 {
ans = ans * a % mod
}
a = a * a % mod
}
return ans
}
arr := make([][3]int, n)
left := make([]int, n)
right := make([]int, n)
for i, x := range nums {
left[i] = -1
right[i] = n
arr[i] = [3]int{i, primeFactors(x), x}
}
stk := []int{}
for _, e := range arr {
i, f := e[0], e[1]
for len(stk) > 0 && arr[stk[len(stk)-1]][1] < f {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
left[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
stk = []int{}
for i := n - 1; i >= 0; i-- {
f := arr[i][1]
for len(stk) > 0 && arr[stk[len(stk)-1]][1] <= f {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
right[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}
sort.Slice(arr, func(i, j int) bool { return arr[i][2] > arr[j][2] })
ans := 1
for _, e := range arr {
i, x := e[0], e[2]
l, r := left[i], right[i]
cnt := (i - l) * (r - i)
if cnt <= k {
ans = ans * qpow(x, cnt) % mod
k -= cnt
} else {
ans = ans * qpow(x, k) % mod
break
}
}
return ans
}
func primeFactors(n int) int {
i := 2
ans := map[int]bool{}
for i <= n/i {
for n%i == 0 {
ans[i] = true
n /= i
}
i++
}
if n > 1 {
ans[n] = true
}
return len(ans)
}
|
2,818
|
Apply Operations to Maximize Score
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p>
<p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p>
<ul>
<li>Choose any <strong>non-empty</strong> subarray <code>nums[l, ..., r]</code> that you haven't chosen previously.</li>
<li>Choose an element <code>x</code> of <code>nums[l, ..., r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li>
<li>Multiply your score by <code>x</code>.</li>
</ul>
<p>Here, <code>nums[l, ..., r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p>
<p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p>
<p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p>
<p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,3,9,3,8], k = 2
<strong>Output:</strong> 81
<strong>Explanation:</strong> To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [19,12,14,6,10,18], k = 3
<strong>Output:</strong> 4788
<strong>Explanation:</strong> To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= min(n * (n + 1) / 2, 10<sup>9</sup>)</code></li>
</ul>
|
Stack; Greedy; Array; Math; Number Theory; Sorting; Monotonic Stack
|
Java
|
class Solution {
private final int mod = (int) 1e9 + 7;
public int maximumScore(List<Integer> nums, int k) {
int n = nums.size();
int[][] arr = new int[n][0];
for (int i = 0; i < n; ++i) {
arr[i] = new int[] {i, primeFactors(nums.get(i)), nums.get(i)};
}
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, -1);
Arrays.fill(right, n);
Deque<Integer> stk = new ArrayDeque<>();
for (int[] e : arr) {
int i = e[0], f = e[1];
while (!stk.isEmpty() && arr[stk.peek()][1] < f) {
stk.pop();
}
if (!stk.isEmpty()) {
left[i] = stk.peek();
}
stk.push(i);
}
stk.clear();
for (int i = n - 1; i >= 0; --i) {
int f = arr[i][1];
while (!stk.isEmpty() && arr[stk.peek()][1] <= f) {
stk.pop();
}
if (!stk.isEmpty()) {
right[i] = stk.peek();
}
stk.push(i);
}
Arrays.sort(arr, (a, b) -> b[2] - a[2]);
long ans = 1;
for (int[] e : arr) {
int i = e[0], x = e[2];
int l = left[i], r = right[i];
long cnt = (long) (i - l) * (r - i);
if (cnt <= k) {
ans = ans * qpow(x, cnt) % mod;
k -= cnt;
} else {
ans = ans * qpow(x, k) % mod;
break;
}
}
return (int) ans;
}
private int primeFactors(int n) {
int i = 2;
Set<Integer> ans = new HashSet<>();
while (i <= n / i) {
while (n % i == 0) {
ans.add(i);
n /= i;
}
++i;
}
if (n > 1) {
ans.add(n);
}
return ans.size();
}
private int qpow(long a, long n) {
long ans = 1;
for (; n > 0; n >>= 1) {
if ((n & 1) == 1) {
ans = ans * a % mod;
}
a = a * a % mod;
}
return (int) ans;
}
}
|
2,818
|
Apply Operations to Maximize Score
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p>
<p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p>
<ul>
<li>Choose any <strong>non-empty</strong> subarray <code>nums[l, ..., r]</code> that you haven't chosen previously.</li>
<li>Choose an element <code>x</code> of <code>nums[l, ..., r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li>
<li>Multiply your score by <code>x</code>.</li>
</ul>
<p>Here, <code>nums[l, ..., r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p>
<p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p>
<p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p>
<p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,3,9,3,8], k = 2
<strong>Output:</strong> 81
<strong>Explanation:</strong> To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [19,12,14,6,10,18], k = 3
<strong>Output:</strong> 4788
<strong>Explanation:</strong> To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= min(n * (n + 1) / 2, 10<sup>9</sup>)</code></li>
</ul>
|
Stack; Greedy; Array; Math; Number Theory; Sorting; Monotonic Stack
|
Python
|
def primeFactors(n):
i = 2
ans = set()
while i * i <= n:
while n % i == 0:
ans.add(i)
n //= i
i += 1
if n > 1:
ans.add(n)
return len(ans)
class Solution:
def maximumScore(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
arr = [(i, primeFactors(x), x) for i, x in enumerate(nums)]
n = len(nums)
left = [-1] * n
right = [n] * n
stk = []
for i, f, x in arr:
while stk and stk[-1][0] < f:
stk.pop()
if stk:
left[i] = stk[-1][1]
stk.append((f, i))
stk = []
for i, f, x in arr[::-1]:
while stk and stk[-1][0] <= f:
stk.pop()
if stk:
right[i] = stk[-1][1]
stk.append((f, i))
arr.sort(key=lambda x: -x[2])
ans = 1
for i, f, x in arr:
l, r = left[i], right[i]
cnt = (i - l) * (r - i)
if cnt <= k:
ans = ans * pow(x, cnt, mod) % mod
k -= cnt
else:
ans = ans * pow(x, k, mod) % mod
break
return ans
|
2,818
|
Apply Operations to Maximize Score
|
Hard
|
<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p>
<p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p>
<ul>
<li>Choose any <strong>non-empty</strong> subarray <code>nums[l, ..., r]</code> that you haven't chosen previously.</li>
<li>Choose an element <code>x</code> of <code>nums[l, ..., r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li>
<li>Multiply your score by <code>x</code>.</li>
</ul>
<p>Here, <code>nums[l, ..., r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p>
<p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p>
<p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p>
<p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [8,3,9,3,8], k = 2
<strong>Output:</strong> 81
<strong>Explanation:</strong> To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [19,12,14,6,10,18], k = 3
<strong>Output:</strong> 4788
<strong>Explanation:</strong> To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>5</sup></code></li>
<li><code>1 <= k <= min(n * (n + 1) / 2, 10<sup>9</sup>)</code></li>
</ul>
|
Stack; Greedy; Array; Math; Number Theory; Sorting; Monotonic Stack
|
TypeScript
|
function maximumScore(nums: number[], k: number): number {
const mod = 10 ** 9 + 7;
const n = nums.length;
const arr: number[][] = Array(n)
.fill(0)
.map(() => Array(3).fill(0));
const left: number[] = Array(n).fill(-1);
const right: number[] = Array(n).fill(n);
for (let i = 0; i < n; ++i) {
arr[i] = [i, primeFactors(nums[i]), nums[i]];
}
const stk: number[] = [];
for (const [i, f, _] of arr) {
while (stk.length && arr[stk.at(-1)!][1] < f) {
stk.pop();
}
if (stk.length) {
left[i] = stk.at(-1)!;
}
stk.push(i);
}
stk.length = 0;
for (let i = n - 1; i >= 0; --i) {
const f = arr[i][1];
while (stk.length && arr[stk.at(-1)!][1] <= f) {
stk.pop();
}
if (stk.length) {
right[i] = stk.at(-1)!;
}
stk.push(i);
}
arr.sort((a, b) => b[2] - a[2]);
let ans = 1n;
for (const [i, _, x] of arr) {
const l = left[i];
const r = right[i];
const cnt = (i - l) * (r - i);
if (cnt <= k) {
ans = (ans * qpow(BigInt(x), cnt, mod)) % BigInt(mod);
k -= cnt;
} else {
ans = (ans * qpow(BigInt(x), k, mod)) % BigInt(mod);
break;
}
}
return Number(ans);
}
function primeFactors(n: number): number {
let i = 2;
const s: Set<number> = new Set();
while (i * i <= n) {
while (n % i === 0) {
s.add(i);
n = Math.floor(n / i);
}
++i;
}
if (n > 1) {
s.add(n);
}
return s.size;
}
function qpow(a: bigint, n: number, mod: number): bigint {
let ans = 1n;
for (; n; n >>>= 1) {
if (n & 1) {
ans = (ans * a) % BigInt(mod);
}
a = (a * a) % BigInt(mod);
}
return ans;
}
|
2,819
|
Minimum Relative Loss After Buying Chocolates
|
Hard
|
<p>You are given an integer array <code>prices</code>, which shows the chocolate prices and a 2D integer array <code>queries</code>, where <code>queries[i] = [k<sub>i</sub>, m<sub>i</sub>]</code>.</p>
<p>Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.</p>
<p>The terms for each query are as follows:</p>
<ul>
<li>If the price of a chocolate is <strong>less than or equal to</strong> <code>k<sub>i</sub></code>, Bob pays for it.</li>
<li>Otherwise, Bob pays <code>k<sub>i</sub></code> of it, and Alice pays the <strong>rest</strong>.</li>
</ul>
<p>Bob wants to select <strong>exactly</strong> <code>m<sub>i</sub></code> chocolates such that his <strong>relative loss</strong> is <strong>minimized</strong>, more formally, if, in total, Alice has paid <code>a<sub>i</sub></code> and Bob has paid <code>b<sub>i</sub></code>, Bob wants to minimize <code>b<sub>i</sub> - a<sub>i</sub></code>.</p>
<p>Return <em>an integer array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is Bob's <strong>minimum relative loss </strong>possible for</em> <code>queries[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
<strong>Output:</strong> [34,-21]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
For the 2<sup>nd</sup> query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
It can be shown that these are the minimum possible relative losses.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
<strong>Output:</strong> [4,16,7,1]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
For the 3<sup>rd</sup> query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
For the 4<sup>th</sup> query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
It can be shown that these are the minimum possible relative losses.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
<strong>Output:</strong> [5,12,0]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
For the 3<sup>rd</sup> query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
It can be shown that these are the minimum possible relative losses.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= prices[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>1 <= k<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= m<sub>i</sub> <= n</code></li>
</ul>
|
Array; Binary Search; Prefix Sum; Sorting
|
C++
|
class Solution {
public:
vector<long long> minimumRelativeLosses(vector<int>& prices, vector<vector<int>>& queries) {
int n = prices.size();
sort(prices.begin(), prices.end());
long long s[n + 1];
s[0] = 0;
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + prices[i - 1];
}
auto f = [&](int k, int m) {
int l = 0, r = upper_bound(prices.begin(), prices.end(), k) - prices.begin();
r = min(r, m);
while (l < r) {
int mid = (l + r) >> 1;
int right = m - mid;
if (prices[mid] < 2LL * k - prices[n - right]) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
};
vector<long long> ans;
for (auto& q : queries) {
int k = q[0], m = q[1];
int l = f(k, m);
int r = m - l;
ans.push_back(s[l] + 2LL * k * r - (s[n] - s[n - r]));
}
return ans;
}
};
|
2,819
|
Minimum Relative Loss After Buying Chocolates
|
Hard
|
<p>You are given an integer array <code>prices</code>, which shows the chocolate prices and a 2D integer array <code>queries</code>, where <code>queries[i] = [k<sub>i</sub>, m<sub>i</sub>]</code>.</p>
<p>Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.</p>
<p>The terms for each query are as follows:</p>
<ul>
<li>If the price of a chocolate is <strong>less than or equal to</strong> <code>k<sub>i</sub></code>, Bob pays for it.</li>
<li>Otherwise, Bob pays <code>k<sub>i</sub></code> of it, and Alice pays the <strong>rest</strong>.</li>
</ul>
<p>Bob wants to select <strong>exactly</strong> <code>m<sub>i</sub></code> chocolates such that his <strong>relative loss</strong> is <strong>minimized</strong>, more formally, if, in total, Alice has paid <code>a<sub>i</sub></code> and Bob has paid <code>b<sub>i</sub></code>, Bob wants to minimize <code>b<sub>i</sub> - a<sub>i</sub></code>.</p>
<p>Return <em>an integer array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is Bob's <strong>minimum relative loss </strong>possible for</em> <code>queries[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
<strong>Output:</strong> [34,-21]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
For the 2<sup>nd</sup> query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
It can be shown that these are the minimum possible relative losses.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
<strong>Output:</strong> [4,16,7,1]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
For the 3<sup>rd</sup> query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
For the 4<sup>th</sup> query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
It can be shown that these are the minimum possible relative losses.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
<strong>Output:</strong> [5,12,0]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
For the 3<sup>rd</sup> query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
It can be shown that these are the minimum possible relative losses.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= prices[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>1 <= k<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= m<sub>i</sub> <= n</code></li>
</ul>
|
Array; Binary Search; Prefix Sum; Sorting
|
Go
|
func minimumRelativeLosses(prices []int, queries [][]int) []int64 {
n := len(prices)
sort.Ints(prices)
s := make([]int, n+1)
for i, x := range prices {
s[i+1] = s[i] + x
}
f := func(k, m int) int {
l, r := 0, sort.Search(n, func(i int) bool { return prices[i] > k })
if r > m {
r = m
}
for l < r {
mid := (l + r) >> 1
right := m - mid
if prices[mid] < 2*k-prices[n-right] {
l = mid + 1
} else {
r = mid
}
}
return l
}
ans := make([]int64, len(queries))
for i, q := range queries {
k, m := q[0], q[1]
l := f(k, m)
r := m - l
ans[i] = int64(s[l] + 2*k*r - (s[n] - s[n-r]))
}
return ans
}
|
2,819
|
Minimum Relative Loss After Buying Chocolates
|
Hard
|
<p>You are given an integer array <code>prices</code>, which shows the chocolate prices and a 2D integer array <code>queries</code>, where <code>queries[i] = [k<sub>i</sub>, m<sub>i</sub>]</code>.</p>
<p>Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.</p>
<p>The terms for each query are as follows:</p>
<ul>
<li>If the price of a chocolate is <strong>less than or equal to</strong> <code>k<sub>i</sub></code>, Bob pays for it.</li>
<li>Otherwise, Bob pays <code>k<sub>i</sub></code> of it, and Alice pays the <strong>rest</strong>.</li>
</ul>
<p>Bob wants to select <strong>exactly</strong> <code>m<sub>i</sub></code> chocolates such that his <strong>relative loss</strong> is <strong>minimized</strong>, more formally, if, in total, Alice has paid <code>a<sub>i</sub></code> and Bob has paid <code>b<sub>i</sub></code>, Bob wants to minimize <code>b<sub>i</sub> - a<sub>i</sub></code>.</p>
<p>Return <em>an integer array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is Bob's <strong>minimum relative loss </strong>possible for</em> <code>queries[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
<strong>Output:</strong> [34,-21]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
For the 2<sup>nd</sup> query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
It can be shown that these are the minimum possible relative losses.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
<strong>Output:</strong> [4,16,7,1]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
For the 3<sup>rd</sup> query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
For the 4<sup>th</sup> query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
It can be shown that these are the minimum possible relative losses.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
<strong>Output:</strong> [5,12,0]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
For the 3<sup>rd</sup> query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
It can be shown that these are the minimum possible relative losses.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= prices[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>1 <= k<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= m<sub>i</sub> <= n</code></li>
</ul>
|
Array; Binary Search; Prefix Sum; Sorting
|
Java
|
class Solution {
private int n;
private int[] prices;
public long[] minimumRelativeLosses(int[] prices, int[][] queries) {
n = prices.length;
Arrays.sort(prices);
this.prices = prices;
long[] s = new long[n + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = s[i] + prices[i];
}
int q = queries.length;
long[] ans = new long[q];
for (int i = 0; i < q; ++i) {
int k = queries[i][0], m = queries[i][1];
int l = f(k, m);
int r = m - l;
ans[i] = s[l] + 2L * k * r - (s[n] - s[n - r]);
}
return ans;
}
private int f(int k, int m) {
int l = 0, r = Arrays.binarySearch(prices, k);
if (r < 0) {
r = -(r + 1);
}
r = Math.min(m, r);
while (l < r) {
int mid = (l + r) >> 1;
int right = m - mid;
if (prices[mid] < 2L * k - prices[n - right]) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
}
|
2,819
|
Minimum Relative Loss After Buying Chocolates
|
Hard
|
<p>You are given an integer array <code>prices</code>, which shows the chocolate prices and a 2D integer array <code>queries</code>, where <code>queries[i] = [k<sub>i</sub>, m<sub>i</sub>]</code>.</p>
<p>Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.</p>
<p>The terms for each query are as follows:</p>
<ul>
<li>If the price of a chocolate is <strong>less than or equal to</strong> <code>k<sub>i</sub></code>, Bob pays for it.</li>
<li>Otherwise, Bob pays <code>k<sub>i</sub></code> of it, and Alice pays the <strong>rest</strong>.</li>
</ul>
<p>Bob wants to select <strong>exactly</strong> <code>m<sub>i</sub></code> chocolates such that his <strong>relative loss</strong> is <strong>minimized</strong>, more formally, if, in total, Alice has paid <code>a<sub>i</sub></code> and Bob has paid <code>b<sub>i</sub></code>, Bob wants to minimize <code>b<sub>i</sub> - a<sub>i</sub></code>.</p>
<p>Return <em>an integer array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is Bob's <strong>minimum relative loss </strong>possible for</em> <code>queries[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
<strong>Output:</strong> [34,-21]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
For the 2<sup>nd</sup> query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
It can be shown that these are the minimum possible relative losses.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
<strong>Output:</strong> [4,16,7,1]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
For the 3<sup>rd</sup> query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
For the 4<sup>th</sup> query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
It can be shown that these are the minimum possible relative losses.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
<strong>Output:</strong> [5,12,0]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
For the 3<sup>rd</sup> query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
It can be shown that these are the minimum possible relative losses.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= prices[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>1 <= k<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= m<sub>i</sub> <= n</code></li>
</ul>
|
Array; Binary Search; Prefix Sum; Sorting
|
Python
|
class Solution:
def minimumRelativeLosses(
self, prices: List[int], queries: List[List[int]]
) -> List[int]:
def f(k: int, m: int) -> int:
l, r = 0, min(m, bisect_right(prices, k))
while l < r:
mid = (l + r) >> 1
right = m - mid
if prices[mid] < 2 * k - prices[n - right]:
l = mid + 1
else:
r = mid
return l
prices.sort()
s = list(accumulate(prices, initial=0))
ans = []
n = len(prices)
for k, m in queries:
l = f(k, m)
r = m - l
loss = s[l] + 2 * k * r - (s[n] - s[n - r])
ans.append(loss)
return ans
|
2,819
|
Minimum Relative Loss After Buying Chocolates
|
Hard
|
<p>You are given an integer array <code>prices</code>, which shows the chocolate prices and a 2D integer array <code>queries</code>, where <code>queries[i] = [k<sub>i</sub>, m<sub>i</sub>]</code>.</p>
<p>Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.</p>
<p>The terms for each query are as follows:</p>
<ul>
<li>If the price of a chocolate is <strong>less than or equal to</strong> <code>k<sub>i</sub></code>, Bob pays for it.</li>
<li>Otherwise, Bob pays <code>k<sub>i</sub></code> of it, and Alice pays the <strong>rest</strong>.</li>
</ul>
<p>Bob wants to select <strong>exactly</strong> <code>m<sub>i</sub></code> chocolates such that his <strong>relative loss</strong> is <strong>minimized</strong>, more formally, if, in total, Alice has paid <code>a<sub>i</sub></code> and Bob has paid <code>b<sub>i</sub></code>, Bob wants to minimize <code>b<sub>i</sub> - a<sub>i</sub></code>.</p>
<p>Return <em>an integer array</em> <code>ans</code> <em>where</em> <code>ans[i]</code> <em>is Bob's <strong>minimum relative loss </strong>possible for</em> <code>queries[i]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
<strong>Output:</strong> [34,-21]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
For the 2<sup>nd</sup> query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
It can be shown that these are the minimum possible relative losses.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
<strong>Output:</strong> [4,16,7,1]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
For the 3<sup>rd</sup> query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
For the 4<sup>th</sup> query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
It can be shown that these are the minimum possible relative losses.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
<strong>Output:</strong> [5,12,0]
<strong>Explanation:</strong> For the 1<sup>st</sup> query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
For the 2<sup>nd</sup> query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
For the 3<sup>rd</sup> query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
It can be shown that these are the minimum possible relative losses.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= prices.length == n <= 10<sup>5</sup></code></li>
<li><code>1 <= prices[i] <= 10<sup>9</sup></code></li>
<li><code>1 <= queries.length <= 10<sup>5</sup></code></li>
<li><code>queries[i].length == 2</code></li>
<li><code>1 <= k<sub>i</sub> <= 10<sup>9</sup></code></li>
<li><code>1 <= m<sub>i</sub> <= n</code></li>
</ul>
|
Array; Binary Search; Prefix Sum; Sorting
|
TypeScript
|
function minimumRelativeLosses(prices: number[], queries: number[][]): number[] {
const n = prices.length;
prices.sort((a, b) => a - b);
const s: number[] = Array(n).fill(0);
for (let i = 0; i < n; ++i) {
s[i + 1] = s[i] + prices[i];
}
const search = (x: number): number => {
let l = 0;
let r = n;
while (l < r) {
const mid = (l + r) >> 1;
if (prices[mid] > x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const f = (k: number, m: number): number => {
let l = 0;
let r = Math.min(search(k), m);
while (l < r) {
const mid = (l + r) >> 1;
const right = m - mid;
if (prices[mid] < 2 * k - prices[n - right]) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
};
const ans: number[] = [];
for (const [k, m] of queries) {
const l = f(k, m);
const r = m - l;
ans.push(s[l] + 2 * k * r - (s[n] - s[n - r]));
}
return ans;
}
|
2,820
|
Election Results
|
Medium
|
<p>Table: <code><font face="monospace">Votes</font></code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| voter | varchar |
| candidate | varchar |
+-------------+---------+
(voter, candidate) is the primary key (combination of unique values) for this table.
Each row of this table contains name of the voter and their candidate.
</pre>
<p>The election is conducted in a city where everyone can vote for <strong>one or more</strong> candidates or choose <strong>not</strong> to vote. Each person has <code>1</code><strong> vote</strong> so if they vote for multiple candidates, their vote gets equally split across them. For example, if a person votes for <code>2</code> candidates, these candidates receive an equivalent of <code>0.5</code> votes each.</p>
<p>Write a solution to find <code>candidate</code> who got the most votes and won the election. Output the name of the <strong>candidate</strong> or If multiple candidates have an <strong>equal number</strong> of votes, display the names of all of them.</p>
<p>Return<em> the result table ordered</em> <em>by</em> <code>candidate</code> <em>in <strong>ascending</strong> order.</em></p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
Votes table:
+----------+-----------+
| voter | candidate |
+----------+-----------+
| Kathy | null |
| Charles | Ryan |
| Charles | Christine |
| Charles | Kathy |
| Benjamin | Christine |
| Anthony | Ryan |
| Edward | Ryan |
| Terry | null |
| Evelyn | Kathy |
| Arthur | Christine |
+----------+-----------+
<strong>Output:</strong>
+-----------+
| candidate |
+-----------+
| Christine |
| Ryan |
+-----------+
<strong>Explanation:</strong>
- Kathy and Terry opted not to participate in voting, resulting in their votes being recorded as 0. Charles distributed his vote among three candidates, equating to 0.33 for each candidate. On the other hand, Benjamin, Arthur, Anthony, Edward, and Evelyn each cast their votes for a single candidate.
- Collectively, Candidate Ryan and Christine amassed a total of 2.33 votes, while Kathy received a combined total of 1.33 votes.
Since Ryan and Christine received an equal number of votes, we will display their names in ascending order.</pre>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT candidate, SUM(vote) AS tot
FROM
(
SELECT
candidate,
1 / (COUNT(candidate) OVER (PARTITION BY voter)) AS vote
FROM Votes
WHERE candidate IS NOT NULL
) AS t
GROUP BY 1
),
P AS (
SELECT
candidate,
RANK() OVER (ORDER BY tot DESC) AS rk
FROM T
)
SELECT candidate
FROM P
WHERE rk = 1
ORDER BY 1;
|
2,821
|
Delay the Resolution of Each Promise
|
Medium
|
<p>Given an array <code>functions</code> and a number <code>ms</code>, return a new array of functions.</p>
<ul>
<li><code>functions</code> is an array of functions that return promises.</li>
<li><code>ms</code> represents the delay duration in milliseconds. It determines the amount of time to wait before resolving or rejecting each promise in the new array.</li>
</ul>
<p>Each function in the new array should return a promise that resolves or rejects after an additional delay of <code>ms</code> milliseconds, preserving the order of the original <code>functions</code> array.</p>
<p>The <code>delayAll</code> function should ensure that each promise from <code>functions</code> is executed with a delay, forming the new array of functions returning delayed promises.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
functions = [
() => new Promise((resolve) => setTimeout(resolve, 30))
],
ms = 50
<strong>Output:</strong> [80]
<strong>Explanation:</strong> The promise from the array would have resolved after 30 ms, but it was delayed by 50 ms, thus 30 ms + 50 ms = 80 ms.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong>
functions = [
() => new Promise((resolve) => setTimeout(resolve, 50)),
() => new Promise((resolve) => setTimeout(resolve, 80))
],
ms = 70
<strong>Output:</strong> [120,150]
<strong>Explanation:</strong> The promises from the array would have resolved after 50 ms and 80 ms, but they were delayed by 70 ms, thus 50 ms + 70 ms = 120 ms and 80 ms + 70 ms = 150 ms.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong>
functions = [
() => new Promise((resolve, reject) => setTimeout(reject, 20)),
() => new Promise((resolve, reject) => setTimeout(reject, 100))
],
ms = 30
<strong>Output: </strong>[50,130]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>functions</code> is an array of functions that return promises</li>
<li><code>10 <= ms <= 500</code></li>
<li><code>1 <= functions.length <= 10</code></li>
</ul>
|
JavaScript
|
TypeScript
|
function delayAll(functions: Function[], ms: number): Function[] {
return functions.map(fn => {
return async function () {
await new Promise(resolve => setTimeout(resolve, ms));
return fn();
};
});
}
|
2,822
|
Inversion of Object
|
Easy
|
<p>Given an object or an array <code>obj</code>, return an inverted object or array <code>invertedObj</code>.</p>
<p>The <code>invertedObj</code> should have the keys of <code>obj</code> as values and the values of <code>obj</code> as keys. The indices of array should be treated as keys.</p>
<p>The function should handle duplicates, meaning that if there are multiple keys in <code>obj</code> with the same value, the <code>invertedObj</code> should map the value to an array containing all corresponding keys.</p>
<p>It is guaranteed that the values in <code>obj</code> are only strings.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
<strong>Output:</strong> invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
<strong>Explanation:</strong> The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
<strong>Output:</strong> invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
<strong>Explanation:</strong> There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> obj = ["1", "2", "3", "4"]
<strong>Output:</strong> invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
<strong>Explanation:</strong> Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>obj</code> is a valid JSON object or array</li>
<li><code>typeof obj[key] === "string"</code></li>
<li><code>2 <= JSON.stringify(obj).length <= 10<sup>5</sup></code></li>
</ul>
|
JavaScript
|
TypeScript
|
function invertObject(obj: Record<any, any>): Record<any, any> {
const ans: Record<any, any> = {};
for (const key in obj) {
if (ans.hasOwnProperty(obj[key])) {
if (Array.isArray(ans[obj[key]])) {
ans[obj[key]].push(key);
} else {
ans[obj[key]] = [ans[obj[key]], key];
}
} else {
ans[obj[key]] = key;
}
}
return ans;
}
|
2,823
|
Deep Object Filter
|
Medium
|
<p>Given an object or an array <code>obj</code> and a function <code>fn</code>, return a filtered object or array <code>filteredObject</code>. </p>
<p>Function <code>deepFilter</code> should perform a deep filter operation on the <code>obj</code>. The deep filter operation should remove properties for which the output of the filter function <code>fn</code> is <code>false</code>, as well as any empty objects or arrays that remain after the keys have been removed.</p>
<p>If the deep filter operation results in an empty object or array, with no remaining properties, <code>deepFilter</code> should return <code>undefined</code> to indicate that there is no valid data left in the <code>filteredObject</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
obj = [-5, -4, -3, -2, -1, 0, 1],
fn = (x) => x > 0
<strong>Output:</strong> [1]
<strong>Explanation:</strong> All values that were not greater than 0 were removed.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong>
obj = {"a": 1, "b": "2", "c": 3, "d": "4", "e": 5, "f": 6, "g": {"a": 1}},
fn = (x) => typeof x === "string"
<strong>Output:</strong> {"b":"2","d":"4"}
<strong>Explanation:</strong> All keys with values that were not a string were removed. When the object keys were removed during the filtering process, any resulting empty objects were also removed.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong>
obj = [-1, [-1, -1, 5, -1, 10], -1, [-1], [-5]],
fn = (x) => x > 0
<strong>Output:</strong> [[5,10]]
<strong>Explanation:</strong> All values that were not greater than 0 were removed. When the values were removed during the filtering process, any resulting empty arrays were also removed.</pre>
<p><strong class="example">Example 4:</strong></p>
<pre>
<strong>Input:</strong>
obj = [[[[5]]]],
fn = (x) => Array.isArray(x)
<strong>Output:</strong> undefined
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>fn</code> is a function that returns a boolean value</li>
<li><code>obj</code> is a valid JSON object or array</li>
<li><code>2 <= JSON.stringify(obj).length <= 10<sup>5</sup></code></li>
</ul>
|
JavaScript
|
TypeScript
|
function deepFilter(obj: Record<string, any>, fn: Function): Record<string, any> | undefined {
const dfs = (data: any): any => {
if (Array.isArray(data)) {
const res = data.map(dfs).filter((item: any) => item !== undefined);
return res.length > 0 ? res : undefined;
}
if (typeof data === 'object' && data !== null) {
const res: Record<string, any> = {};
for (const key in data) {
if (data.hasOwnProperty(key)) {
const filteredValue = dfs(data[key]);
if (filteredValue !== undefined) {
res[key] = filteredValue;
}
}
}
return Object.keys(res).length > 0 ? res : undefined;
}
return fn(data) ? data : undefined;
};
return dfs(obj);
}
|
2,824
|
Count Pairs Whose Sum is Less than Target
|
Easy
|
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 <= i < j < n</code> <em>and</em> <code>nums[i] + nums[j] < target</code>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 50</code></li>
<li><code>-50 <= nums[i], target <= 50</code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
C++
|
class Solution {
public:
int countPairs(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ans = 0;
for (int j = 0; j < nums.size(); ++j) {
int i = lower_bound(nums.begin(), nums.begin() + j, target - nums[j]) - nums.begin();
ans += i;
}
return ans;
}
};
|
2,824
|
Count Pairs Whose Sum is Less than Target
|
Easy
|
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 <= i < j < n</code> <em>and</em> <code>nums[i] + nums[j] < target</code>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 50</code></li>
<li><code>-50 <= nums[i], target <= 50</code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Go
|
func countPairs(nums []int, target int) (ans int) {
sort.Ints(nums)
for j, x := range nums {
i := sort.SearchInts(nums[:j], target-x)
ans += i
}
return
}
|
2,824
|
Count Pairs Whose Sum is Less than Target
|
Easy
|
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 <= i < j < n</code> <em>and</em> <code>nums[i] + nums[j] < target</code>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 50</code></li>
<li><code>-50 <= nums[i], target <= 50</code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Java
|
class Solution {
public int countPairs(List<Integer> nums, int target) {
Collections.sort(nums);
int ans = 0;
for (int j = 0; j < nums.size(); ++j) {
int x = nums.get(j);
int i = search(nums, target - x, j);
ans += i;
}
return ans;
}
private int search(List<Integer> nums, int x, int r) {
int l = 0;
while (l < r) {
int mid = (l + r) >> 1;
if (nums.get(mid) >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
|
2,824
|
Count Pairs Whose Sum is Less than Target
|
Easy
|
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 <= i < j < n</code> <em>and</em> <code>nums[i] + nums[j] < target</code>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 50</code></li>
<li><code>-50 <= nums[i], target <= 50</code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Python
|
class Solution:
def countPairs(self, nums: List[int], target: int) -> int:
nums.sort()
ans = 0
for j, x in enumerate(nums):
i = bisect_left(nums, target - x, hi=j)
ans += i
return ans
|
2,824
|
Count Pairs Whose Sum is Less than Target
|
Easy
|
Given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, return <em>the number of pairs</em> <code>(i, j)</code> <em>where</em> <code>0 <= i < j < n</code> <em>and</em> <code>nums[i] + nums[j] < target</code>.
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length == n <= 50</code></li>
<li><code>-50 <= nums[i], target <= 50</code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
TypeScript
|
function countPairs(nums: number[], target: number): number {
nums.sort((a, b) => a - b);
let ans = 0;
const search = (x: number, r: number): number => {
let l = 0;
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
for (let j = 0; j < nums.length; ++j) {
const i = search(target - nums[j], j);
ans += i;
}
return ans;
}
|
2,825
|
Make String a Subsequence Using Cyclic Increments
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>str1</code> and <code>str2</code>.</p>
<p>In an operation, you select a <strong>set</strong> of indices in <code>str1</code>, and for each index <code>i</code> in the set, increment <code>str1[i]</code> to the next character <strong>cyclically</strong>. That is <code>'a'</code> becomes <code>'b'</code>, <code>'b'</code> becomes <code>'c'</code>, and so on, and <code>'z'</code> becomes <code>'a'</code>.</p>
<p>Return <code>true</code> <em>if it is possible to make </em><code>str2</code> <em>a subsequence of </em><code>str1</code> <em>by performing the operation <strong>at most once</strong></em>, <em>and</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note:</strong> A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= str1.length <= 10<sup>5</sup></code></li>
<li><code>1 <= str2.length <= 10<sup>5</sup></code></li>
<li><code>str1</code> and <code>str2</code> consist of only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
C++
|
class Solution {
public:
bool canMakeSubsequence(string str1, string str2) {
int i = 0, n = str2.size();
for (char c : str1) {
char d = c == 'z' ? 'a' : c + 1;
if (i < n && (str2[i] == c || str2[i] == d)) {
++i;
}
}
return i == n;
}
};
|
2,825
|
Make String a Subsequence Using Cyclic Increments
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>str1</code> and <code>str2</code>.</p>
<p>In an operation, you select a <strong>set</strong> of indices in <code>str1</code>, and for each index <code>i</code> in the set, increment <code>str1[i]</code> to the next character <strong>cyclically</strong>. That is <code>'a'</code> becomes <code>'b'</code>, <code>'b'</code> becomes <code>'c'</code>, and so on, and <code>'z'</code> becomes <code>'a'</code>.</p>
<p>Return <code>true</code> <em>if it is possible to make </em><code>str2</code> <em>a subsequence of </em><code>str1</code> <em>by performing the operation <strong>at most once</strong></em>, <em>and</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note:</strong> A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= str1.length <= 10<sup>5</sup></code></li>
<li><code>1 <= str2.length <= 10<sup>5</sup></code></li>
<li><code>str1</code> and <code>str2</code> consist of only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Go
|
func canMakeSubsequence(str1 string, str2 string) bool {
i, n := 0, len(str2)
for _, c := range str1 {
d := byte('a')
if c != 'z' {
d = byte(c + 1)
}
if i < n && (str2[i] == byte(c) || str2[i] == d) {
i++
}
}
return i == n
}
|
2,825
|
Make String a Subsequence Using Cyclic Increments
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>str1</code> and <code>str2</code>.</p>
<p>In an operation, you select a <strong>set</strong> of indices in <code>str1</code>, and for each index <code>i</code> in the set, increment <code>str1[i]</code> to the next character <strong>cyclically</strong>. That is <code>'a'</code> becomes <code>'b'</code>, <code>'b'</code> becomes <code>'c'</code>, and so on, and <code>'z'</code> becomes <code>'a'</code>.</p>
<p>Return <code>true</code> <em>if it is possible to make </em><code>str2</code> <em>a subsequence of </em><code>str1</code> <em>by performing the operation <strong>at most once</strong></em>, <em>and</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note:</strong> A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= str1.length <= 10<sup>5</sup></code></li>
<li><code>1 <= str2.length <= 10<sup>5</sup></code></li>
<li><code>str1</code> and <code>str2</code> consist of only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Java
|
class Solution {
public boolean canMakeSubsequence(String str1, String str2) {
int i = 0, n = str2.length();
for (char c : str1.toCharArray()) {
char d = c == 'z' ? 'a' : (char) (c + 1);
if (i < n && (str2.charAt(i) == c || str2.charAt(i) == d)) {
++i;
}
}
return i == n;
}
}
|
2,825
|
Make String a Subsequence Using Cyclic Increments
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>str1</code> and <code>str2</code>.</p>
<p>In an operation, you select a <strong>set</strong> of indices in <code>str1</code>, and for each index <code>i</code> in the set, increment <code>str1[i]</code> to the next character <strong>cyclically</strong>. That is <code>'a'</code> becomes <code>'b'</code>, <code>'b'</code> becomes <code>'c'</code>, and so on, and <code>'z'</code> becomes <code>'a'</code>.</p>
<p>Return <code>true</code> <em>if it is possible to make </em><code>str2</code> <em>a subsequence of </em><code>str1</code> <em>by performing the operation <strong>at most once</strong></em>, <em>and</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note:</strong> A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= str1.length <= 10<sup>5</sup></code></li>
<li><code>1 <= str2.length <= 10<sup>5</sup></code></li>
<li><code>str1</code> and <code>str2</code> consist of only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
Python
|
class Solution:
def canMakeSubsequence(self, str1: str, str2: str) -> bool:
i = 0
for c in str1:
d = "a" if c == "z" else chr(ord(c) + 1)
if i < len(str2) and str2[i] in (c, d):
i += 1
return i == len(str2)
|
2,825
|
Make String a Subsequence Using Cyclic Increments
|
Medium
|
<p>You are given two <strong>0-indexed</strong> strings <code>str1</code> and <code>str2</code>.</p>
<p>In an operation, you select a <strong>set</strong> of indices in <code>str1</code>, and for each index <code>i</code> in the set, increment <code>str1[i]</code> to the next character <strong>cyclically</strong>. That is <code>'a'</code> becomes <code>'b'</code>, <code>'b'</code> becomes <code>'c'</code>, and so on, and <code>'z'</code> becomes <code>'a'</code>.</p>
<p>Return <code>true</code> <em>if it is possible to make </em><code>str2</code> <em>a subsequence of </em><code>str1</code> <em>by performing the operation <strong>at most once</strong></em>, <em>and</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note:</strong> A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= str1.length <= 10<sup>5</sup></code></li>
<li><code>1 <= str2.length <= 10<sup>5</sup></code></li>
<li><code>str1</code> and <code>str2</code> consist of only lowercase English letters.</li>
</ul>
|
Two Pointers; String
|
TypeScript
|
function canMakeSubsequence(str1: string, str2: string): boolean {
let i = 0;
const n = str2.length;
for (const c of str1) {
const d = c === 'z' ? 'a' : String.fromCharCode(c.charCodeAt(0) + 1);
if (i < n && (str2[i] === c || str2[i] === d)) {
++i;
}
}
return i === n;
}
|
2,826
|
Sorting Three Groups
|
Medium
|
<p>You are given an integer array <code>nums</code>. Each element in <code>nums</code> is 1, 2 or 3. In each operation, you can remove an element from <code>nums</code>. Return the <strong>minimum</strong> number of operations to make <code>nums</code> <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[0]</code>, <code>nums[2]</code> and <code>nums[3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[1]</code> and <code>nums[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 = [2,2,2,2,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 3</code></li>
</ul>
<p> </p>
<strong>Follow-up:</strong> Can you come up with an algorithm that runs in <code>O(n)</code> time complexity?
|
Array; Binary Search; Dynamic Programming
|
C++
|
class Solution {
public:
int minimumOperations(vector<int>& nums) {
vector<int> f(3);
for (int x : nums) {
vector<int> g(3);
if (x == 1) {
g[0] = f[0];
g[1] = min(f[0], f[1]) + 1;
g[2] = min({f[0], f[1], f[2]}) + 1;
} else if (x == 2) {
g[0] = f[0] + 1;
g[1] = min(f[0], f[1]);
g[2] = min(f[0], min(f[1], f[2])) + 1;
} else {
g[0] = f[0] + 1;
g[1] = min(f[0], f[1]) + 1;
g[2] = min(f[0], min(f[1], f[2]));
}
f = move(g);
}
return min({f[0], f[1], f[2]});
}
};
|
2,826
|
Sorting Three Groups
|
Medium
|
<p>You are given an integer array <code>nums</code>. Each element in <code>nums</code> is 1, 2 or 3. In each operation, you can remove an element from <code>nums</code>. Return the <strong>minimum</strong> number of operations to make <code>nums</code> <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[0]</code>, <code>nums[2]</code> and <code>nums[3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[1]</code> and <code>nums[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 = [2,2,2,2,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 3</code></li>
</ul>
<p> </p>
<strong>Follow-up:</strong> Can you come up with an algorithm that runs in <code>O(n)</code> time complexity?
|
Array; Binary Search; Dynamic Programming
|
Go
|
func minimumOperations(nums []int) int {
f := make([]int, 3)
for _, x := range nums {
g := make([]int, 3)
if x == 1 {
g[0] = f[0]
g[1] = min(f[0], f[1]) + 1
g[2] = min(f[0], min(f[1], f[2])) + 1
} else if x == 2 {
g[0] = f[0] + 1
g[1] = min(f[0], f[1])
g[2] = min(f[0], min(f[1], f[2])) + 1
} else {
g[0] = f[0] + 1
g[1] = min(f[0], f[1]) + 1
g[2] = min(f[0], min(f[1], f[2]))
}
f = g
}
return min(f[0], min(f[1], f[2]))
}
|
2,826
|
Sorting Three Groups
|
Medium
|
<p>You are given an integer array <code>nums</code>. Each element in <code>nums</code> is 1, 2 or 3. In each operation, you can remove an element from <code>nums</code>. Return the <strong>minimum</strong> number of operations to make <code>nums</code> <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[0]</code>, <code>nums[2]</code> and <code>nums[3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[1]</code> and <code>nums[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 = [2,2,2,2,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 3</code></li>
</ul>
<p> </p>
<strong>Follow-up:</strong> Can you come up with an algorithm that runs in <code>O(n)</code> time complexity?
|
Array; Binary Search; Dynamic Programming
|
Java
|
class Solution {
public int minimumOperations(List<Integer> nums) {
int[] f = new int[3];
for (int x : nums) {
int[] g = new int[3];
if (x == 1) {
g[0] = f[0];
g[1] = Math.min(f[0], f[1]) + 1;
g[2] = Math.min(f[0], Math.min(f[1], f[2])) + 1;
} else if (x == 2) {
g[0] = f[0] + 1;
g[1] = Math.min(f[0], f[1]);
g[2] = Math.min(f[0], Math.min(f[1], f[2])) + 1;
} else {
g[0] = f[0] + 1;
g[1] = Math.min(f[0], f[1]) + 1;
g[2] = Math.min(f[0], Math.min(f[1], f[2]));
}
f = g;
}
return Math.min(f[0], Math.min(f[1], f[2]));
}
}
|
2,826
|
Sorting Three Groups
|
Medium
|
<p>You are given an integer array <code>nums</code>. Each element in <code>nums</code> is 1, 2 or 3. In each operation, you can remove an element from <code>nums</code>. Return the <strong>minimum</strong> number of operations to make <code>nums</code> <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[0]</code>, <code>nums[2]</code> and <code>nums[3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[1]</code> and <code>nums[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 = [2,2,2,2,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 3</code></li>
</ul>
<p> </p>
<strong>Follow-up:</strong> Can you come up with an algorithm that runs in <code>O(n)</code> time complexity?
|
Array; Binary Search; Dynamic Programming
|
Python
|
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
f = [0] * 3
for x in nums:
g = [0] * 3
if x == 1:
g[0] = f[0]
g[1] = min(f[:2]) + 1
g[2] = min(f) + 1
elif x == 2:
g[0] = f[0] + 1
g[1] = min(f[:2])
g[2] = min(f) + 1
else:
g[0] = f[0] + 1
g[1] = min(f[:2]) + 1
g[2] = min(f)
f = g
return min(f)
|
2,826
|
Sorting Three Groups
|
Medium
|
<p>You are given an integer array <code>nums</code>. Each element in <code>nums</code> is 1, 2 or 3. In each operation, you can remove an element from <code>nums</code>. Return the <strong>minimum</strong> number of operations to make <code>nums</code> <strong>non-decreasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,1,3,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[0]</code>, <code>nums[2]</code> and <code>nums[3]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,1,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>One of the optimal solutions is to remove <code>nums[1]</code> and <code>nums[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 = [2,2,2,2,3,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> is already non-decreasing.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 3</code></li>
</ul>
<p> </p>
<strong>Follow-up:</strong> Can you come up with an algorithm that runs in <code>O(n)</code> time complexity?
|
Array; Binary Search; Dynamic Programming
|
TypeScript
|
function minimumOperations(nums: number[]): number {
let f: number[] = new Array(3).fill(0);
for (const x of nums) {
const g: number[] = new Array(3).fill(0);
if (x === 1) {
g[0] = f[0];
g[1] = Math.min(f[0], f[1]) + 1;
g[2] = Math.min(f[0], Math.min(f[1], f[2])) + 1;
} else if (x === 2) {
g[0] = f[0] + 1;
g[1] = Math.min(f[0], f[1]);
g[2] = Math.min(f[0], Math.min(f[1], f[2])) + 1;
} else {
g[0] = f[0] + 1;
g[1] = Math.min(f[0], f[1]) + 1;
g[2] = Math.min(f[0], Math.min(f[1], f[2]));
}
f = g;
}
return Math.min(...f);
}
|
2,827
|
Number of Beautiful Integers in the Range
|
Hard
|
<p>You are given positive integers <code>low</code>, <code>high</code>, and <code>k</code>.</p>
<p>A number is <strong>beautiful</strong> if it meets both of the following conditions:</p>
<ul>
<li>The count of even digits in the number is equal to the count of odd digits.</li>
<li>The number is divisible by <code>k</code>.</li>
</ul>
<p>Return <em>the number of beautiful integers in the range</em> <code>[low, high]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = 10, high = 20, k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful integers in the given range: [12,18].
- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
Additionally we can see that:
- 16 is not beautiful because it is not divisible by k = 3.
- 15 is not beautiful because it does not contain equal counts even and odd digits.
It can be shown that there are only 2 beautiful integers in the given range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = 1, high = 10, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 beautiful integer in the given range: [10].
- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.
It can be shown that there is only 1 beautiful integer in the given range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> low = 5, high = 5, k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 0 beautiful integers in the given range.
- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < low <= high <= 10<sup>9</sup></code></li>
<li><code>0 < k <= 20</code></li>
</ul>
|
Math; Dynamic Programming
|
C++
|
class Solution {
public:
int numberOfBeautifulIntegers(int low, int high, int k) {
int f[11][21][21];
memset(f, -1, sizeof(f));
string s = to_string(high);
function<int(int, int, int, bool, bool)> dfs = [&](int pos, int mod, int diff, bool lead, bool limit) {
if (pos >= s.size()) {
return mod == 0 && diff == 10 ? 1 : 0;
}
if (!lead && !limit && f[pos][mod][diff] != -1) {
return f[pos][mod][diff];
}
int ans = 0;
int up = limit ? s[pos] - '0' : 9;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead) {
ans += dfs(pos + 1, mod, diff, true, limit && i == up);
} else {
int nxt = diff + (i % 2 == 1 ? 1 : -1);
ans += dfs(pos + 1, (mod * 10 + i) % k, nxt, false, limit && i == up);
}
}
if (!lead && !limit) {
f[pos][mod][diff] = ans;
}
return ans;
};
int a = dfs(0, 0, 10, true, true);
memset(f, -1, sizeof(f));
s = to_string(low - 1);
int b = dfs(0, 0, 10, true, true);
return a - b;
}
};
|
2,827
|
Number of Beautiful Integers in the Range
|
Hard
|
<p>You are given positive integers <code>low</code>, <code>high</code>, and <code>k</code>.</p>
<p>A number is <strong>beautiful</strong> if it meets both of the following conditions:</p>
<ul>
<li>The count of even digits in the number is equal to the count of odd digits.</li>
<li>The number is divisible by <code>k</code>.</li>
</ul>
<p>Return <em>the number of beautiful integers in the range</em> <code>[low, high]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = 10, high = 20, k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful integers in the given range: [12,18].
- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
Additionally we can see that:
- 16 is not beautiful because it is not divisible by k = 3.
- 15 is not beautiful because it does not contain equal counts even and odd digits.
It can be shown that there are only 2 beautiful integers in the given range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = 1, high = 10, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 beautiful integer in the given range: [10].
- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.
It can be shown that there is only 1 beautiful integer in the given range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> low = 5, high = 5, k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 0 beautiful integers in the given range.
- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < low <= high <= 10<sup>9</sup></code></li>
<li><code>0 < k <= 20</code></li>
</ul>
|
Math; Dynamic Programming
|
Go
|
func numberOfBeautifulIntegers(low int, high int, k int) int {
s := strconv.Itoa(high)
f := g(len(s), k, 21)
var dfs func(pos, mod, diff int, lead, limit bool) int
dfs = func(pos, mod, diff int, lead, limit bool) int {
if pos >= len(s) {
if mod == 0 && diff == 10 {
return 1
}
return 0
}
if !lead && !limit && f[pos][mod][diff] != -1 {
return f[pos][mod][diff]
}
up := 9
if limit {
up = int(s[pos] - '0')
}
ans := 0
for i := 0; i <= up; i++ {
if i == 0 && lead {
ans += dfs(pos+1, mod, diff, true, limit && i == up)
} else {
nxt := diff + 1
if i%2 == 0 {
nxt -= 2
}
ans += dfs(pos+1, (mod*10+i)%k, nxt, false, limit && i == up)
}
}
if !lead && !limit {
f[pos][mod][diff] = ans
}
return ans
}
a := dfs(0, 0, 10, true, true)
s = strconv.Itoa(low - 1)
f = g(len(s), k, 21)
b := dfs(0, 0, 10, true, true)
return a - b
}
func g(m, n, k int) [][][]int {
f := make([][][]int, m)
for i := 0; i < m; i++ {
f[i] = make([][]int, n)
for j := 0; j < n; j++ {
f[i][j] = make([]int, k)
for d := 0; d < k; d++ {
f[i][j][d] = -1
}
}
}
return f
}
|
2,827
|
Number of Beautiful Integers in the Range
|
Hard
|
<p>You are given positive integers <code>low</code>, <code>high</code>, and <code>k</code>.</p>
<p>A number is <strong>beautiful</strong> if it meets both of the following conditions:</p>
<ul>
<li>The count of even digits in the number is equal to the count of odd digits.</li>
<li>The number is divisible by <code>k</code>.</li>
</ul>
<p>Return <em>the number of beautiful integers in the range</em> <code>[low, high]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = 10, high = 20, k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful integers in the given range: [12,18].
- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
Additionally we can see that:
- 16 is not beautiful because it is not divisible by k = 3.
- 15 is not beautiful because it does not contain equal counts even and odd digits.
It can be shown that there are only 2 beautiful integers in the given range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = 1, high = 10, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 beautiful integer in the given range: [10].
- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.
It can be shown that there is only 1 beautiful integer in the given range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> low = 5, high = 5, k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 0 beautiful integers in the given range.
- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < low <= high <= 10<sup>9</sup></code></li>
<li><code>0 < k <= 20</code></li>
</ul>
|
Math; Dynamic Programming
|
Java
|
class Solution {
private String s;
private int k;
private Integer[][][] f = new Integer[11][21][21];
public int numberOfBeautifulIntegers(int low, int high, int k) {
this.k = k;
s = String.valueOf(high);
int a = dfs(0, 0, 10, true, true);
s = String.valueOf(low - 1);
f = new Integer[11][21][21];
int b = dfs(0, 0, 10, true, true);
return a - b;
}
private int dfs(int pos, int mod, int diff, boolean lead, boolean limit) {
if (pos >= s.length()) {
return mod == 0 && diff == 10 ? 1 : 0;
}
if (!lead && !limit && f[pos][mod][diff] != null) {
return f[pos][mod][diff];
}
int ans = 0;
int up = limit ? s.charAt(pos) - '0' : 9;
for (int i = 0; i <= up; ++i) {
if (i == 0 && lead) {
ans += dfs(pos + 1, mod, diff, true, limit && i == up);
} else {
int nxt = diff + (i % 2 == 1 ? 1 : -1);
ans += dfs(pos + 1, (mod * 10 + i) % k, nxt, false, limit && i == up);
}
}
if (!lead && !limit) {
f[pos][mod][diff] = ans;
}
return ans;
}
}
|
2,827
|
Number of Beautiful Integers in the Range
|
Hard
|
<p>You are given positive integers <code>low</code>, <code>high</code>, and <code>k</code>.</p>
<p>A number is <strong>beautiful</strong> if it meets both of the following conditions:</p>
<ul>
<li>The count of even digits in the number is equal to the count of odd digits.</li>
<li>The number is divisible by <code>k</code>.</li>
</ul>
<p>Return <em>the number of beautiful integers in the range</em> <code>[low, high]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = 10, high = 20, k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful integers in the given range: [12,18].
- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
Additionally we can see that:
- 16 is not beautiful because it is not divisible by k = 3.
- 15 is not beautiful because it does not contain equal counts even and odd digits.
It can be shown that there are only 2 beautiful integers in the given range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = 1, high = 10, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 beautiful integer in the given range: [10].
- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.
It can be shown that there is only 1 beautiful integer in the given range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> low = 5, high = 5, k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 0 beautiful integers in the given range.
- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < low <= high <= 10<sup>9</sup></code></li>
<li><code>0 < k <= 20</code></li>
</ul>
|
Math; Dynamic Programming
|
Python
|
class Solution:
def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int:
@cache
def dfs(pos: int, mod: int, diff: int, lead: int, limit: int) -> int:
if pos >= len(s):
return mod == 0 and diff == 10
up = int(s[pos]) if limit else 9
ans = 0
for i in range(up + 1):
if i == 0 and lead:
ans += dfs(pos + 1, mod, diff, 1, limit and i == up)
else:
nxt = diff + (1 if i % 2 == 1 else -1)
ans += dfs(pos + 1, (mod * 10 + i) % k, nxt, 0, limit and i == up)
return ans
s = str(high)
a = dfs(0, 0, 10, 1, 1)
dfs.cache_clear()
s = str(low - 1)
b = dfs(0, 0, 10, 1, 1)
return a - b
|
2,827
|
Number of Beautiful Integers in the Range
|
Hard
|
<p>You are given positive integers <code>low</code>, <code>high</code>, and <code>k</code>.</p>
<p>A number is <strong>beautiful</strong> if it meets both of the following conditions:</p>
<ul>
<li>The count of even digits in the number is equal to the count of odd digits.</li>
<li>The number is divisible by <code>k</code>.</li>
</ul>
<p>Return <em>the number of beautiful integers in the range</em> <code>[low, high]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> low = 10, high = 20, k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful integers in the given range: [12,18].
- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.
Additionally we can see that:
- 16 is not beautiful because it is not divisible by k = 3.
- 15 is not beautiful because it does not contain equal counts even and odd digits.
It can be shown that there are only 2 beautiful integers in the given range.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> low = 1, high = 10, k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 beautiful integer in the given range: [10].
- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.
It can be shown that there is only 1 beautiful integer in the given range.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> low = 5, high = 5, k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 0 beautiful integers in the given range.
- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 < low <= high <= 10<sup>9</sup></code></li>
<li><code>0 < k <= 20</code></li>
</ul>
|
Math; Dynamic Programming
|
TypeScript
|
function numberOfBeautifulIntegers(low: number, high: number, k: number): number {
let s = String(high);
let f: number[][][] = Array(11)
.fill(0)
.map(() =>
Array(21)
.fill(0)
.map(() => Array(21).fill(-1)),
);
const dfs = (pos: number, mod: number, diff: number, lead: boolean, limit: boolean): number => {
if (pos >= s.length) {
return mod == 0 && diff == 10 ? 1 : 0;
}
if (!lead && !limit && f[pos][mod][diff] != -1) {
return f[pos][mod][diff];
}
let ans = 0;
const up = limit ? Number(s[pos]) : 9;
for (let i = 0; i <= up; ++i) {
if (i === 0 && lead) {
ans += dfs(pos + 1, mod, diff, true, limit && i === up);
} else {
const nxt = diff + (i % 2 ? 1 : -1);
ans += dfs(pos + 1, (mod * 10 + i) % k, nxt, false, limit && i === up);
}
}
if (!lead && !limit) {
f[pos][mod][diff] = ans;
}
return ans;
};
const a = dfs(0, 0, 10, true, true);
s = String(low - 1);
f = Array(11)
.fill(0)
.map(() =>
Array(21)
.fill(0)
.map(() => Array(21).fill(-1)),
);
const b = dfs(0, 0, 10, true, true);
return a - b;
}
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
C++
|
class Solution {
public:
bool isAcronym(vector<string>& words, string s) {
string t;
for (auto& w : words) {
t += w[0];
}
return t == s;
}
};
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
Go
|
func isAcronym(words []string, s string) bool {
t := []byte{}
for _, w := range words {
t = append(t, w[0])
}
return string(t) == s
}
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
Java
|
class Solution {
public boolean isAcronym(List<String> words, String s) {
StringBuilder t = new StringBuilder();
for (var w : words) {
t.append(w.charAt(0));
}
return t.toString().equals(s);
}
}
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
Python
|
class Solution:
def isAcronym(self, words: List[str], s: str) -> bool:
return "".join(w[0] for w in words) == s
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
Rust
|
impl Solution {
pub fn is_acronym(words: Vec<String>, s: String) -> bool {
words
.iter()
.map(|w| w.chars().next().unwrap_or_default())
.collect::<String>()
== s
}
}
|
2,828
|
Check if a String Is an Acronym of Words
|
Easy
|
<p>Given an array of strings <code>words</code> and a string <code>s</code>, determine if <code>s</code> is an <strong>acronym</strong> of words.</p>
<p>The string <code>s</code> is considered an acronym of <code>words</code> if it can be formed by concatenating the <strong>first</strong> character of each string in <code>words</code> <strong>in order</strong>. For example, <code>"ab"</code> can be formed from <code>["apple", "banana"]</code>, but it can't be formed from <code>["bear", "aardvark"]</code>.</p>
<p>Return <code>true</code><em> if </em><code>s</code><em> is an acronym of </em><code>words</code><em>, and </em><code>false</code><em> otherwise. </em></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["alice","bob","charlie"], s = "abc"
<strong>Output:</strong> true
<strong>Explanation:</strong> The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["an","apple"], s = "a"
<strong>Output:</strong> false
<strong>Explanation:</strong> The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> words = ["never","gonna","give","up","on","you"], s = "ngguoy"
<strong>Output:</strong> true
<strong>Explanation: </strong>By concatenating the first character of the words in the array, we get the string "ngguoy".
Hence, s = "ngguoy" is the acronym.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>1 <= s.length <= 100</code></li>
<li><code>words[i]</code> and <code>s</code> consist of lowercase English letters.</li>
</ul>
|
Array; String
|
TypeScript
|
function isAcronym(words: string[], s: string): boolean {
return words.map(w => w[0]).join('') === s;
}
|
2,829
|
Determine the Minimum Sum of a k-avoiding Array
|
Medium
|
<p>You are given two integers, <code>n</code> and <code>k</code>.</p>
<p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 50</code></li>
</ul>
|
Greedy; Math
|
C++
|
class Solution {
public:
int minimumSum(int n, int k) {
int s = 0, i = 1;
bool vis[n + k + 1];
memset(vis, false, sizeof(vis));
while (n--) {
while (vis[i]) {
++i;
}
if (k >= i) {
vis[k - i] = true;
}
s += i++;
}
return s;
}
};
|
2,829
|
Determine the Minimum Sum of a k-avoiding Array
|
Medium
|
<p>You are given two integers, <code>n</code> and <code>k</code>.</p>
<p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 50</code></li>
</ul>
|
Greedy; Math
|
Go
|
func minimumSum(n int, k int) int {
s, i := 0, 1
vis := make([]bool, n+k+1)
for ; n > 0; n-- {
for vis[i] {
i++
}
if k >= i {
vis[k-i] = true
}
s += i
i++
}
return s
}
|
2,829
|
Determine the Minimum Sum of a k-avoiding Array
|
Medium
|
<p>You are given two integers, <code>n</code> and <code>k</code>.</p>
<p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 50</code></li>
</ul>
|
Greedy; Math
|
Java
|
class Solution {
public int minimumSum(int n, int k) {
int s = 0, i = 1;
boolean[] vis = new boolean[n + k + 1];
while (n-- > 0) {
while (vis[i]) {
++i;
}
if (k >= i) {
vis[k - i] = true;
}
s += i++;
}
return s;
}
}
|
2,829
|
Determine the Minimum Sum of a k-avoiding Array
|
Medium
|
<p>You are given two integers, <code>n</code> and <code>k</code>.</p>
<p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 50</code></li>
</ul>
|
Greedy; Math
|
Python
|
class Solution:
def minimumSum(self, n: int, k: int) -> int:
s, i = 0, 1
vis = set()
for _ in range(n):
while i in vis:
i += 1
vis.add(k - i)
s += i
i += 1
return s
|
2,829
|
Determine the Minimum Sum of a k-avoiding Array
|
Medium
|
<p>You are given two integers, <code>n</code> and <code>k</code>.</p>
<p>An array of <strong>distinct</strong> positive integers is called a <b>k-avoiding</b> array if there does not exist any pair of distinct elements that sum to <code>k</code>.</p>
<p>Return <em>the <strong>minimum</strong> possible sum of a k-avoiding array of length </em><code>n</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n, k <= 50</code></li>
</ul>
|
Greedy; Math
|
Rust
|
impl Solution {
pub fn minimum_sum(n: i32, k: i32) -> i32 {
let (mut s, mut i) = (0, 1);
let mut vis = std::collections::HashSet::new();
for _ in 0..n {
while vis.contains(&i) {
i += 1;
}
vis.insert(k - i);
s += i;
i += 1;
}
s
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.