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,545
Sort the Students by Their Kth Score
Medium
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p> <p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code>&nbsp;(<strong>0-indexed</strong>) exam from the highest to the lowest.</p> <p>Return <em>the matrix after sorting it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" /> <pre> <strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 <strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" /> <pre> <strong>Input:</strong> score = [[3,4],[5,6]], k = 0 <strong>Output:</strong> [[5,6],[3,4]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == score.length</code></li> <li><code>n == score[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>1 &lt;= score[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>score</code> consists of <strong>distinct</strong> integers.</li> <li><code>0 &lt;= k &lt; n</code></li> </ul>
Array; Matrix; Sorting
Go
func sortTheStudents(score [][]int, k int) [][]int { sort.Slice(score, func(i, j int) bool { return score[i][k] > score[j][k] }) return score }
2,545
Sort the Students by Their Kth Score
Medium
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p> <p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code>&nbsp;(<strong>0-indexed</strong>) exam from the highest to the lowest.</p> <p>Return <em>the matrix after sorting it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" /> <pre> <strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 <strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" /> <pre> <strong>Input:</strong> score = [[3,4],[5,6]], k = 0 <strong>Output:</strong> [[5,6],[3,4]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == score.length</code></li> <li><code>n == score[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>1 &lt;= score[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>score</code> consists of <strong>distinct</strong> integers.</li> <li><code>0 &lt;= k &lt; n</code></li> </ul>
Array; Matrix; Sorting
Java
class Solution { public int[][] sortTheStudents(int[][] score, int k) { Arrays.sort(score, (a, b) -> b[k] - a[k]); return score; } }
2,545
Sort the Students by Their Kth Score
Medium
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p> <p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code>&nbsp;(<strong>0-indexed</strong>) exam from the highest to the lowest.</p> <p>Return <em>the matrix after sorting it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" /> <pre> <strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 <strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" /> <pre> <strong>Input:</strong> score = [[3,4],[5,6]], k = 0 <strong>Output:</strong> [[5,6],[3,4]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == score.length</code></li> <li><code>n == score[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>1 &lt;= score[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>score</code> consists of <strong>distinct</strong> integers.</li> <li><code>0 &lt;= k &lt; n</code></li> </ul>
Array; Matrix; Sorting
Python
class Solution: def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: return sorted(score, key=lambda x: -x[k])
2,545
Sort the Students by Their Kth Score
Medium
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p> <p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code>&nbsp;(<strong>0-indexed</strong>) exam from the highest to the lowest.</p> <p>Return <em>the matrix after sorting it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" /> <pre> <strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 <strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" /> <pre> <strong>Input:</strong> score = [[3,4],[5,6]], k = 0 <strong>Output:</strong> [[5,6],[3,4]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == score.length</code></li> <li><code>n == score[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>1 &lt;= score[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>score</code> consists of <strong>distinct</strong> integers.</li> <li><code>0 &lt;= k &lt; n</code></li> </ul>
Array; Matrix; Sorting
Rust
impl Solution { pub fn sort_the_students(mut score: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> { let k = k as usize; score.sort_by(|a, b| b[k].cmp(&a[k])); score } }
2,545
Sort the Students by Their Kth Score
Medium
<p>There is a class with <code>m</code> students and <code>n</code> exams. You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>score</code>, where each row represents one student and <code>score[i][j]</code> denotes the score the <code>i<sup>th</sup></code> student got in the <code>j<sup>th</sup></code> exam. The matrix <code>score</code> contains <strong>distinct</strong> integers only.</p> <p>You are also given an integer <code>k</code>. Sort the students (i.e., the rows of the matrix) by their scores in the <code>k<sup>th</sup></code>&nbsp;(<strong>0-indexed</strong>) exam from the highest to the lowest.</p> <p>Return <em>the matrix after sorting it.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example1.png" style="width: 600px; height: 136px;" /> <pre> <strong>Input:</strong> score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 <strong>Output:</strong> [[7,5,11,2],[10,6,9,1],[4,8,3,15]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place. - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place. - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2545.Sort%20the%20Students%20by%20Their%20Kth%20Score/images/example2.png" style="width: 486px; height: 121px;" /> <pre> <strong>Input:</strong> score = [[3,4],[5,6]], k = 0 <strong>Output:</strong> [[5,6],[3,4]] <strong>Explanation:</strong> In the above diagram, S denotes the student, while E denotes the exam. - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place. - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == score.length</code></li> <li><code>n == score[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>1 &lt;= score[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>score</code> consists of <strong>distinct</strong> integers.</li> <li><code>0 &lt;= k &lt; n</code></li> </ul>
Array; Matrix; Sorting
TypeScript
function sortTheStudents(score: number[][], k: number): number[][] { return score.sort((a, b) => b[k] - a[k]); }
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
C
bool makeStringsEqual(char* s, char* target) { int count = 0; for (int i = 0; s[i]; i++) { if (s[i] == '1') { count++; break; } } for (int i = 0; target[i]; i++) { if (target[i] == '1') { count++; break; } } return !(count & 1); }
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
C++
class Solution { public: bool makeStringsEqual(string s, string target) { auto a = count(s.begin(), s.end(), '1') > 0; auto b = count(target.begin(), target.end(), '1') > 0; return a == b; } };
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
Go
func makeStringsEqual(s string, target string) bool { return strings.Contains(s, "1") == strings.Contains(target, "1") }
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
Java
class Solution { public boolean makeStringsEqual(String s, String target) { return s.contains("1") == target.contains("1"); } }
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
Python
class Solution: def makeStringsEqual(self, s: str, target: str) -> bool: return ("1" in s) == ("1" in target)
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
Rust
impl Solution { pub fn make_strings_equal(s: String, target: String) -> bool { s.contains('1') == target.contains('1') } }
2,546
Apply Bitwise Operations to Make Strings Equal
Medium
<p>You are given two <strong>0-indexed binary</strong> strings <code>s</code> and <code>target</code> of the same length <code>n</code>. You can do the following operation on <code>s</code> <strong>any</strong> number of times:</p> <ul> <li>Choose two <strong>different</strong> indices <code>i</code> and <code>j</code> where <code>0 &lt;= i, j &lt; n</code>.</li> <li>Simultaneously, replace <code>s[i]</code> with (<code>s[i]</code> <strong>OR</strong> <code>s[j]</code>) and <code>s[j]</code> with (<code>s[i]</code> <strong>XOR</strong> <code>s[j]</code>).</li> </ul> <p>For example, if <code>s = &quot;0110&quot;</code>, you can choose <code>i = 0</code> and <code>j = 2</code>, then simultaneously replace <code>s[0]</code> with (<code>s[0]</code> <strong>OR</strong> <code>s[2]</code> = <code>0</code> <strong>OR</strong> <code>1</code> = <code>1</code>), and <code>s[2]</code> with (<code>s[0]</code> <strong>XOR</strong> <code>s[2]</code> = <code>0</code> <strong>XOR</strong> <code>1</code> = <code>1</code>), so we will have <code>s = &quot;1110&quot;</code>.</p> <p>Return <code>true</code> <em>if you can make the string </em><code>s</code><em> equal to </em><code>target</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1010&quot;, target = &quot;0110&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can do the following operations: - Choose i = 2 and j = 0. We have now s = &quot;<strong><u>0</u></strong>0<strong><u>1</u></strong>0&quot;. - Choose i = 2 and j = 1. We have now s = &quot;0<strong><u>11</u></strong>0&quot;. Since we can make s equal to target, we return true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;11&quot;, target = &quot;00&quot; <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to make s equal to target with any number of operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == s.length == target.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>target</code> consist of only the digits <code>0</code> and <code>1</code>.</li> </ul>
Bit Manipulation; String
TypeScript
function makeStringsEqual(s: string, target: string): boolean { return s.includes('1') === target.includes('1'); }
2,547
Minimum Cost to Split an Array
Hard
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Split the array into some number of non-empty subarrays. The <strong>cost</strong> of a split is the sum of the <strong>importance value</strong> of each subarray in the split.</p> <p>Let <code>trimmed(subarray)</code> be the version of the subarray where all numbers which appear only once are removed.</p> <ul> <li>For example, <code>trimmed([3,1,2,4,3,4]) = [3,4,3,4].</code></li> </ul> <p>The <strong>importance value</strong> of a subarray is <code>k + trimmed(subarray).length</code>.</p> <ul> <li>For example, if a subarray is <code>[1,2,3,3,3,4,4]</code>, then <font face="monospace">trimmed(</font><code>[1,2,3,3,3,4,4]) = [3,3,3,4,4].</code>The importance value of this subarray will be <code>k + 5</code>.</li> </ul> <p>Return <em>the minimum possible cost of a split of </em><code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,3,3], k = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 5 <strong>Output:</strong> 10 <strong>Explanation:</strong> We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Hash Table; Dynamic Programming; Counting
C++
class Solution { public: int minCost(vector<int>& nums, int k) { int n = nums.size(); int f[n]; memset(f, 0, sizeof f); function<int(int)> dfs = [&](int i) { if (i >= n) { return 0; } if (f[i]) { return f[i]; } int cnt[n]; memset(cnt, 0, sizeof cnt); int one = 0; int ans = 1 << 30; for (int j = i; j < n; ++j) { int x = ++cnt[nums[j]]; if (x == 1) { ++one; } else if (x == 2) { --one; } ans = min(ans, k + j - i + 1 - one + dfs(j + 1)); } return f[i] = ans; }; return dfs(0); } };
2,547
Minimum Cost to Split an Array
Hard
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Split the array into some number of non-empty subarrays. The <strong>cost</strong> of a split is the sum of the <strong>importance value</strong> of each subarray in the split.</p> <p>Let <code>trimmed(subarray)</code> be the version of the subarray where all numbers which appear only once are removed.</p> <ul> <li>For example, <code>trimmed([3,1,2,4,3,4]) = [3,4,3,4].</code></li> </ul> <p>The <strong>importance value</strong> of a subarray is <code>k + trimmed(subarray).length</code>.</p> <ul> <li>For example, if a subarray is <code>[1,2,3,3,3,4,4]</code>, then <font face="monospace">trimmed(</font><code>[1,2,3,3,3,4,4]) = [3,3,3,4,4].</code>The importance value of this subarray will be <code>k + 5</code>.</li> </ul> <p>Return <em>the minimum possible cost of a split of </em><code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,3,3], k = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 5 <strong>Output:</strong> 10 <strong>Explanation:</strong> We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Hash Table; Dynamic Programming; Counting
Go
func minCost(nums []int, k int) int { n := len(nums) f := make([]int, n) var dfs func(int) int dfs = func(i int) int { if i >= n { return 0 } if f[i] > 0 { return f[i] } ans, one := 1<<30, 0 cnt := make([]int, n) for j := i; j < n; j++ { cnt[nums[j]]++ x := cnt[nums[j]] if x == 1 { one++ } else if x == 2 { one-- } ans = min(ans, k+j-i+1-one+dfs(j+1)) } f[i] = ans return ans } return dfs(0) }
2,547
Minimum Cost to Split an Array
Hard
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Split the array into some number of non-empty subarrays. The <strong>cost</strong> of a split is the sum of the <strong>importance value</strong> of each subarray in the split.</p> <p>Let <code>trimmed(subarray)</code> be the version of the subarray where all numbers which appear only once are removed.</p> <ul> <li>For example, <code>trimmed([3,1,2,4,3,4]) = [3,4,3,4].</code></li> </ul> <p>The <strong>importance value</strong> of a subarray is <code>k + trimmed(subarray).length</code>.</p> <ul> <li>For example, if a subarray is <code>[1,2,3,3,3,4,4]</code>, then <font face="monospace">trimmed(</font><code>[1,2,3,3,3,4,4]) = [3,3,3,4,4].</code>The importance value of this subarray will be <code>k + 5</code>.</li> </ul> <p>Return <em>the minimum possible cost of a split of </em><code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,3,3], k = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 5 <strong>Output:</strong> 10 <strong>Explanation:</strong> We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Hash Table; Dynamic Programming; Counting
Java
class Solution { private Integer[] f; private int[] nums; private int n, k; public int minCost(int[] nums, int k) { n = nums.length; this.k = k; this.nums = nums; f = new Integer[n]; return dfs(0); } private int dfs(int i) { if (i >= n) { return 0; } if (f[i] != null) { return f[i]; } int[] cnt = new int[n]; int one = 0; int ans = 1 << 30; for (int j = i; j < n; ++j) { int x = ++cnt[nums[j]]; if (x == 1) { ++one; } else if (x == 2) { --one; } ans = Math.min(ans, k + j - i + 1 - one + dfs(j + 1)); } return f[i] = ans; } }
2,547
Minimum Cost to Split an Array
Hard
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Split the array into some number of non-empty subarrays. The <strong>cost</strong> of a split is the sum of the <strong>importance value</strong> of each subarray in the split.</p> <p>Let <code>trimmed(subarray)</code> be the version of the subarray where all numbers which appear only once are removed.</p> <ul> <li>For example, <code>trimmed([3,1,2,4,3,4]) = [3,4,3,4].</code></li> </ul> <p>The <strong>importance value</strong> of a subarray is <code>k + trimmed(subarray).length</code>.</p> <ul> <li>For example, if a subarray is <code>[1,2,3,3,3,4,4]</code>, then <font face="monospace">trimmed(</font><code>[1,2,3,3,3,4,4]) = [3,3,3,4,4].</code>The importance value of this subarray will be <code>k + 5</code>.</li> </ul> <p>Return <em>the minimum possible cost of a split of </em><code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,3,3], k = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 5 <strong>Output:</strong> 10 <strong>Explanation:</strong> We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Hash Table; Dynamic Programming; Counting
Python
class Solution: def minCost(self, nums: List[int], k: int) -> int: @cache def dfs(i): if i >= n: return 0 cnt = Counter() one = 0 ans = inf for j in range(i, n): cnt[nums[j]] += 1 if cnt[nums[j]] == 1: one += 1 elif cnt[nums[j]] == 2: one -= 1 ans = min(ans, k + j - i + 1 - one + dfs(j + 1)) return ans n = len(nums) return dfs(0)
2,547
Minimum Cost to Split an Array
Hard
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Split the array into some number of non-empty subarrays. The <strong>cost</strong> of a split is the sum of the <strong>importance value</strong> of each subarray in the split.</p> <p>Let <code>trimmed(subarray)</code> be the version of the subarray where all numbers which appear only once are removed.</p> <ul> <li>For example, <code>trimmed([3,1,2,4,3,4]) = [3,4,3,4].</code></li> </ul> <p>The <strong>importance value</strong> of a subarray is <code>k + trimmed(subarray).length</code>.</p> <ul> <li>For example, if a subarray is <code>[1,2,3,3,3,4,4]</code>, then <font face="monospace">trimmed(</font><code>[1,2,3,3,3,4,4]) = [3,3,3,4,4].</code>The importance value of this subarray will be <code>k + 5</code>.</li> </ul> <p>Return <em>the minimum possible cost of a split of </em><code>nums</code>.</p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,3,3], k = 2 <strong>Output:</strong> 8 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1], k = 5 <strong>Output:</strong> 10 <strong>Explanation:</strong> We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Hash Table; Dynamic Programming; Counting
TypeScript
function minCost(nums: number[], k: number): number { const n = nums.length; const f = new Array(n).fill(0); const dfs = (i: number) => { if (i >= n) { return 0; } if (f[i]) { return f[i]; } const cnt = new Array(n).fill(0); let one = 0; let ans = 1 << 30; for (let j = i; j < n; ++j) { const x = ++cnt[nums[j]]; if (x == 1) { ++one; } else if (x == 2) { --one; } ans = Math.min(ans, k + j - i + 1 - one + dfs(j + 1)); } f[i] = ans; return f[i]; }; return dfs(0); }
2,548
Maximum Price to Fill a Bag
Medium
<p>You are given a 2D integer array <code>items</code> where <code>items[i] = [price<sub>i</sub>, weight<sub>i</sub>]</code> denotes the price and weight of the <code>i<sup>th</sup></code> item, respectively.</p> <p>You are also given a <strong>positive</strong> integer <code>capacity</code>.</p> <p>Each item can be divided into two items with ratios <code>part1</code> and <code>part2</code>, where <code>part1 + part2 == 1</code>.</p> <ul> <li>The weight of the first item is <code>weight<sub>i</sub> * part1</code> and the price of the first item is <code>price<sub>i</sub> * part1</code>.</li> <li>Similarly, the weight of the second item is <code>weight<sub>i</sub> * part2</code> and the price of the second item is <code>price<sub>i</sub> * part2</code>.</li> </ul> <p>Return <em><strong>the maximum total price</strong> to fill a bag of capacity</em> <code>capacity</code> <em>with given items</em>. If it is impossible to fill a bag return <code>-1</code>. Answers within <code>10<sup>-5</sup></code> of the <strong>actual answer</strong> will be considered accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> items = [[50,1],[10,8]], capacity = 5 <strong>Output:</strong> 55.00000 <strong>Explanation:</strong> We divide the 2<sup>nd</sup> item into two parts with part1 = 0.5 and part2 = 0.5. The price and weight of the 1<sup>st</sup> item are 5, 4. And similarly, the price and the weight of the 2<sup>nd</sup> item are 5, 4. The array items after operation becomes [[50,1],[5,4],[5,4]]. To fill a bag with capacity 5 we take the 1<sup>st</sup> element with a price of 50 and the 2<sup>nd</sup> element with a price of 5. It can be proved that 55.0 is the maximum total price that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> items = [[100,30]], capacity = 50 <strong>Output:</strong> -1.00000 <strong>Explanation:</strong> It is impossible to fill a bag with the given item. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= items.length &lt;= 10<sup>5</sup></code></li> <li><code>items[i].length == 2</code></li> <li><code>1 &lt;= price<sub>i</sub>, weight<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= capacity &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: double maxPrice(vector<vector<int>>& items, int capacity) { sort(items.begin(), items.end(), [&](const auto& a, const auto& b) { return a[1] * b[0] < a[0] * b[1]; }); double ans = 0; for (auto& e : items) { int p = e[0], w = e[1]; int v = min(w, capacity); ans += v * 1.0 / w * p; capacity -= v; } return capacity > 0 ? -1 : ans; } };
2,548
Maximum Price to Fill a Bag
Medium
<p>You are given a 2D integer array <code>items</code> where <code>items[i] = [price<sub>i</sub>, weight<sub>i</sub>]</code> denotes the price and weight of the <code>i<sup>th</sup></code> item, respectively.</p> <p>You are also given a <strong>positive</strong> integer <code>capacity</code>.</p> <p>Each item can be divided into two items with ratios <code>part1</code> and <code>part2</code>, where <code>part1 + part2 == 1</code>.</p> <ul> <li>The weight of the first item is <code>weight<sub>i</sub> * part1</code> and the price of the first item is <code>price<sub>i</sub> * part1</code>.</li> <li>Similarly, the weight of the second item is <code>weight<sub>i</sub> * part2</code> and the price of the second item is <code>price<sub>i</sub> * part2</code>.</li> </ul> <p>Return <em><strong>the maximum total price</strong> to fill a bag of capacity</em> <code>capacity</code> <em>with given items</em>. If it is impossible to fill a bag return <code>-1</code>. Answers within <code>10<sup>-5</sup></code> of the <strong>actual answer</strong> will be considered accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> items = [[50,1],[10,8]], capacity = 5 <strong>Output:</strong> 55.00000 <strong>Explanation:</strong> We divide the 2<sup>nd</sup> item into two parts with part1 = 0.5 and part2 = 0.5. The price and weight of the 1<sup>st</sup> item are 5, 4. And similarly, the price and the weight of the 2<sup>nd</sup> item are 5, 4. The array items after operation becomes [[50,1],[5,4],[5,4]]. To fill a bag with capacity 5 we take the 1<sup>st</sup> element with a price of 50 and the 2<sup>nd</sup> element with a price of 5. It can be proved that 55.0 is the maximum total price that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> items = [[100,30]], capacity = 50 <strong>Output:</strong> -1.00000 <strong>Explanation:</strong> It is impossible to fill a bag with the given item. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= items.length &lt;= 10<sup>5</sup></code></li> <li><code>items[i].length == 2</code></li> <li><code>1 &lt;= price<sub>i</sub>, weight<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= capacity &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func maxPrice(items [][]int, capacity int) (ans float64) { sort.Slice(items, func(i, j int) bool { return items[i][1]*items[j][0] < items[i][0]*items[j][1] }) for _, e := range items { p, w := e[0], e[1] v := min(w, capacity) ans += float64(v) / float64(w) * float64(p) capacity -= v } if capacity > 0 { return -1 } return }
2,548
Maximum Price to Fill a Bag
Medium
<p>You are given a 2D integer array <code>items</code> where <code>items[i] = [price<sub>i</sub>, weight<sub>i</sub>]</code> denotes the price and weight of the <code>i<sup>th</sup></code> item, respectively.</p> <p>You are also given a <strong>positive</strong> integer <code>capacity</code>.</p> <p>Each item can be divided into two items with ratios <code>part1</code> and <code>part2</code>, where <code>part1 + part2 == 1</code>.</p> <ul> <li>The weight of the first item is <code>weight<sub>i</sub> * part1</code> and the price of the first item is <code>price<sub>i</sub> * part1</code>.</li> <li>Similarly, the weight of the second item is <code>weight<sub>i</sub> * part2</code> and the price of the second item is <code>price<sub>i</sub> * part2</code>.</li> </ul> <p>Return <em><strong>the maximum total price</strong> to fill a bag of capacity</em> <code>capacity</code> <em>with given items</em>. If it is impossible to fill a bag return <code>-1</code>. Answers within <code>10<sup>-5</sup></code> of the <strong>actual answer</strong> will be considered accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> items = [[50,1],[10,8]], capacity = 5 <strong>Output:</strong> 55.00000 <strong>Explanation:</strong> We divide the 2<sup>nd</sup> item into two parts with part1 = 0.5 and part2 = 0.5. The price and weight of the 1<sup>st</sup> item are 5, 4. And similarly, the price and the weight of the 2<sup>nd</sup> item are 5, 4. The array items after operation becomes [[50,1],[5,4],[5,4]]. To fill a bag with capacity 5 we take the 1<sup>st</sup> element with a price of 50 and the 2<sup>nd</sup> element with a price of 5. It can be proved that 55.0 is the maximum total price that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> items = [[100,30]], capacity = 50 <strong>Output:</strong> -1.00000 <strong>Explanation:</strong> It is impossible to fill a bag with the given item. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= items.length &lt;= 10<sup>5</sup></code></li> <li><code>items[i].length == 2</code></li> <li><code>1 &lt;= price<sub>i</sub>, weight<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= capacity &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public double maxPrice(int[][] items, int capacity) { Arrays.sort(items, (a, b) -> a[1] * b[0] - a[0] * b[1]); double ans = 0; for (var e : items) { int p = e[0], w = e[1]; int v = Math.min(w, capacity); ans += v * 1.0 / w * p; capacity -= v; } return capacity > 0 ? -1 : ans; } }
2,548
Maximum Price to Fill a Bag
Medium
<p>You are given a 2D integer array <code>items</code> where <code>items[i] = [price<sub>i</sub>, weight<sub>i</sub>]</code> denotes the price and weight of the <code>i<sup>th</sup></code> item, respectively.</p> <p>You are also given a <strong>positive</strong> integer <code>capacity</code>.</p> <p>Each item can be divided into two items with ratios <code>part1</code> and <code>part2</code>, where <code>part1 + part2 == 1</code>.</p> <ul> <li>The weight of the first item is <code>weight<sub>i</sub> * part1</code> and the price of the first item is <code>price<sub>i</sub> * part1</code>.</li> <li>Similarly, the weight of the second item is <code>weight<sub>i</sub> * part2</code> and the price of the second item is <code>price<sub>i</sub> * part2</code>.</li> </ul> <p>Return <em><strong>the maximum total price</strong> to fill a bag of capacity</em> <code>capacity</code> <em>with given items</em>. If it is impossible to fill a bag return <code>-1</code>. Answers within <code>10<sup>-5</sup></code> of the <strong>actual answer</strong> will be considered accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> items = [[50,1],[10,8]], capacity = 5 <strong>Output:</strong> 55.00000 <strong>Explanation:</strong> We divide the 2<sup>nd</sup> item into two parts with part1 = 0.5 and part2 = 0.5. The price and weight of the 1<sup>st</sup> item are 5, 4. And similarly, the price and the weight of the 2<sup>nd</sup> item are 5, 4. The array items after operation becomes [[50,1],[5,4],[5,4]]. To fill a bag with capacity 5 we take the 1<sup>st</sup> element with a price of 50 and the 2<sup>nd</sup> element with a price of 5. It can be proved that 55.0 is the maximum total price that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> items = [[100,30]], capacity = 50 <strong>Output:</strong> -1.00000 <strong>Explanation:</strong> It is impossible to fill a bag with the given item. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= items.length &lt;= 10<sup>5</sup></code></li> <li><code>items[i].length == 2</code></li> <li><code>1 &lt;= price<sub>i</sub>, weight<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= capacity &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def maxPrice(self, items: List[List[int]], capacity: int) -> float: ans = 0 for p, w in sorted(items, key=lambda x: x[1] / x[0]): v = min(w, capacity) ans += v / w * p capacity -= v return -1 if capacity else ans
2,548
Maximum Price to Fill a Bag
Medium
<p>You are given a 2D integer array <code>items</code> where <code>items[i] = [price<sub>i</sub>, weight<sub>i</sub>]</code> denotes the price and weight of the <code>i<sup>th</sup></code> item, respectively.</p> <p>You are also given a <strong>positive</strong> integer <code>capacity</code>.</p> <p>Each item can be divided into two items with ratios <code>part1</code> and <code>part2</code>, where <code>part1 + part2 == 1</code>.</p> <ul> <li>The weight of the first item is <code>weight<sub>i</sub> * part1</code> and the price of the first item is <code>price<sub>i</sub> * part1</code>.</li> <li>Similarly, the weight of the second item is <code>weight<sub>i</sub> * part2</code> and the price of the second item is <code>price<sub>i</sub> * part2</code>.</li> </ul> <p>Return <em><strong>the maximum total price</strong> to fill a bag of capacity</em> <code>capacity</code> <em>with given items</em>. If it is impossible to fill a bag return <code>-1</code>. Answers within <code>10<sup>-5</sup></code> of the <strong>actual answer</strong> will be considered accepted.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> items = [[50,1],[10,8]], capacity = 5 <strong>Output:</strong> 55.00000 <strong>Explanation:</strong> We divide the 2<sup>nd</sup> item into two parts with part1 = 0.5 and part2 = 0.5. The price and weight of the 1<sup>st</sup> item are 5, 4. And similarly, the price and the weight of the 2<sup>nd</sup> item are 5, 4. The array items after operation becomes [[50,1],[5,4],[5,4]]. To fill a bag with capacity 5 we take the 1<sup>st</sup> element with a price of 50 and the 2<sup>nd</sup> element with a price of 5. It can be proved that 55.0 is the maximum total price that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> items = [[100,30]], capacity = 50 <strong>Output:</strong> -1.00000 <strong>Explanation:</strong> It is impossible to fill a bag with the given item. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= items.length &lt;= 10<sup>5</sup></code></li> <li><code>items[i].length == 2</code></li> <li><code>1 &lt;= price<sub>i</sub>, weight<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= capacity &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function maxPrice(items: number[][], capacity: number): number { items.sort((a, b) => a[1] * b[0] - a[0] * b[1]); let ans = 0; for (const [p, w] of items) { const v = Math.min(w, capacity); ans += (v / w) * p; capacity -= v; } return capacity ? -1 : ans; }
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
C++
class Solution { public: int distinctIntegers(int n) { return max(1, n - 1); } };
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
Go
func distinctIntegers(n int) int { return max(1, n-1) }
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
Java
class Solution { public int distinctIntegers(int n) { return Math.max(1, n - 1); } }
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
Python
class Solution: def distinctIntegers(self, n: int) -> int: return max(1, n - 1)
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
Rust
impl Solution { pub fn distinct_integers(n: i32) -> i32 { (1).max(n - 1) } }
2,549
Count Distinct Numbers on Board
Easy
<p>You are given a positive integer <code>n</code>, that is initially placed on a board. Every day, for <code>10<sup>9</sup></code> days, you perform the following procedure:</p> <ul> <li>For each number <code>x</code> present on the board, find all numbers <code>1 &lt;= i &lt;= n</code> such that <code>x % i == 1</code>.</li> <li>Then, place those numbers on the board.</li> </ul> <p>Return<em> the number of <strong>distinct</strong> integers present on the board after</em> <code>10<sup>9</sup></code> <em>days have elapsed</em>.</p> <p><strong>Note:</strong></p> <ul> <li>Once a number is placed on the board, it will remain on it until the end.</li> <li><code>%</code>&nbsp;stands&nbsp;for the modulo operation. For example,&nbsp;<code>14 % 3</code> is <code>2</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 4 <strong>Explanation:</strong> Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> </ul>
Array; Hash Table; Math; Simulation
TypeScript
function distinctIntegers(n: number): number { return Math.max(1, n - 1); }
2,550
Count Collisions of Monkeys on a Polygon
Medium
<p>There is a regular convex polygon with <code>n</code> vertices. The vertices are labeled from <code>0</code> to <code>n - 1</code> in a clockwise direction, and each vertex has <strong>exactly one monkey</strong>. The following figure shows a convex polygon of <code>6</code> vertices.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2550.Count%20Collisions%20of%20Monkeys%20on%20a%20Polygon/images/hexagon.jpg" style="width: 300px; height: 293px;" /> <p>Simultaneously, each monkey moves to a neighboring vertex. A <strong>collision</strong> happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.</p> <p>Return the number of ways the monkeys can move so that at least <strong>one collision</strong> happens. Since the answer may be very large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 8 total possible movements.<br /> Two ways such that they collide at some point are:</p> <ul> <li>Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.</li> <li>Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
C++
class Solution { public: int monkeyMove(int n) { const int mod = 1e9 + 7; using ll = long long; auto qpow = [&](ll a, int n) { ll ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return ans; }; return (qpow(2, n) - 2 + mod) % mod; } };
2,550
Count Collisions of Monkeys on a Polygon
Medium
<p>There is a regular convex polygon with <code>n</code> vertices. The vertices are labeled from <code>0</code> to <code>n - 1</code> in a clockwise direction, and each vertex has <strong>exactly one monkey</strong>. The following figure shows a convex polygon of <code>6</code> vertices.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2550.Count%20Collisions%20of%20Monkeys%20on%20a%20Polygon/images/hexagon.jpg" style="width: 300px; height: 293px;" /> <p>Simultaneously, each monkey moves to a neighboring vertex. A <strong>collision</strong> happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.</p> <p>Return the number of ways the monkeys can move so that at least <strong>one collision</strong> happens. Since the answer may be very large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 8 total possible movements.<br /> Two ways such that they collide at some point are:</p> <ul> <li>Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.</li> <li>Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Go
func monkeyMove(n int) int { 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 } return (qpow(2, n) - 2 + mod) % mod }
2,550
Count Collisions of Monkeys on a Polygon
Medium
<p>There is a regular convex polygon with <code>n</code> vertices. The vertices are labeled from <code>0</code> to <code>n - 1</code> in a clockwise direction, and each vertex has <strong>exactly one monkey</strong>. The following figure shows a convex polygon of <code>6</code> vertices.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2550.Count%20Collisions%20of%20Monkeys%20on%20a%20Polygon/images/hexagon.jpg" style="width: 300px; height: 293px;" /> <p>Simultaneously, each monkey moves to a neighboring vertex. A <strong>collision</strong> happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.</p> <p>Return the number of ways the monkeys can move so that at least <strong>one collision</strong> happens. Since the answer may be very large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 8 total possible movements.<br /> Two ways such that they collide at some point are:</p> <ul> <li>Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.</li> <li>Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Java
class Solution { public int monkeyMove(int n) { final int mod = (int) 1e9 + 7; return (qpow(2, n, mod) - 2 + mod) % mod; } private int qpow(long a, int n, int mod) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; } }
2,550
Count Collisions of Monkeys on a Polygon
Medium
<p>There is a regular convex polygon with <code>n</code> vertices. The vertices are labeled from <code>0</code> to <code>n - 1</code> in a clockwise direction, and each vertex has <strong>exactly one monkey</strong>. The following figure shows a convex polygon of <code>6</code> vertices.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2550.Count%20Collisions%20of%20Monkeys%20on%20a%20Polygon/images/hexagon.jpg" style="width: 300px; height: 293px;" /> <p>Simultaneously, each monkey moves to a neighboring vertex. A <strong>collision</strong> happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.</p> <p>Return the number of ways the monkeys can move so that at least <strong>one collision</strong> happens. Since the answer may be very large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 8 total possible movements.<br /> Two ways such that they collide at some point are:</p> <ul> <li>Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.</li> <li>Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Python
class Solution: def monkeyMove(self, n: int) -> int: mod = 10**9 + 7 return (pow(2, n, mod) - 2) % mod
2,550
Count Collisions of Monkeys on a Polygon
Medium
<p>There is a regular convex polygon with <code>n</code> vertices. The vertices are labeled from <code>0</code> to <code>n - 1</code> in a clockwise direction, and each vertex has <strong>exactly one monkey</strong>. The following figure shows a convex polygon of <code>6</code> vertices.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2550.Count%20Collisions%20of%20Monkeys%20on%20a%20Polygon/images/hexagon.jpg" style="width: 300px; height: 293px;" /> <p>Simultaneously, each monkey moves to a neighboring vertex. A <strong>collision</strong> happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.</p> <p>Return the number of ways the monkeys can move so that at least <strong>one collision</strong> happens. Since the answer may be very large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 8 total possible movements.<br /> Two ways such that they collide at some point are:</p> <ul> <li>Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.</li> <li>Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
TypeScript
function monkeyMove(n: number): number { const mod = 10 ** 9 + 7; const qpow = (a: number, n: number): number => { let ans = 1n; for (; n; n >>>= 1) { if (n & 1) { ans = (ans * BigInt(a)) % BigInt(mod); } a = Number((BigInt(a) * BigInt(a)) % BigInt(mod)); } return Number(ans); }; return (qpow(2, n) - 2 + mod) % mod; }
2,551
Put Marbles in Bags
Hard
<p>You have <code>k</code> bags. You are given a <strong>0-indexed</strong> integer array <code>weights</code> where <code>weights[i]</code> is the weight of the <code>i<sup>th</sup></code> marble. You are also given the integer <code>k.</code></p> <p>Divide the marbles into the <code>k</code> bags according to the following rules:</p> <ul> <li>No bag is empty.</li> <li>If the <code>i<sup>th</sup></code> marble and <code>j<sup>th</sup></code> marble are in a bag, then all marbles with an index between the <code>i<sup>th</sup></code> and <code>j<sup>th</sup></code> indices should also be in that same bag.</li> <li>If a bag consists of all the marbles with an index from <code>i</code> to <code>j</code> inclusively, then the cost of the bag is <code>weights[i] + weights[j]</code>.</li> </ul> <p>The <strong>score</strong> after distributing the marbles is the sum of the costs of all the <code>k</code> bags.</p> <p>Return <em>the <strong>difference</strong> between the <strong>maximum</strong> and <strong>minimum</strong> scores among marble distributions</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> weights = [1,3,5,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> weights = [1, 3], k = 2 <strong>Output:</strong> 0 <strong>Explanation:</strong> The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= weights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= weights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: long long putMarbles(vector<int>& weights, int k) { int n = weights.size(); vector<int> arr(n - 1); for (int i = 0; i < n - 1; ++i) { arr[i] = weights[i] + weights[i + 1]; } sort(arr.begin(), arr.end()); long long ans = 0; for (int i = 0; i < k - 1; ++i) { ans -= arr[i]; ans += arr[n - 2 - i]; } return ans; } };
2,551
Put Marbles in Bags
Hard
<p>You have <code>k</code> bags. You are given a <strong>0-indexed</strong> integer array <code>weights</code> where <code>weights[i]</code> is the weight of the <code>i<sup>th</sup></code> marble. You are also given the integer <code>k.</code></p> <p>Divide the marbles into the <code>k</code> bags according to the following rules:</p> <ul> <li>No bag is empty.</li> <li>If the <code>i<sup>th</sup></code> marble and <code>j<sup>th</sup></code> marble are in a bag, then all marbles with an index between the <code>i<sup>th</sup></code> and <code>j<sup>th</sup></code> indices should also be in that same bag.</li> <li>If a bag consists of all the marbles with an index from <code>i</code> to <code>j</code> inclusively, then the cost of the bag is <code>weights[i] + weights[j]</code>.</li> </ul> <p>The <strong>score</strong> after distributing the marbles is the sum of the costs of all the <code>k</code> bags.</p> <p>Return <em>the <strong>difference</strong> between the <strong>maximum</strong> and <strong>minimum</strong> scores among marble distributions</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> weights = [1,3,5,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> weights = [1, 3], k = 2 <strong>Output:</strong> 0 <strong>Explanation:</strong> The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= weights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= weights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func putMarbles(weights []int, k int) (ans int64) { n := len(weights) arr := make([]int, n-1) for i, w := range weights[:n-1] { arr[i] = w + weights[i+1] } sort.Ints(arr) for i := 0; i < k-1; i++ { ans += int64(arr[n-2-i] - arr[i]) } return }
2,551
Put Marbles in Bags
Hard
<p>You have <code>k</code> bags. You are given a <strong>0-indexed</strong> integer array <code>weights</code> where <code>weights[i]</code> is the weight of the <code>i<sup>th</sup></code> marble. You are also given the integer <code>k.</code></p> <p>Divide the marbles into the <code>k</code> bags according to the following rules:</p> <ul> <li>No bag is empty.</li> <li>If the <code>i<sup>th</sup></code> marble and <code>j<sup>th</sup></code> marble are in a bag, then all marbles with an index between the <code>i<sup>th</sup></code> and <code>j<sup>th</sup></code> indices should also be in that same bag.</li> <li>If a bag consists of all the marbles with an index from <code>i</code> to <code>j</code> inclusively, then the cost of the bag is <code>weights[i] + weights[j]</code>.</li> </ul> <p>The <strong>score</strong> after distributing the marbles is the sum of the costs of all the <code>k</code> bags.</p> <p>Return <em>the <strong>difference</strong> between the <strong>maximum</strong> and <strong>minimum</strong> scores among marble distributions</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> weights = [1,3,5,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> weights = [1, 3], k = 2 <strong>Output:</strong> 0 <strong>Explanation:</strong> The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= weights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= weights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public long putMarbles(int[] weights, int k) { int n = weights.length; int[] arr = new int[n - 1]; for (int i = 0; i < n - 1; ++i) { arr[i] = weights[i] + weights[i + 1]; } Arrays.sort(arr); long ans = 0; for (int i = 0; i < k - 1; ++i) { ans -= arr[i]; ans += arr[n - 2 - i]; } return ans; } }
2,551
Put Marbles in Bags
Hard
<p>You have <code>k</code> bags. You are given a <strong>0-indexed</strong> integer array <code>weights</code> where <code>weights[i]</code> is the weight of the <code>i<sup>th</sup></code> marble. You are also given the integer <code>k.</code></p> <p>Divide the marbles into the <code>k</code> bags according to the following rules:</p> <ul> <li>No bag is empty.</li> <li>If the <code>i<sup>th</sup></code> marble and <code>j<sup>th</sup></code> marble are in a bag, then all marbles with an index between the <code>i<sup>th</sup></code> and <code>j<sup>th</sup></code> indices should also be in that same bag.</li> <li>If a bag consists of all the marbles with an index from <code>i</code> to <code>j</code> inclusively, then the cost of the bag is <code>weights[i] + weights[j]</code>.</li> </ul> <p>The <strong>score</strong> after distributing the marbles is the sum of the costs of all the <code>k</code> bags.</p> <p>Return <em>the <strong>difference</strong> between the <strong>maximum</strong> and <strong>minimum</strong> scores among marble distributions</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> weights = [1,3,5,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> weights = [1, 3], k = 2 <strong>Output:</strong> 0 <strong>Explanation:</strong> The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= weights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= weights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def putMarbles(self, weights: List[int], k: int) -> int: arr = sorted(a + b for a, b in pairwise(weights)) return sum(arr[len(arr) - k + 1 :]) - sum(arr[: k - 1])
2,551
Put Marbles in Bags
Hard
<p>You have <code>k</code> bags. You are given a <strong>0-indexed</strong> integer array <code>weights</code> where <code>weights[i]</code> is the weight of the <code>i<sup>th</sup></code> marble. You are also given the integer <code>k.</code></p> <p>Divide the marbles into the <code>k</code> bags according to the following rules:</p> <ul> <li>No bag is empty.</li> <li>If the <code>i<sup>th</sup></code> marble and <code>j<sup>th</sup></code> marble are in a bag, then all marbles with an index between the <code>i<sup>th</sup></code> and <code>j<sup>th</sup></code> indices should also be in that same bag.</li> <li>If a bag consists of all the marbles with an index from <code>i</code> to <code>j</code> inclusively, then the cost of the bag is <code>weights[i] + weights[j]</code>.</li> </ul> <p>The <strong>score</strong> after distributing the marbles is the sum of the costs of all the <code>k</code> bags.</p> <p>Return <em>the <strong>difference</strong> between the <strong>maximum</strong> and <strong>minimum</strong> scores among marble distributions</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> weights = [1,3,5,1], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. Thus, we return their difference 10 - 6 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> weights = [1, 3], k = 2 <strong>Output:</strong> 0 <strong>Explanation:</strong> The only distribution possible is [1],[3]. Since both the maximal and minimal score are the same, we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= weights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= weights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
TypeScript
function putMarbles(weights: number[], k: number): number { const n = weights.length; const arr: number[] = []; for (let i = 0; i < n - 1; ++i) { arr.push(weights[i] + weights[i + 1]); } arr.sort((a, b) => a - b); let ans = 0; for (let i = 0; i < k - 1; ++i) { ans += arr[n - i - 2] - arr[i]; } return ans; }
2,552
Count Increasing Quadruplets
Hard
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> containing all numbers from <code>1</code> to <code>n</code>, return <em>the number of increasing quadruplets</em>.</p> <p>A quadruplet <code>(i, j, k, l)</code> is increasing if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; l &lt; n</code>, and</li> <li><code>nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> - When i = 0, j = 1, k = 2, and l = 3, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. There are no other quadruplets, so we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] &lt; nums[k], we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= nums.length &lt;= 4000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>. <code>nums</code> is a permutation.</li> </ul>
Binary Indexed Tree; Array; Dynamic Programming; Enumeration; Prefix Sum
C++
const int N = 4001; int f[N][N]; int g[N][N]; class Solution { public: long long countQuadruplets(vector<int>& nums) { int n = nums.size(); memset(f, 0, sizeof f); memset(g, 0, sizeof g); for (int j = 1; j < n - 2; ++j) { int cnt = 0; for (int l = j + 1; l < n; ++l) { if (nums[l] > nums[j]) { ++cnt; } } for (int k = j + 1; k < n - 1; ++k) { if (nums[j] > nums[k]) { f[j][k] = cnt; } else { --cnt; } } } long long ans = 0; for (int k = 2; k < n - 1; ++k) { int cnt = 0; for (int i = 0; i < k; ++i) { if (nums[i] < nums[k]) { ++cnt; } } for (int j = k - 1; j > 0; --j) { if (nums[j] > nums[k]) { g[j][k] = cnt; ans += 1ll * f[j][k] * g[j][k]; } else { --cnt; } } } return ans; } };
2,552
Count Increasing Quadruplets
Hard
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> containing all numbers from <code>1</code> to <code>n</code>, return <em>the number of increasing quadruplets</em>.</p> <p>A quadruplet <code>(i, j, k, l)</code> is increasing if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; l &lt; n</code>, and</li> <li><code>nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> - When i = 0, j = 1, k = 2, and l = 3, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. There are no other quadruplets, so we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] &lt; nums[k], we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= nums.length &lt;= 4000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>. <code>nums</code> is a permutation.</li> </ul>
Binary Indexed Tree; Array; Dynamic Programming; Enumeration; Prefix Sum
Go
func countQuadruplets(nums []int) int64 { n := len(nums) f := make([][]int, n) g := make([][]int, n) for i := range f { f[i] = make([]int, n) g[i] = make([]int, n) } for j := 1; j < n-2; j++ { cnt := 0 for l := j + 1; l < n; l++ { if nums[l] > nums[j] { cnt++ } } for k := j + 1; k < n-1; k++ { if nums[j] > nums[k] { f[j][k] = cnt } else { cnt-- } } } ans := 0 for k := 2; k < n-1; k++ { cnt := 0 for i := 0; i < k; i++ { if nums[i] < nums[k] { cnt++ } } for j := k - 1; j > 0; j-- { if nums[j] > nums[k] { g[j][k] = cnt ans += f[j][k] * g[j][k] } else { cnt-- } } } return int64(ans) }
2,552
Count Increasing Quadruplets
Hard
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> containing all numbers from <code>1</code> to <code>n</code>, return <em>the number of increasing quadruplets</em>.</p> <p>A quadruplet <code>(i, j, k, l)</code> is increasing if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; l &lt; n</code>, and</li> <li><code>nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> - When i = 0, j = 1, k = 2, and l = 3, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. There are no other quadruplets, so we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] &lt; nums[k], we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= nums.length &lt;= 4000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>. <code>nums</code> is a permutation.</li> </ul>
Binary Indexed Tree; Array; Dynamic Programming; Enumeration; Prefix Sum
Java
class Solution { public long countQuadruplets(int[] nums) { int n = nums.length; int[][] f = new int[n][n]; int[][] g = new int[n][n]; for (int j = 1; j < n - 2; ++j) { int cnt = 0; for (int l = j + 1; l < n; ++l) { if (nums[l] > nums[j]) { ++cnt; } } for (int k = j + 1; k < n - 1; ++k) { if (nums[j] > nums[k]) { f[j][k] = cnt; } else { --cnt; } } } long ans = 0; for (int k = 2; k < n - 1; ++k) { int cnt = 0; for (int i = 0; i < k; ++i) { if (nums[i] < nums[k]) { ++cnt; } } for (int j = k - 1; j > 0; --j) { if (nums[j] > nums[k]) { g[j][k] = cnt; ans += (long) f[j][k] * g[j][k]; } else { --cnt; } } } return ans; } }
2,552
Count Increasing Quadruplets
Hard
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> containing all numbers from <code>1</code> to <code>n</code>, return <em>the number of increasing quadruplets</em>.</p> <p>A quadruplet <code>(i, j, k, l)</code> is increasing if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; l &lt; n</code>, and</li> <li><code>nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,4,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> - When i = 0, j = 1, k = 2, and l = 3, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. - When i = 0, j = 1, k = 2, and l = 4, nums[i] &lt; nums[k] &lt; nums[j] &lt; nums[l]. There are no other quadruplets, so we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] &lt; nums[k], we return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>4 &lt;= nums.length &lt;= 4000</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li>All the integers of <code>nums</code> are <strong>unique</strong>. <code>nums</code> is a permutation.</li> </ul>
Binary Indexed Tree; Array; Dynamic Programming; Enumeration; Prefix Sum
Python
class Solution: def countQuadruplets(self, nums: List[int]) -> int: n = len(nums) f = [[0] * n for _ in range(n)] g = [[0] * n for _ in range(n)] for j in range(1, n - 2): cnt = sum(nums[l] > nums[j] for l in range(j + 1, n)) for k in range(j + 1, n - 1): if nums[j] > nums[k]: f[j][k] = cnt else: cnt -= 1 for k in range(2, n - 1): cnt = sum(nums[i] < nums[k] for i in range(k)) for j in range(k - 1, 0, -1): if nums[j] > nums[k]: g[j][k] = cnt else: cnt -= 1 return sum( f[j][k] * g[j][k] for j in range(1, n - 2) for k in range(j + 1, n - 1) )
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
C
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* separateDigits(int* nums, int numsSize, int* returnSize) { int n = 0; for (int i = 0; i < numsSize; i++) { int t = nums[i]; while (t != 0) { t /= 10; n++; } } int* ans = malloc(sizeof(int) * n); for (int i = numsSize - 1, j = n - 1; i >= 0; i--) { int t = nums[i]; while (t != 0) { ans[j--] = t % 10; t /= 10; } } *returnSize = n; return ans; }
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
C++
class Solution { public: vector<int> separateDigits(vector<int>& nums) { vector<int> ans; for (int x : nums) { vector<int> t; for (; x; x /= 10) { t.push_back(x % 10); } while (t.size()) { ans.push_back(t.back()); t.pop_back(); } } return ans; } };
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
Go
func separateDigits(nums []int) (ans []int) { for _, x := range nums { t := []int{} for ; x > 0; x /= 10 { t = append(t, x%10) } for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 { t[i], t[j] = t[j], t[i] } ans = append(ans, t...) } return }
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
Java
class Solution { public int[] separateDigits(int[] nums) { List<Integer> res = new ArrayList<>(); for (int x : nums) { List<Integer> t = new ArrayList<>(); for (; x > 0; x /= 10) { t.add(x % 10); } Collections.reverse(t); res.addAll(t); } int[] ans = new int[res.size()]; for (int i = 0; i < ans.length; ++i) { ans[i] = res.get(i); } return ans; } }
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
Python
class Solution: def separateDigits(self, nums: List[int]) -> List[int]: ans = [] for x in nums: t = [] while x: t.append(x % 10) x //= 10 ans.extend(t[::-1]) return ans
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
Rust
impl Solution { pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> { let mut ans = Vec::new(); for &num in nums.iter() { let mut num = num; let mut t = Vec::new(); while num != 0 { t.push(num % 10); num /= 10; } t.into_iter().rev().for_each(|v| ans.push(v)); } ans } }
2,553
Separate the Digits in an Array
Easy
<p>Given an array of positive integers <code>nums</code>, return <em>an array </em><code>answer</code><em> that consists of the digits of each integer in </em><code>nums</code><em> after separating them in <strong>the same order</strong> they appear in </em><code>nums</code>.</p> <p>To separate the digits of an integer is to get all the digits it has in the same order.</p> <ul> <li>For example, for the integer <code>10921</code>, the separation of its digits is <code>[1,0,9,2,1]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [13,25,83,77] <strong>Output:</strong> [1,3,2,5,8,3,7,7] <strong>Explanation:</strong> - The separation of 13 is [1,3]. - The separation of 25 is [2,5]. - The separation of 83 is [8,3]. - The separation of 77 is [7,7]. answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,1,3,9] <strong>Output:</strong> [7,1,3,9] <strong>Explanation:</strong> The separation of each integer in nums is itself. answer = [7,1,3,9]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Simulation
TypeScript
function separateDigits(nums: number[]): number[] { const ans: number[] = []; for (let num of nums) { const t: number[] = []; while (num) { t.push(num % 10); num = Math.floor(num / 10); } ans.push(...t.reverse()); } return ans; }
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
C
int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; } int maxCount(int* banned, int bannedSize, int n, int maxSum) { qsort(banned, bannedSize, sizeof(int), cmp); int sum = 0; int ans = 0; for (int i = 1, j = 0; i <= n; i++) { if (sum + i > maxSum) { break; } if (j < bannedSize && i == banned[j]) { while (j < bannedSize && i == banned[j]) { j++; } } else { sum += i; ans++; } } return ans; }
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
C++
class Solution { public: int maxCount(vector<int>& banned, int n, int maxSum) { unordered_set<int> ban(banned.begin(), banned.end()); int ans = 0, s = 0; for (int i = 1; i <= n && s + i <= maxSum; ++i) { if (!ban.count(i)) { ++ans; s += i; } } return ans; } };
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
Go
func maxCount(banned []int, n int, maxSum int) (ans int) { ban := map[int]bool{} for _, x := range banned { ban[x] = true } s := 0 for i := 1; i <= n && s+i <= maxSum; i++ { if !ban[i] { ans++ s += i } } return }
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
Java
class Solution { public int maxCount(int[] banned, int n, int maxSum) { Set<Integer> ban = new HashSet<>(banned.length); for (int x : banned) { ban.add(x); } int ans = 0, s = 0; for (int i = 1; i <= n && s + i <= maxSum; ++i) { if (!ban.contains(i)) { ++ans; s += i; } } return ans; } }
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
Python
class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: ans = s = 0 ban = set(banned) for i in range(1, n + 1): if s + i > maxSum: break if i not in ban: ans += 1 s += i return ans
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
Rust
use std::collections::HashSet; impl Solution { pub fn max_count(banned: Vec<i32>, n: i32, max_sum: i32) -> i32 { let mut set = banned.into_iter().collect::<HashSet<i32>>(); let mut sum = 0; let mut ans = 0; for i in 1..=n { if sum + i > max_sum { break; } if set.contains(&i) { continue; } sum += i; ans += 1; } ans } }
2,554
Maximum Number of Integers to Choose From a Range I
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6 <strong>Output:</strong> 2 <strong>Explanation:</strong> You can choose the integers 2 and 4. 2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> banned = [11], n = 7, maxSum = 50 <strong>Output:</strong> 7 <strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7. They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Hash Table; Binary Search; Sorting
TypeScript
function maxCount(banned: number[], n: number, maxSum: number): number { const set = new Set(banned); let sum = 0; let ans = 0; for (let i = 1; i <= n; i++) { if (i + sum > maxSum) { break; } if (set.has(i)) { continue; } sum += i; ans++; } return ans; }
2,555
Maximize Win From Two Segments
Medium
<p>There are some prizes on the <strong>X-axis</strong>. You are given an integer array <code>prizePositions</code> that is <strong>sorted in non-decreasing order</strong>, where <code>prizePositions[i]</code> is the position of the <code>i<sup>th</sup></code> prize. There could be different prizes at the same position on the line. You are also given an integer <code>k</code>.</p> <p>You are allowed to select two segments with integer endpoints. The length of each segment must be <code>k</code>. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.</p> <ul> <li>For example if <code>k = 2</code>, you can choose segments <code>[1, 3]</code> and <code>[2, 4]</code>, and you will win any prize <font face="monospace">i</font> that satisfies <code>1 &lt;= prizePositions[i] &lt;= 3</code> or <code>2 &lt;= prizePositions[i] &lt;= 4</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of prizes you can win if you choose the two segments optimally</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,1,2,2,3,3,5], k = 2 <strong>Output:</strong> 7 <strong>Explanation:</strong> In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,2,3,4], k = 0 <strong>Output:</strong> 2 <strong>Explanation:</strong> For this example, <strong>one choice</strong> for the segments is <code>[3, 3]</code> and <code>[4, 4],</code> and you will be able to get <code>2</code> prizes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prizePositions.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prizePositions[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup> </code></li> <li><code>prizePositions</code> is sorted in non-decreasing order.</li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Binary Search; Sliding Window
C++
class Solution { public: int maximizeWin(vector<int>& prizePositions, int k) { int n = prizePositions.size(); vector<int> f(n + 1); int ans = 0; for (int i = 1; i <= n; ++i) { int x = prizePositions[i - 1]; int j = lower_bound(prizePositions.begin(), prizePositions.end(), x - k) - prizePositions.begin(); ans = max(ans, f[j] + i - j); f[i] = max(f[i - 1], i - j); } return ans; } };
2,555
Maximize Win From Two Segments
Medium
<p>There are some prizes on the <strong>X-axis</strong>. You are given an integer array <code>prizePositions</code> that is <strong>sorted in non-decreasing order</strong>, where <code>prizePositions[i]</code> is the position of the <code>i<sup>th</sup></code> prize. There could be different prizes at the same position on the line. You are also given an integer <code>k</code>.</p> <p>You are allowed to select two segments with integer endpoints. The length of each segment must be <code>k</code>. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.</p> <ul> <li>For example if <code>k = 2</code>, you can choose segments <code>[1, 3]</code> and <code>[2, 4]</code>, and you will win any prize <font face="monospace">i</font> that satisfies <code>1 &lt;= prizePositions[i] &lt;= 3</code> or <code>2 &lt;= prizePositions[i] &lt;= 4</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of prizes you can win if you choose the two segments optimally</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,1,2,2,3,3,5], k = 2 <strong>Output:</strong> 7 <strong>Explanation:</strong> In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,2,3,4], k = 0 <strong>Output:</strong> 2 <strong>Explanation:</strong> For this example, <strong>one choice</strong> for the segments is <code>[3, 3]</code> and <code>[4, 4],</code> and you will be able to get <code>2</code> prizes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prizePositions.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prizePositions[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup> </code></li> <li><code>prizePositions</code> is sorted in non-decreasing order.</li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Binary Search; Sliding Window
Go
func maximizeWin(prizePositions []int, k int) (ans int) { n := len(prizePositions) f := make([]int, n+1) for i, x := range prizePositions { j := sort.Search(n, func(h int) bool { return prizePositions[h] >= x-k }) ans = max(ans, f[j]+i-j+1) f[i+1] = max(f[i], i-j+1) } return }
2,555
Maximize Win From Two Segments
Medium
<p>There are some prizes on the <strong>X-axis</strong>. You are given an integer array <code>prizePositions</code> that is <strong>sorted in non-decreasing order</strong>, where <code>prizePositions[i]</code> is the position of the <code>i<sup>th</sup></code> prize. There could be different prizes at the same position on the line. You are also given an integer <code>k</code>.</p> <p>You are allowed to select two segments with integer endpoints. The length of each segment must be <code>k</code>. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.</p> <ul> <li>For example if <code>k = 2</code>, you can choose segments <code>[1, 3]</code> and <code>[2, 4]</code>, and you will win any prize <font face="monospace">i</font> that satisfies <code>1 &lt;= prizePositions[i] &lt;= 3</code> or <code>2 &lt;= prizePositions[i] &lt;= 4</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of prizes you can win if you choose the two segments optimally</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,1,2,2,3,3,5], k = 2 <strong>Output:</strong> 7 <strong>Explanation:</strong> In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,2,3,4], k = 0 <strong>Output:</strong> 2 <strong>Explanation:</strong> For this example, <strong>one choice</strong> for the segments is <code>[3, 3]</code> and <code>[4, 4],</code> and you will be able to get <code>2</code> prizes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prizePositions.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prizePositions[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup> </code></li> <li><code>prizePositions</code> is sorted in non-decreasing order.</li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Binary Search; Sliding Window
Java
class Solution { public int maximizeWin(int[] prizePositions, int k) { int n = prizePositions.length; int[] f = new int[n + 1]; int ans = 0; for (int i = 1; i <= n; ++i) { int x = prizePositions[i - 1]; int j = search(prizePositions, x - k); ans = Math.max(ans, f[j] + i - j); f[i] = Math.max(f[i - 1], i - j); } return ans; } private int search(int[] nums, int x) { int left = 0, right = nums.length; while (left < right) { int mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } }
2,555
Maximize Win From Two Segments
Medium
<p>There are some prizes on the <strong>X-axis</strong>. You are given an integer array <code>prizePositions</code> that is <strong>sorted in non-decreasing order</strong>, where <code>prizePositions[i]</code> is the position of the <code>i<sup>th</sup></code> prize. There could be different prizes at the same position on the line. You are also given an integer <code>k</code>.</p> <p>You are allowed to select two segments with integer endpoints. The length of each segment must be <code>k</code>. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.</p> <ul> <li>For example if <code>k = 2</code>, you can choose segments <code>[1, 3]</code> and <code>[2, 4]</code>, and you will win any prize <font face="monospace">i</font> that satisfies <code>1 &lt;= prizePositions[i] &lt;= 3</code> or <code>2 &lt;= prizePositions[i] &lt;= 4</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of prizes you can win if you choose the two segments optimally</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,1,2,2,3,3,5], k = 2 <strong>Output:</strong> 7 <strong>Explanation:</strong> In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,2,3,4], k = 0 <strong>Output:</strong> 2 <strong>Explanation:</strong> For this example, <strong>one choice</strong> for the segments is <code>[3, 3]</code> and <code>[4, 4],</code> and you will be able to get <code>2</code> prizes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prizePositions.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prizePositions[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup> </code></li> <li><code>prizePositions</code> is sorted in non-decreasing order.</li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Binary Search; Sliding Window
Python
class Solution: def maximizeWin(self, prizePositions: List[int], k: int) -> int: n = len(prizePositions) f = [0] * (n + 1) ans = 0 for i, x in enumerate(prizePositions, 1): j = bisect_left(prizePositions, x - k) ans = max(ans, f[j] + i - j) f[i] = max(f[i - 1], i - j) return ans
2,555
Maximize Win From Two Segments
Medium
<p>There are some prizes on the <strong>X-axis</strong>. You are given an integer array <code>prizePositions</code> that is <strong>sorted in non-decreasing order</strong>, where <code>prizePositions[i]</code> is the position of the <code>i<sup>th</sup></code> prize. There could be different prizes at the same position on the line. You are also given an integer <code>k</code>.</p> <p>You are allowed to select two segments with integer endpoints. The length of each segment must be <code>k</code>. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.</p> <ul> <li>For example if <code>k = 2</code>, you can choose segments <code>[1, 3]</code> and <code>[2, 4]</code>, and you will win any prize <font face="monospace">i</font> that satisfies <code>1 &lt;= prizePositions[i] &lt;= 3</code> or <code>2 &lt;= prizePositions[i] &lt;= 4</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of prizes you can win if you choose the two segments optimally</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,1,2,2,3,3,5], k = 2 <strong>Output:</strong> 7 <strong>Explanation:</strong> In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prizePositions = [1,2,3,4], k = 0 <strong>Output:</strong> 2 <strong>Explanation:</strong> For this example, <strong>one choice</strong> for the segments is <code>[3, 3]</code> and <code>[4, 4],</code> and you will be able to get <code>2</code> prizes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prizePositions.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= prizePositions[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup> </code></li> <li><code>prizePositions</code> is sorted in non-decreasing order.</li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Binary Search; Sliding Window
TypeScript
function maximizeWin(prizePositions: number[], k: number): number { const n = prizePositions.length; const f: number[] = Array(n + 1).fill(0); let ans = 0; const search = (x: number): number => { let left = 0; let right = n; while (left < right) { const mid = (left + right) >> 1; if (prizePositions[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; }; for (let i = 1; i <= n; ++i) { const x = prizePositions[i - 1]; const j = search(x - k); ans = Math.max(ans, f[j] + i - j); f[i] = Math.max(f[i - 1], i - j); } return ans; }
2,556
Disconnect Path in a Binary Matrix by at Most One Flip
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> <strong>binary</strong> matrix <code>grid</code>. You can move from a cell <code>(row, col)</code> to any of the cells <code>(row + 1, col)</code> or <code>(row, col + 1)</code> that has the value <code>1</code>.&nbsp;The matrix is <strong>disconnected</strong> if there is no path from <code>(0, 0)</code> to <code>(m - 1, n - 1)</code>.</p> <p>You can flip the value of <strong>at most one</strong> (possibly none) cell. You <strong>cannot flip</strong> the cells <code>(0, 0)</code> and <code>(m - 1, n - 1)</code>.</p> <p>Return <code>true</code> <em>if it is possible to make the matrix disconnect or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Note</strong> that flipping a cell changes its value from <code>0</code> to <code>1</code> or from <code>1</code> to <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid2drawio.png" style="width: 441px; height: 151px;" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,0],[1,1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid3drawio.png" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]] <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 1000</code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li><code>grid[0][0] == grid[m - 1][n - 1] == 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Dynamic Programming; Matrix
C++
class Solution { public: bool isPossibleToCutPath(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); function<bool(int, int)> dfs = [&](int i, int j) -> bool { if (i >= m || j >= n || grid[i][j] == 0) { return false; } if (i == m - 1 && j == n - 1) { return true; } grid[i][j] = 0; return dfs(i + 1, j) || dfs(i, j + 1); }; bool a = dfs(0, 0); grid[0][0] = grid[m - 1][n - 1] = 1; bool b = dfs(0, 0); return !(a && b); } };
2,556
Disconnect Path in a Binary Matrix by at Most One Flip
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> <strong>binary</strong> matrix <code>grid</code>. You can move from a cell <code>(row, col)</code> to any of the cells <code>(row + 1, col)</code> or <code>(row, col + 1)</code> that has the value <code>1</code>.&nbsp;The matrix is <strong>disconnected</strong> if there is no path from <code>(0, 0)</code> to <code>(m - 1, n - 1)</code>.</p> <p>You can flip the value of <strong>at most one</strong> (possibly none) cell. You <strong>cannot flip</strong> the cells <code>(0, 0)</code> and <code>(m - 1, n - 1)</code>.</p> <p>Return <code>true</code> <em>if it is possible to make the matrix disconnect or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Note</strong> that flipping a cell changes its value from <code>0</code> to <code>1</code> or from <code>1</code> to <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid2drawio.png" style="width: 441px; height: 151px;" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,0],[1,1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid3drawio.png" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]] <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 1000</code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li><code>grid[0][0] == grid[m - 1][n - 1] == 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Dynamic Programming; Matrix
Go
func isPossibleToCutPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) var dfs func(i, j int) bool dfs = func(i, j int) bool { if i >= m || j >= n || grid[i][j] == 0 { return false } if i == m-1 && j == n-1 { return true } grid[i][j] = 0 return dfs(i+1, j) || dfs(i, j+1) } a := dfs(0, 0) grid[0][0], grid[m-1][n-1] = 1, 1 b := dfs(0, 0) return !(a && b) }
2,556
Disconnect Path in a Binary Matrix by at Most One Flip
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> <strong>binary</strong> matrix <code>grid</code>. You can move from a cell <code>(row, col)</code> to any of the cells <code>(row + 1, col)</code> or <code>(row, col + 1)</code> that has the value <code>1</code>.&nbsp;The matrix is <strong>disconnected</strong> if there is no path from <code>(0, 0)</code> to <code>(m - 1, n - 1)</code>.</p> <p>You can flip the value of <strong>at most one</strong> (possibly none) cell. You <strong>cannot flip</strong> the cells <code>(0, 0)</code> and <code>(m - 1, n - 1)</code>.</p> <p>Return <code>true</code> <em>if it is possible to make the matrix disconnect or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Note</strong> that flipping a cell changes its value from <code>0</code> to <code>1</code> or from <code>1</code> to <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid2drawio.png" style="width: 441px; height: 151px;" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,0],[1,1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid3drawio.png" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]] <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 1000</code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li><code>grid[0][0] == grid[m - 1][n - 1] == 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Dynamic Programming; Matrix
Java
class Solution { private int[][] grid; private int m; private int n; public boolean isPossibleToCutPath(int[][] grid) { this.grid = grid; m = grid.length; n = grid[0].length; boolean a = dfs(0, 0); grid[0][0] = 1; grid[m - 1][n - 1] = 1; boolean b = dfs(0, 0); return !(a && b); } private boolean dfs(int i, int j) { if (i >= m || j >= n || grid[i][j] == 0) { return false; } if (i == m - 1 && j == n - 1) { return true; } grid[i][j] = 0; return dfs(i + 1, j) || dfs(i, j + 1); } }
2,556
Disconnect Path in a Binary Matrix by at Most One Flip
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> <strong>binary</strong> matrix <code>grid</code>. You can move from a cell <code>(row, col)</code> to any of the cells <code>(row + 1, col)</code> or <code>(row, col + 1)</code> that has the value <code>1</code>.&nbsp;The matrix is <strong>disconnected</strong> if there is no path from <code>(0, 0)</code> to <code>(m - 1, n - 1)</code>.</p> <p>You can flip the value of <strong>at most one</strong> (possibly none) cell. You <strong>cannot flip</strong> the cells <code>(0, 0)</code> and <code>(m - 1, n - 1)</code>.</p> <p>Return <code>true</code> <em>if it is possible to make the matrix disconnect or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Note</strong> that flipping a cell changes its value from <code>0</code> to <code>1</code> or from <code>1</code> to <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid2drawio.png" style="width: 441px; height: 151px;" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,0],[1,1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid3drawio.png" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]] <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 1000</code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li><code>grid[0][0] == grid[m - 1][n - 1] == 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Dynamic Programming; Matrix
Python
class Solution: def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: def dfs(i, j): if i >= m or j >= n or grid[i][j] == 0: return False grid[i][j] = 0 if i == m - 1 and j == n - 1: return True return dfs(i + 1, j) or dfs(i, j + 1) m, n = len(grid), len(grid[0]) a = dfs(0, 0) grid[0][0] = grid[-1][-1] = 1 b = dfs(0, 0) return not (a and b)
2,556
Disconnect Path in a Binary Matrix by at Most One Flip
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> <strong>binary</strong> matrix <code>grid</code>. You can move from a cell <code>(row, col)</code> to any of the cells <code>(row + 1, col)</code> or <code>(row, col + 1)</code> that has the value <code>1</code>.&nbsp;The matrix is <strong>disconnected</strong> if there is no path from <code>(0, 0)</code> to <code>(m - 1, n - 1)</code>.</p> <p>You can flip the value of <strong>at most one</strong> (possibly none) cell. You <strong>cannot flip</strong> the cells <code>(0, 0)</code> and <code>(m - 1, n - 1)</code>.</p> <p>Return <code>true</code> <em>if it is possible to make the matrix disconnect or </em><code>false</code><em> otherwise</em>.</p> <p><strong>Note</strong> that flipping a cell changes its value from <code>0</code> to <code>1</code> or from <code>1</code> to <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid2drawio.png" style="width: 441px; height: 151px;" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,0],[1,1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2556.Disconnect%20Path%20in%20a%20Binary%20Matrix%20by%20at%20Most%20One%20Flip/images/yetgrid3drawio.png" /> <pre> <strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]] <strong>Output:</strong> false <strong>Explanation:</strong> It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 1000</code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li> <li><code>grid[0][0] == grid[m - 1][n - 1] == 1</code></li> </ul>
Depth-First Search; Breadth-First Search; Array; Dynamic Programming; Matrix
TypeScript
function isPossibleToCutPath(grid: number[][]): boolean { const m = grid.length; const n = grid[0].length; const dfs = (i: number, j: number): boolean => { if (i >= m || j >= n || grid[i][j] !== 1) { return false; } grid[i][j] = 0; if (i === m - 1 && j === n - 1) { return true; } return dfs(i + 1, j) || dfs(i, j + 1); }; const a = dfs(0, 0); grid[0][0] = 1; grid[m - 1][n - 1] = 1; const b = dfs(0, 0); return !(a && b); }
2,557
Maximum Number of Integers to Choose From a Range II
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,4,6], n = 6, maxSum = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> You can choose the integer 3. 3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [4,3,5,6], n = 7, maxSum = 18 <strong>Output:</strong> 3 <strong>Explanation:</strong> You can choose the integers 1, 2, and 7. All these integers are in the range [1, 7], all do not appear in banned, and their sum is 10, which does not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= banned[i] &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>15</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
C++
class Solution { public: int maxCount(vector<int>& banned, int n, long long maxSum) { banned.push_back(0); banned.push_back(n + 1); sort(banned.begin(), banned.end()); banned.erase(unique(banned.begin(), banned.end()), banned.end()); int ans = 0; for (int k = 1; k < banned.size(); ++k) { int i = banned[k - 1], j = banned[k]; int left = 0, right = j - i - 1; while (left < right) { int mid = left + ((right - left + 1) / 2); if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { left = mid; } else { right = mid - 1; } } ans += left; maxSum -= (i + 1 + i + left) * 1LL * left / 2; if (maxSum <= 0) { break; } } return ans; } };
2,557
Maximum Number of Integers to Choose From a Range II
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,4,6], n = 6, maxSum = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> You can choose the integer 3. 3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [4,3,5,6], n = 7, maxSum = 18 <strong>Output:</strong> 3 <strong>Explanation:</strong> You can choose the integers 1, 2, and 7. All these integers are in the range [1, 7], all do not appear in banned, and their sum is 10, which does not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= banned[i] &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>15</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Go
func maxCount(banned []int, n int, maxSum int64) (ans int) { banned = append(banned, []int{0, n + 1}...) sort.Ints(banned) ban := []int{} for i, x := range banned { if i > 0 && x == banned[i-1] { continue } ban = append(ban, x) } for k := 1; k < len(ban); k++ { i, j := ban[k-1], ban[k] left, right := 0, j-i-1 for left < right { mid := (left + right + 1) >> 1 if int64((i+1+i+mid)*mid/2) <= maxSum { left = mid } else { right = mid - 1 } } ans += left maxSum -= int64((i + 1 + i + left) * left / 2) if maxSum <= 0 { break } } return }
2,557
Maximum Number of Integers to Choose From a Range II
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,4,6], n = 6, maxSum = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> You can choose the integer 3. 3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [4,3,5,6], n = 7, maxSum = 18 <strong>Output:</strong> 3 <strong>Explanation:</strong> You can choose the integers 1, 2, and 7. All these integers are in the range [1, 7], all do not appear in banned, and their sum is 10, which does not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= banned[i] &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>15</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Java
class Solution { public int maxCount(int[] banned, int n, long maxSum) { Set<Integer> black = new HashSet<>(); black.add(0); black.add(n + 1); for (int x : banned) { black.add(x); } List<Integer> ban = new ArrayList<>(black); Collections.sort(ban); int ans = 0; for (int k = 1; k < ban.size(); ++k) { int i = ban.get(k - 1), j = ban.get(k); int left = 0, right = j - i - 1; while (left < right) { int mid = (left + right + 1) >>> 1; if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { left = mid; } else { right = mid - 1; } } ans += left; maxSum -= (i + 1 + i + left) * 1L * left / 2; if (maxSum <= 0) { break; } } return ans; } }
2,557
Maximum Number of Integers to Choose From a Range II
Medium
<p>You are given an integer array <code>banned</code> and two integers <code>n</code> and <code>maxSum</code>. You are choosing some number of integers following the below rules:</p> <ul> <li>The chosen integers have to be in the range <code>[1, n]</code>.</li> <li>Each integer can be chosen <strong>at most once</strong>.</li> <li>The chosen integers should not be in the array <code>banned</code>.</li> <li>The sum of the chosen integers should not exceed <code>maxSum</code>.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of integers you can choose following the mentioned rules</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> banned = [1,4,6], n = 6, maxSum = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> You can choose the integer 3. 3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> banned = [4,3,5,6], n = 7, maxSum = 18 <strong>Output:</strong> 3 <strong>Explanation:</strong> You can choose the integers 1, 2, and 7. All these integers are in the range [1, 7], all do not appear in banned, and their sum is 10, which does not exceed maxSum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= banned.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= banned[i] &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= maxSum &lt;= 10<sup>15</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Python
class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: banned.extend([0, n + 1]) ban = sorted(set(banned)) ans = 0 for i, j in pairwise(ban): left, right = 0, j - i - 1 while left < right: mid = (left + right + 1) >> 1 if (i + 1 + i + mid) * mid // 2 <= maxSum: left = mid else: right = mid - 1 ans += left maxSum -= (i + 1 + i + left) * left // 2 if maxSum <= 0: break return ans
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
C++
class Solution { public: long long pickGifts(vector<int>& gifts, int k) { make_heap(gifts.begin(), gifts.end()); while (k--) { pop_heap(gifts.begin(), gifts.end()); gifts.back() = sqrt(gifts.back()); push_heap(gifts.begin(), gifts.end()); } return accumulate(gifts.begin(), gifts.end(), 0LL); } };
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
Go
func pickGifts(gifts []int, k int) (ans int64) { h := &hp{gifts} heap.Init(h) for ; k > 0; k-- { gifts[0] = int(math.Sqrt(float64(gifts[0]))) heap.Fix(h, 0) } for _, x := range gifts { ans += int64(x) } return } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } func (hp) Pop() (_ any) { return } func (hp) Push(any) {}
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
Java
class Solution { public long pickGifts(int[] gifts, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); for (int v : gifts) { pq.offer(v); } while (k-- > 0) { pq.offer((int) Math.sqrt(pq.poll())); } long ans = 0; for (int v : pq) { ans += v; } return ans; } }
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
Python
class Solution: def pickGifts(self, gifts: List[int], k: int) -> int: h = [-v for v in gifts] heapify(h) for _ in range(k): heapreplace(h, -int(sqrt(-h[0]))) return -sum(h)
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
Rust
impl Solution { pub fn pick_gifts(gifts: Vec<i32>, k: i32) -> i64 { let mut h = std::collections::BinaryHeap::from(gifts); let mut ans = 0; for _ in 0..k { if let Some(mut max_gift) = h.pop() { max_gift = (max_gift as f64).sqrt().floor() as i32; h.push(max_gift); } } for x in h { ans += x as i64; } ans } }
2,558
Take Gifts From the Richest Pile
Easy
<p>You are given an integer array <code>gifts</code> denoting the number of gifts in various piles. Every second, you do the following:</p> <ul> <li>Choose the pile with the maximum number of gifts.</li> <li>If there is more than one pile with the maximum number of gifts, choose any.</li> <li>Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.</li> </ul> <p>Return <em>the number of gifts remaining after </em><code>k</code><em> seconds.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> gifts = [25,64,9,4,100], k = 4 <strong>Output:</strong> 29 <strong>Explanation:</strong> The gifts are taken in the following way: - In the first second, the last pile is chosen and 10 gifts are left behind. - Then the second pile is chosen and 8 gifts are left behind. - After that the first pile is chosen and 5 gifts are left behind. - Finally, the last pile is chosen again and 3 gifts are left behind. The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> gifts = [1,1,1,1], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can&#39;t take any pile with you. So, the total gifts remaining are 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= gifts.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= gifts[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li> </ul>
Array; Simulation; Heap (Priority Queue)
TypeScript
function pickGifts(gifts: number[], k: number): number { const pq = new MaxPriorityQueue(); gifts.forEach(v => pq.enqueue(v)); while (k--) { let v = pq.dequeue().element; v = Math.floor(Math.sqrt(v)); pq.enqueue(v); } let ans = 0; while (!pq.isEmpty()) { ans += pq.dequeue().element; } return ans; }
2,559
Count Vowel Strings in Ranges
Medium
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a 2D array of integers <code>queries</code>.</p> <p>Each query <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> asks us to find the number of strings present at the indices ranging from <code>l<sub>i</sub></code> to <code>r<sub>i</sub></code> (both <strong>inclusive</strong>) of <code>words</code> that start and end with a vowel.</p> <p>Return <em>an array </em><code>ans</code><em> of size </em><code>queries.length</code><em>, where </em><code>ans[i]</code><em> is the answer to the </em><code>i</code><sup>th</sup><em> query</em>.</p> <p><strong>Note</strong> that the vowel letters are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;aba&quot;,&quot;bcb&quot;,&quot;ece&quot;,&quot;aa&quot;,&quot;e&quot;], queries = [[0,2],[1,4],[1,1]] <strong>Output:</strong> [2,3,0] <strong>Explanation:</strong> The strings starting and ending with a vowel are &quot;aba&quot;, &quot;ece&quot;, &quot;aa&quot; and &quot;e&quot;. The answer to the query [0,2] is 2 (strings &quot;aba&quot; and &quot;ece&quot;). to query [1,4] is 3 (strings &quot;ece&quot;, &quot;aa&quot;, &quot;e&quot;). to query [1,1] is 0. We return [2,3,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;], queries = [[0,2],[0,1],[2,2]] <strong>Output:</strong> [3,2,1] <strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 40</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li> </ul>
Array; String; Prefix Sum
C++
class Solution { public: vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) { unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u'}; vector<int> nums; for (int i = 0; i < words.size(); ++i) { char a = words[i][0], b = words[i].back(); if (vowels.count(a) && vowels.count(b)) { nums.push_back(i); } } vector<int> ans; for (auto& q : queries) { int l = q[0], r = q[1]; int cnt = upper_bound(nums.begin(), nums.end(), r) - lower_bound(nums.begin(), nums.end(), l); ans.push_back(cnt); } return ans; } };
2,559
Count Vowel Strings in Ranges
Medium
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a 2D array of integers <code>queries</code>.</p> <p>Each query <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> asks us to find the number of strings present at the indices ranging from <code>l<sub>i</sub></code> to <code>r<sub>i</sub></code> (both <strong>inclusive</strong>) of <code>words</code> that start and end with a vowel.</p> <p>Return <em>an array </em><code>ans</code><em> of size </em><code>queries.length</code><em>, where </em><code>ans[i]</code><em> is the answer to the </em><code>i</code><sup>th</sup><em> query</em>.</p> <p><strong>Note</strong> that the vowel letters are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;aba&quot;,&quot;bcb&quot;,&quot;ece&quot;,&quot;aa&quot;,&quot;e&quot;], queries = [[0,2],[1,4],[1,1]] <strong>Output:</strong> [2,3,0] <strong>Explanation:</strong> The strings starting and ending with a vowel are &quot;aba&quot;, &quot;ece&quot;, &quot;aa&quot; and &quot;e&quot;. The answer to the query [0,2] is 2 (strings &quot;aba&quot; and &quot;ece&quot;). to query [1,4] is 3 (strings &quot;ece&quot;, &quot;aa&quot;, &quot;e&quot;). to query [1,1] is 0. We return [2,3,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;], queries = [[0,2],[0,1],[2,2]] <strong>Output:</strong> [3,2,1] <strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 40</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li> </ul>
Array; String; Prefix Sum
Go
func vowelStrings(words []string, queries [][]int) []int { vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} nums := []int{} for i, w := range words { if vowels[w[0]] && vowels[w[len(w)-1]] { nums = append(nums, i) } } ans := make([]int, len(queries)) for i, q := range queries { l, r := q[0], q[1] ans[i] = sort.SearchInts(nums, r+1) - sort.SearchInts(nums, l) } return ans }
2,559
Count Vowel Strings in Ranges
Medium
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a 2D array of integers <code>queries</code>.</p> <p>Each query <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> asks us to find the number of strings present at the indices ranging from <code>l<sub>i</sub></code> to <code>r<sub>i</sub></code> (both <strong>inclusive</strong>) of <code>words</code> that start and end with a vowel.</p> <p>Return <em>an array </em><code>ans</code><em> of size </em><code>queries.length</code><em>, where </em><code>ans[i]</code><em> is the answer to the </em><code>i</code><sup>th</sup><em> query</em>.</p> <p><strong>Note</strong> that the vowel letters are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;aba&quot;,&quot;bcb&quot;,&quot;ece&quot;,&quot;aa&quot;,&quot;e&quot;], queries = [[0,2],[1,4],[1,1]] <strong>Output:</strong> [2,3,0] <strong>Explanation:</strong> The strings starting and ending with a vowel are &quot;aba&quot;, &quot;ece&quot;, &quot;aa&quot; and &quot;e&quot;. The answer to the query [0,2] is 2 (strings &quot;aba&quot; and &quot;ece&quot;). to query [1,4] is 3 (strings &quot;ece&quot;, &quot;aa&quot;, &quot;e&quot;). to query [1,1] is 0. We return [2,3,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;], queries = [[0,2],[0,1],[2,2]] <strong>Output:</strong> [3,2,1] <strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 40</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li> </ul>
Array; String; Prefix Sum
Java
class Solution { private List<Integer> nums = new ArrayList<>(); public int[] vowelStrings(String[] words, int[][] queries) { Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u'); for (int i = 0; i < words.length; ++i) { char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); if (vowels.contains(a) && vowels.contains(b)) { nums.add(i); } } int m = queries.length; int[] ans = new int[m]; for (int i = 0; i < m; ++i) { int l = queries[i][0], r = queries[i][1]; ans[i] = search(r + 1) - search(l); } return ans; } private int search(int x) { int l = 0, r = nums.size(); while (l < r) { int mid = (l + r) >> 1; if (nums.get(mid) >= x) { r = mid; } else { l = mid + 1; } } return l; } }
2,559
Count Vowel Strings in Ranges
Medium
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a 2D array of integers <code>queries</code>.</p> <p>Each query <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> asks us to find the number of strings present at the indices ranging from <code>l<sub>i</sub></code> to <code>r<sub>i</sub></code> (both <strong>inclusive</strong>) of <code>words</code> that start and end with a vowel.</p> <p>Return <em>an array </em><code>ans</code><em> of size </em><code>queries.length</code><em>, where </em><code>ans[i]</code><em> is the answer to the </em><code>i</code><sup>th</sup><em> query</em>.</p> <p><strong>Note</strong> that the vowel letters are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;aba&quot;,&quot;bcb&quot;,&quot;ece&quot;,&quot;aa&quot;,&quot;e&quot;], queries = [[0,2],[1,4],[1,1]] <strong>Output:</strong> [2,3,0] <strong>Explanation:</strong> The strings starting and ending with a vowel are &quot;aba&quot;, &quot;ece&quot;, &quot;aa&quot; and &quot;e&quot;. The answer to the query [0,2] is 2 (strings &quot;aba&quot; and &quot;ece&quot;). to query [1,4] is 3 (strings &quot;ece&quot;, &quot;aa&quot;, &quot;e&quot;). to query [1,1] is 0. We return [2,3,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;], queries = [[0,2],[0,1],[2,2]] <strong>Output:</strong> [3,2,1] <strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 40</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li> </ul>
Array; String; Prefix Sum
Python
class Solution: def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: vowels = set("aeiou") nums = [i for i, w in enumerate(words) if w[0] in vowels and w[-1] in vowels] return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries]
2,559
Count Vowel Strings in Ranges
Medium
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a 2D array of integers <code>queries</code>.</p> <p>Each query <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> asks us to find the number of strings present at the indices ranging from <code>l<sub>i</sub></code> to <code>r<sub>i</sub></code> (both <strong>inclusive</strong>) of <code>words</code> that start and end with a vowel.</p> <p>Return <em>an array </em><code>ans</code><em> of size </em><code>queries.length</code><em>, where </em><code>ans[i]</code><em> is the answer to the </em><code>i</code><sup>th</sup><em> query</em>.</p> <p><strong>Note</strong> that the vowel letters are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;aba&quot;,&quot;bcb&quot;,&quot;ece&quot;,&quot;aa&quot;,&quot;e&quot;], queries = [[0,2],[1,4],[1,1]] <strong>Output:</strong> [2,3,0] <strong>Explanation:</strong> The strings starting and ending with a vowel are &quot;aba&quot;, &quot;ece&quot;, &quot;aa&quot; and &quot;e&quot;. The answer to the query [0,2] is 2 (strings &quot;aba&quot; and &quot;ece&quot;). to query [1,4] is 3 (strings &quot;ece&quot;, &quot;aa&quot;, &quot;e&quot;). to query [1,1] is 0. We return [2,3,0]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;], queries = [[0,2],[0,1],[2,2]] <strong>Output:</strong> [3,2,1] <strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 40</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li> </ul>
Array; String; Prefix Sum
TypeScript
function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); const nums: number[] = []; for (let i = 0; i < words.length; ++i) { if (vowels.has(words[i][0]) && vowels.has(words[i][words[i].length - 1])) { nums.push(i); } } const search = (x: number): number => { let l = 0, r = nums.length; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; return queries.map(([l, r]) => search(r + 1) - search(l)); }
2,560
House Robber IV
Medium
<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he <strong>refuses to steal from adjacent homes</strong>.</p> <p>The <strong>capability</strong> of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p> <p>You are given an integer array <code>nums</code> representing how much money is stashed in each house. More formally, the <code>i<sup>th</sup></code> house from the left has <code>nums[i]</code> dollars.</p> <p>You are also given an integer <code>k</code>, representing the <strong>minimum</strong> number of houses the robber will steal from. It is always possible to steal at least <code>k</code> houses.</p> <p>Return <em>the <strong>minimum</strong> capability of the robber out of all the possible ways to steal at least </em><code>k</code><em> houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,9], k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= (nums.length + 1)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming
C++
class Solution { public: int minCapability(vector<int>& nums, int k) { auto f = [&](int x) { int cnt = 0, j = -2; for (int i = 0; i < nums.size(); ++i) { if (nums[i] > x || i == j + 1) { continue; } ++cnt; j = i; } return cnt >= k; }; int left = 0, right = *max_element(nums.begin(), nums.end()); while (left < right) { int mid = (left + right) >> 1; if (f(mid)) { right = mid; } else { left = mid + 1; } } return left; } };
2,560
House Robber IV
Medium
<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he <strong>refuses to steal from adjacent homes</strong>.</p> <p>The <strong>capability</strong> of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p> <p>You are given an integer array <code>nums</code> representing how much money is stashed in each house. More formally, the <code>i<sup>th</sup></code> house from the left has <code>nums[i]</code> dollars.</p> <p>You are also given an integer <code>k</code>, representing the <strong>minimum</strong> number of houses the robber will steal from. It is always possible to steal at least <code>k</code> houses.</p> <p>Return <em>the <strong>minimum</strong> capability of the robber out of all the possible ways to steal at least </em><code>k</code><em> houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,9], k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= (nums.length + 1)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming
Go
func minCapability(nums []int, k int) int { return sort.Search(1e9+1, func(x int) bool { cnt, j := 0, -2 for i, v := range nums { if v > x || i == j+1 { continue } cnt++ j = i } return cnt >= k }) }
2,560
House Robber IV
Medium
<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he <strong>refuses to steal from adjacent homes</strong>.</p> <p>The <strong>capability</strong> of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p> <p>You are given an integer array <code>nums</code> representing how much money is stashed in each house. More formally, the <code>i<sup>th</sup></code> house from the left has <code>nums[i]</code> dollars.</p> <p>You are also given an integer <code>k</code>, representing the <strong>minimum</strong> number of houses the robber will steal from. It is always possible to steal at least <code>k</code> houses.</p> <p>Return <em>the <strong>minimum</strong> capability of the robber out of all the possible ways to steal at least </em><code>k</code><em> houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,9], k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= (nums.length + 1)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming
Java
class Solution { public int minCapability(int[] nums, int k) { int left = 0, right = (int) 1e9; while (left < right) { int mid = (left + right) >> 1; if (f(nums, mid) >= k) { right = mid; } else { left = mid + 1; } } return left; } private int f(int[] nums, int x) { int cnt = 0, j = -2; for (int i = 0; i < nums.length; ++i) { if (nums[i] > x || i == j + 1) { continue; } ++cnt; j = i; } return cnt; } }
2,560
House Robber IV
Medium
<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he <strong>refuses to steal from adjacent homes</strong>.</p> <p>The <strong>capability</strong> of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p> <p>You are given an integer array <code>nums</code> representing how much money is stashed in each house. More formally, the <code>i<sup>th</sup></code> house from the left has <code>nums[i]</code> dollars.</p> <p>You are also given an integer <code>k</code>, representing the <strong>minimum</strong> number of houses the robber will steal from. It is always possible to steal at least <code>k</code> houses.</p> <p>Return <em>the <strong>minimum</strong> capability of the robber out of all the possible ways to steal at least </em><code>k</code><em> houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,9], k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= (nums.length + 1)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming
Python
class Solution: def minCapability(self, nums: List[int], k: int) -> int: def f(x): cnt, j = 0, -2 for i, v in enumerate(nums): if v > x or i == j + 1: continue cnt += 1 j = i return cnt >= k return bisect_left(range(max(nums) + 1), True, key=f)
2,560
House Robber IV
Medium
<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he <strong>refuses to steal from adjacent homes</strong>.</p> <p>The <strong>capability</strong> of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p> <p>You are given an integer array <code>nums</code> representing how much money is stashed in each house. More formally, the <code>i<sup>th</sup></code> house from the left has <code>nums[i]</code> dollars.</p> <p>You are also given an integer <code>k</code>, representing the <strong>minimum</strong> number of houses the robber will steal from. It is always possible to steal at least <code>k</code> houses.</p> <p>Return <em>the <strong>minimum</strong> capability of the robber out of all the possible ways to steal at least </em><code>k</code><em> houses</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,5,9], k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> There are three ways to rob at least 2 houses: - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. Therefore, we return min(5, 9, 9) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,7,9,3,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= (nums.length + 1)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming
TypeScript
function minCapability(nums: number[], k: number): number { const f = (mx: number): boolean => { let cnt = 0; let j = -2; for (let i = 0; i < nums.length; ++i) { if (nums[i] <= mx && i - j > 1) { ++cnt; j = i; } } return cnt >= k; }; let left = 1; let right = Math.max(...nums); while (left < right) { const mid = (left + right) >> 1; if (f(mid)) { right = mid; } else { left = mid + 1; } } return left; }
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
C++
class Solution { public: long long minCost(vector<int>& basket1, vector<int>& basket2) { int n = basket1.size(); unordered_map<int, int> cnt; for (int i = 0; i < n; ++i) { cnt[basket1[i]]++; cnt[basket2[i]]--; } int mi = 1 << 30; vector<int> nums; for (auto& [x, v] : cnt) { if (v % 2) { return -1; } for (int i = abs(v) / 2; i; --i) { nums.push_back(x); } mi = min(mi, x); } ranges::sort(nums); int m = nums.size(); long long ans = 0; for (int i = 0; i < m / 2; ++i) { ans += min(nums[i], mi * 2); } return ans; } };
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
Go
func minCost(basket1 []int, basket2 []int) (ans int64) { cnt := map[int]int{} for i, a := range basket1 { cnt[a]++ cnt[basket2[i]]-- } mi := 1 << 30 nums := []int{} for x, v := range cnt { if v%2 != 0 { return -1 } for i := abs(v) / 2; i > 0; i-- { nums = append(nums, x) } mi = min(mi, x) } sort.Ints(nums) m := len(nums) for i := 0; i < m/2; i++ { ans += int64(min(nums[i], mi*2)) } return } func abs(x int) int { if x < 0 { return -x } return x }
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
Java
class Solution { public long minCost(int[] basket1, int[] basket2) { int n = basket1.length; Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < n; ++i) { cnt.merge(basket1[i], 1, Integer::sum); cnt.merge(basket2[i], -1, Integer::sum); } int mi = 1 << 30; List<Integer> nums = new ArrayList<>(); for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); if (v % 2 != 0) { return -1; } for (int i = Math.abs(v) / 2; i > 0; --i) { nums.add(x); } mi = Math.min(mi, x); } Collections.sort(nums); int m = nums.size(); long ans = 0; for (int i = 0; i < m / 2; ++i) { ans += Math.min(nums.get(i), mi * 2); } return ans; } }
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
Python
class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: cnt = Counter() for a, b in zip(basket1, basket2): cnt[a] += 1 cnt[b] -= 1 mi = min(cnt) nums = [] for x, v in cnt.items(): if v % 2: return -1 nums.extend([x] * (abs(v) // 2)) nums.sort() m = len(nums) // 2 return sum(min(x, mi * 2) for x in nums[:m])
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
Rust
use std::collections::HashMap; impl Solution { pub fn min_cost(basket1: Vec<i32>, basket2: Vec<i32>) -> i64 { let n = basket1.len(); let mut cnt: HashMap<i32, i32> = HashMap::new(); for i in 0..n { *cnt.entry(basket1[i]).or_insert(0) += 1; *cnt.entry(basket2[i]).or_insert(0) -= 1; } let mut mi = i32::MAX; let mut nums = Vec::new(); for (x, v) in cnt { if v % 2 != 0 { return -1; } for _ in 0..(v.abs() / 2) { nums.push(x); } mi = mi.min(x); } nums.sort(); let m = nums.len(); let mut ans = 0; for i in 0..(m / 2) { ans += nums[i].min(mi * 2) as i64; } ans } }
2,561
Rearranging Fruits
Hard
<p>You have two fruit baskets containing <code>n</code> fruits each. You are given two <strong>0-indexed</strong> integer arrays <code>basket1</code> and <code>basket2</code> representing the cost of fruit in each basket. You want to make both baskets <strong>equal</strong>. To do so, you can use the following operation as many times as you want:</p> <ul> <li>Choose two indices <code>i</code> and <code>j</code>, and swap the <code>i<sup><font size="1">th</font></sup></code> fruit of <code>basket1</code> with the <code>j<sup><font size="1">th</font></sup></code> fruit of <code>basket2</code>.</li> <li>The cost of the swap is <code>min(basket1[i], basket2[j])</code>.</li> </ul> <p>Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.</p> <p>Return <em>the minimum cost to make both the baskets equal or </em><code>-1</code><em> if impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> basket1 = [4,2,2,2], basket2 = [1,4,1,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> basket1 = [2,3,4,1], basket2 = [3,2,5,1] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make both the baskets equal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>basket1.length == basket2.length</code></li> <li><code>1 &lt;= basket1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= basket1[i], basket2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Sort; Array; Hash Table
TypeScript
function minCost(basket1: number[], basket2: number[]): number { const n = basket1.length; const cnt: Map<number, number> = new Map(); for (let i = 0; i < n; i++) { cnt.set(basket1[i], (cnt.get(basket1[i]) || 0) + 1); cnt.set(basket2[i], (cnt.get(basket2[i]) || 0) - 1); } let mi = Number.MAX_SAFE_INTEGER; const nums: number[] = []; for (const [x, v] of cnt.entries()) { if (v % 2 !== 0) { return -1; } for (let i = 0; i < Math.abs(v) / 2; i++) { nums.push(x); } mi = Math.min(mi, x); } nums.sort((a, b) => a - b); const m = nums.length; let ans = 0; for (let i = 0; i < m / 2; i++) { ans += Math.min(nums[i], mi * 2); } return ans; }
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
C
int getLen(int num) { int res = 0; while (num) { num /= 10; res++; } return res; } long long findTheArrayConcVal(int* nums, int numsSize) { long long ans = 0; int i = 0; int j = numsSize - 1; while (i < j) { ans += nums[i] * pow(10, getLen(nums[j])) + nums[j]; i++; j--; } if (i == j) { ans += nums[i]; } return ans; }
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
C++
class Solution { public: long long findTheArrayConcVal(vector<int>& nums) { long long ans = 0; int i = 0, j = nums.size() - 1; for (; i < j; ++i, --j) { ans += stoi(to_string(nums[i]) + to_string(nums[j])); } if (i == j) { ans += nums[i]; } return ans; } };
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
Go
func findTheArrayConcVal(nums []int) (ans int64) { i, j := 0, len(nums)-1 for ; i < j; i, j = i+1, j-1 { x, _ := strconv.Atoi(strconv.Itoa(nums[i]) + strconv.Itoa(nums[j])) ans += int64(x) } if i == j { ans += int64(nums[i]) } return }
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
Java
class Solution { public long findTheArrayConcVal(int[] nums) { long ans = 0; int i = 0, j = nums.length - 1; for (; i < j; ++i, --j) { ans += Integer.parseInt(nums[i] + "" + nums[j]); } if (i == j) { ans += nums[i]; } return ans; } }
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
Python
class Solution: def findTheArrayConcVal(self, nums: List[int]) -> int: ans = 0 i, j = 0, len(nums) - 1 while i < j: ans += int(str(nums[i]) + str(nums[j])) i, j = i + 1, j - 1 if i == j: ans += nums[i] return ans
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
Rust
impl Solution { pub fn find_the_array_conc_val(nums: Vec<i32>) -> i64 { let n = nums.len(); let mut ans = 0; let mut i = 0; let mut j = n - 1; while i < j { ans += format!("{}{}", nums[i], nums[j]).parse::<i64>().unwrap(); i += 1; j -= 1; } if i == j { ans += nums[i] as i64; } ans } }
2,562
Find the Array Concatenation Value
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>The <strong>concatenation</strong> of two numbers is the number formed by concatenating their numerals.</p> <ul> <li>For example, the concatenation of <code>15</code>, <code>49</code> is <code>1549</code>.</li> </ul> <p>The <strong>concatenation value</strong> of <code>nums</code> is initially equal to <code>0</code>. Perform this operation until <code>nums</code> becomes empty:</p> <ul> <li>If <code>nums</code> has a size greater than one, add the value of the concatenation of the first and the last element to the <strong>concatenation value</strong> of <code>nums</code>, and remove those two elements from <code>nums</code>. For example, if the <code>nums</code> was <code>[1, 2, 4, 5, 6]</code>, add 16 to the <code>concatenation value</code>.</li> <li>If only one element exists in <code>nums</code>, add its value to the <strong>concatenation value</strong> of <code>nums</code>, then remove it.</li> </ul> <p>Return<em> the concatenation value of <code>nums</code></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,52,2,4] <strong>Output:</strong> 596 <strong>Explanation:</strong> Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,13,8,12] <strong>Output:</strong> 673 <strong>Explanation:</strong> Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Array; Two Pointers; Simulation
TypeScript
function findTheArrayConcVal(nums: number[]): number { const n = nums.length; let ans = 0; let i = 0; let j = n - 1; while (i < j) { ans += Number(`${nums[i]}${nums[j]}`); i++; j--; } if (i === j) { ans += nums[i]; } return ans; }
2,563
Count the Number of Fair Pairs
Medium
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p> <p>A pair <code>(i, j)</code> is <b>fair </b>if:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; n</code>, and</li> <li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11 <strong>Output:</strong> 1 <strong>Explanation:</strong> There is a single fair pair: (2,3). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n</code></li> <li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
C++
class Solution { public: long long countFairPairs(vector<int>& nums, int lower, int upper) { long long ans = 0; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); ++i) { auto j = lower_bound(nums.begin() + i + 1, nums.end(), lower - nums[i]); auto k = lower_bound(nums.begin() + i + 1, nums.end(), upper - nums[i] + 1); ans += k - j; } return ans; } };