id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,634
Minimum Removals to Balance Array
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An array is considered <strong>balanced</strong> if the value of its <strong>maximum</strong> element is <strong>at most</strong> <code>k</code> times the <strong>minimum</strong> element.</p> <p>You may remove <strong>any</strong> number of elements from <code>nums</code>​​​​​​​ without making it <strong>empty</strong>.</p> <p>Return the <strong>minimum</strong> number of elements to remove so that the remaining array is balanced.</p> <p><strong>Note:</strong> An array of size 1 is considered balanced as its maximum and minimum are equal, and the condition always holds true.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>nums[2] = 5</code> to get <code>nums = [2, 1]</code>.</li> <li>Now <code>max = 2</code>, <code>min = 1</code> and <code>max &lt;= min * k</code> as <code>2 &lt;= 1 * 2</code>. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,6,2,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>nums[0] = 1</code> and <code>nums[3] = 9</code> to get <code>nums = [6, 2]</code>.</li> <li>Now <code>max = 6</code>, <code>min = 2</code> and <code>max &lt;= min * k</code> as <code>6 &lt;= 2 * 3</code>. Thus, the answer is 2.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,6], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since <code>nums</code> is already balanced as <code>6 &lt;= 4 * 2</code>, no elements need to be removed.</li> </ul> </div> <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;= 10<sup>5</sup></code></li> </ul>
Python
class Solution: def minRemoval(self, nums: List[int], k: int) -> int: nums.sort() cnt = 0 for i, x in enumerate(nums): j = bisect_right(nums, k * x) cnt = max(cnt, j - i) return len(nums) - cnt
3,634
Minimum Removals to Balance Array
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>An array is considered <strong>balanced</strong> if the value of its <strong>maximum</strong> element is <strong>at most</strong> <code>k</code> times the <strong>minimum</strong> element.</p> <p>You may remove <strong>any</strong> number of elements from <code>nums</code>​​​​​​​ without making it <strong>empty</strong>.</p> <p>Return the <strong>minimum</strong> number of elements to remove so that the remaining array is balanced.</p> <p><strong>Note:</strong> An array of size 1 is considered balanced as its maximum and minimum are equal, and the condition always holds true.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,5], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>nums[2] = 5</code> to get <code>nums = [2, 1]</code>.</li> <li>Now <code>max = 2</code>, <code>min = 1</code> and <code>max &lt;= min * k</code> as <code>2 &lt;= 1 * 2</code>. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,6,2,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>nums[0] = 1</code> and <code>nums[3] = 9</code> to get <code>nums = [6, 2]</code>.</li> <li>Now <code>max = 6</code>, <code>min = 2</code> and <code>max &lt;= min * k</code> as <code>6 &lt;= 2 * 3</code>. Thus, the answer is 2.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,6], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since <code>nums</code> is already balanced as <code>6 &lt;= 4 * 2</code>, no elements need to be removed.</li> </ul> </div> <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;= 10<sup>5</sup></code></li> </ul>
TypeScript
function minRemoval(nums: number[], k: number): number { nums.sort((a, b) => a - b); const n = nums.length; let cnt = 0; for (let i = 0; i < n; ++i) { let j = n; if (nums[i] * k <= nums[n - 1]) { const target = nums[i] * k + 1; j = _.sortedIndexBy(nums, target, x => x); } cnt = Math.max(cnt, j - i); } return n - cnt; }
3,635
Earliest Finish Time for Land and Water Rides II
Medium
<p data-end="143" data-start="53">You are given two categories of theme park attractions: <strong data-end="122" data-start="108">land rides</strong> and <strong data-end="142" data-start="127">water rides</strong>.</p> <ul> <li data-end="163" data-start="147"><strong data-end="161" data-start="147">Land rides</strong> <ul> <li data-end="245" data-start="168"><code data-end="186" data-start="168">landStartTime[i]</code> &ndash; the earliest time the <code>i<sup>th</sup></code> land ride can be boarded.</li> <li data-end="306" data-start="250"><code data-end="267" data-start="250">landDuration[i]</code> &ndash; how long the <code>i<sup>th</sup></code> land ride lasts.</li> </ul> </li> <li><strong data-end="325" data-start="310">Water rides</strong> <ul> <li><code data-end="351" data-start="332">waterStartTime[j]</code> &ndash; the earliest time the <code>j<sup>th</sup></code> water ride can be boarded.</li> <li><code data-end="434" data-start="416">waterDuration[j]</code> &ndash; how long the <code>j<sup>th</sup></code> water ride lasts.</li> </ul> </li> </ul> <p data-end="569" data-start="476">A tourist must experience <strong data-end="517" data-start="502">exactly one</strong> ride from <strong data-end="536" data-start="528">each</strong> category, in <strong data-end="566" data-start="550">either order</strong>.</p> <ul> <li data-end="641" data-start="573">A ride may be started at its opening time or <strong data-end="638" data-start="618">any later moment</strong>.</li> <li data-end="715" data-start="644">If a ride is started at time <code data-end="676" data-start="673">t</code>, it finishes at time <code data-end="712" data-start="698">t + duration</code>.</li> <li data-end="834" data-start="718">Immediately after finishing one ride the tourist may board the other (if it is already open) or wait until it opens.</li> </ul> <p data-end="917" data-start="836">Return the <strong data-end="873" data-start="847">earliest possible time</strong> at which the tourist can finish both rides.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul> <li data-end="181" data-start="145">Plan A (land ride 0 &rarr; water ride 0): <ul> <li data-end="272" data-start="186">Start land ride 0 at time <code data-end="234" data-start="212">landStartTime[0] = 2</code>. Finish at <code data-end="271" data-start="246">2 + landDuration[0] = 6</code>.</li> <li data-end="392" data-start="277">Water ride 0 opens at time <code data-end="327" data-start="304">waterStartTime[0] = 6</code>. Start immediately at <code data-end="353" data-start="350">6</code>, finish at <code data-end="391" data-start="365">6 + waterDuration[0] = 9</code>.</li> </ul> </li> <li data-end="432" data-start="396">Plan B (water ride 0 &rarr; land ride 1): <ul> <li data-end="526" data-start="437">Start water ride 0 at time <code data-end="487" data-start="464">waterStartTime[0] = 6</code>. Finish at <code data-end="525" data-start="499">6 + waterDuration[0] = 9</code>.</li> <li data-end="632" data-start="531">Land ride 1 opens at <code data-end="574" data-start="552">landStartTime[1] = 8</code>. Start at time <code data-end="593" data-start="590">9</code>, finish at <code data-end="631" data-start="605">9 + landDuration[1] = 10</code>.</li> </ul> </li> <li data-end="672" data-start="636">Plan C (land ride 1 &rarr; water ride 0): <ul> <li data-end="763" data-start="677">Start land ride 1 at time <code data-end="725" data-start="703">landStartTime[1] = 8</code>. Finish at <code data-end="762" data-start="737">8 + landDuration[1] = 9</code>.</li> <li data-end="873" data-start="768">Water ride 0 opened at <code data-end="814" data-start="791">waterStartTime[0] = 6</code>. Start at time <code data-end="833" data-start="830">9</code>, finish at <code data-end="872" data-start="845">9 + waterDuration[0] = 12</code>.</li> </ul> </li> <li data-end="913" data-start="877">Plan D (water ride 0 &rarr; land ride 0): <ul> <li data-end="1007" data-start="918">Start water ride 0 at time <code data-end="968" data-start="945">waterStartTime[0] = 6</code>. Finish at <code data-end="1006" data-start="980">6 + waterDuration[0] = 9</code>.</li> <li data-end="1114" data-start="1012">Land ride 0 opened at <code data-end="1056" data-start="1034">landStartTime[0] = 2</code>. Start at time <code data-end="1075" data-start="1072">9</code>, finish at <code data-end="1113" data-start="1087">9 + landDuration[0] = 13</code>.</li> </ul> </li> </ul> <p data-end="1161" data-is-last-node="" data-is-only-node="" data-start="1116">Plan A gives the earliest finish time of 9.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul data-end="1589" data-start="1086"> <li data-end="1124" data-start="1088">Plan A (water ride 0 &rarr; land ride 0): <ul> <li data-end="1219" data-start="1129">Start water ride 0 at time <code data-end="1179" data-start="1156">waterStartTime[0] = 1</code>. Finish at <code data-end="1218" data-start="1191">1 + waterDuration[0] = 11</code>.</li> <li data-end="1338" data-start="1224">Land ride 0 opened at <code data-end="1268" data-start="1246">landStartTime[0] = 5</code>. Start immediately at <code data-end="1295" data-start="1291">11</code> and finish at <code data-end="1337" data-start="1310">11 + landDuration[0] = 14</code>.</li> </ul> </li> <li data-end="1378" data-start="1342">Plan B (land ride 0 &rarr; water ride 0): <ul> <li data-end="1469" data-start="1383">Start land ride 0 at time <code data-end="1431" data-start="1409">landStartTime[0] = 5</code>. Finish at <code data-end="1468" data-start="1443">5 + landDuration[0] = 8</code>.</li> <li data-end="1589" data-start="1474">Water ride 0 opened at <code data-end="1520" data-start="1497">waterStartTime[0] = 1</code>. Start immediately at <code data-end="1546" data-start="1543">8</code> and finish at <code data-end="1588" data-start="1561">8 + waterDuration[0] = 18</code>.</li> </ul> </li> </ul> <p data-end="1640" data-is-last-node="" data-is-only-node="" data-start="1591">Plan A provides the earliest finish time of 14.<strong>​​​​​​​</strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="38" data-start="16"><code data-end="36" data-start="16">1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li> <li data-end="93" data-start="41"><code data-end="91" data-start="41">landStartTime.length == landDuration.length == n</code></li> <li data-end="150" data-start="96"><code data-end="148" data-start="96">waterStartTime.length == waterDuration.length == m</code></li> <li data-end="237" data-start="153"><code data-end="235" data-start="153">1 &lt;= landStartTime[i], landDuration[i], waterStartTime[j], waterDuration[j] &lt;= 10<sup>5</sup></code></li> </ul>
C++
class Solution { public: int earliestFinishTime(vector<int>& landStartTime, vector<int>& landDuration, vector<int>& waterStartTime, vector<int>& waterDuration) { int x = calc(landStartTime, landDuration, waterStartTime, waterDuration); int y = calc(waterStartTime, waterDuration, landStartTime, landDuration); return min(x, y); } int calc(vector<int>& a1, vector<int>& t1, vector<int>& a2, vector<int>& t2) { int minEnd = INT_MAX; for (int i = 0; i < a1.size(); ++i) { minEnd = min(minEnd, a1[i] + t1[i]); } int ans = INT_MAX; for (int i = 0; i < a2.size(); ++i) { ans = min(ans, max(minEnd, a2[i]) + t2[i]); } return ans; } };
3,635
Earliest Finish Time for Land and Water Rides II
Medium
<p data-end="143" data-start="53">You are given two categories of theme park attractions: <strong data-end="122" data-start="108">land rides</strong> and <strong data-end="142" data-start="127">water rides</strong>.</p> <ul> <li data-end="163" data-start="147"><strong data-end="161" data-start="147">Land rides</strong> <ul> <li data-end="245" data-start="168"><code data-end="186" data-start="168">landStartTime[i]</code> &ndash; the earliest time the <code>i<sup>th</sup></code> land ride can be boarded.</li> <li data-end="306" data-start="250"><code data-end="267" data-start="250">landDuration[i]</code> &ndash; how long the <code>i<sup>th</sup></code> land ride lasts.</li> </ul> </li> <li><strong data-end="325" data-start="310">Water rides</strong> <ul> <li><code data-end="351" data-start="332">waterStartTime[j]</code> &ndash; the earliest time the <code>j<sup>th</sup></code> water ride can be boarded.</li> <li><code data-end="434" data-start="416">waterDuration[j]</code> &ndash; how long the <code>j<sup>th</sup></code> water ride lasts.</li> </ul> </li> </ul> <p data-end="569" data-start="476">A tourist must experience <strong data-end="517" data-start="502">exactly one</strong> ride from <strong data-end="536" data-start="528">each</strong> category, in <strong data-end="566" data-start="550">either order</strong>.</p> <ul> <li data-end="641" data-start="573">A ride may be started at its opening time or <strong data-end="638" data-start="618">any later moment</strong>.</li> <li data-end="715" data-start="644">If a ride is started at time <code data-end="676" data-start="673">t</code>, it finishes at time <code data-end="712" data-start="698">t + duration</code>.</li> <li data-end="834" data-start="718">Immediately after finishing one ride the tourist may board the other (if it is already open) or wait until it opens.</li> </ul> <p data-end="917" data-start="836">Return the <strong data-end="873" data-start="847">earliest possible time</strong> at which the tourist can finish both rides.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul> <li data-end="181" data-start="145">Plan A (land ride 0 &rarr; water ride 0): <ul> <li data-end="272" data-start="186">Start land ride 0 at time <code data-end="234" data-start="212">landStartTime[0] = 2</code>. Finish at <code data-end="271" data-start="246">2 + landDuration[0] = 6</code>.</li> <li data-end="392" data-start="277">Water ride 0 opens at time <code data-end="327" data-start="304">waterStartTime[0] = 6</code>. Start immediately at <code data-end="353" data-start="350">6</code>, finish at <code data-end="391" data-start="365">6 + waterDuration[0] = 9</code>.</li> </ul> </li> <li data-end="432" data-start="396">Plan B (water ride 0 &rarr; land ride 1): <ul> <li data-end="526" data-start="437">Start water ride 0 at time <code data-end="487" data-start="464">waterStartTime[0] = 6</code>. Finish at <code data-end="525" data-start="499">6 + waterDuration[0] = 9</code>.</li> <li data-end="632" data-start="531">Land ride 1 opens at <code data-end="574" data-start="552">landStartTime[1] = 8</code>. Start at time <code data-end="593" data-start="590">9</code>, finish at <code data-end="631" data-start="605">9 + landDuration[1] = 10</code>.</li> </ul> </li> <li data-end="672" data-start="636">Plan C (land ride 1 &rarr; water ride 0): <ul> <li data-end="763" data-start="677">Start land ride 1 at time <code data-end="725" data-start="703">landStartTime[1] = 8</code>. Finish at <code data-end="762" data-start="737">8 + landDuration[1] = 9</code>.</li> <li data-end="873" data-start="768">Water ride 0 opened at <code data-end="814" data-start="791">waterStartTime[0] = 6</code>. Start at time <code data-end="833" data-start="830">9</code>, finish at <code data-end="872" data-start="845">9 + waterDuration[0] = 12</code>.</li> </ul> </li> <li data-end="913" data-start="877">Plan D (water ride 0 &rarr; land ride 0): <ul> <li data-end="1007" data-start="918">Start water ride 0 at time <code data-end="968" data-start="945">waterStartTime[0] = 6</code>. Finish at <code data-end="1006" data-start="980">6 + waterDuration[0] = 9</code>.</li> <li data-end="1114" data-start="1012">Land ride 0 opened at <code data-end="1056" data-start="1034">landStartTime[0] = 2</code>. Start at time <code data-end="1075" data-start="1072">9</code>, finish at <code data-end="1113" data-start="1087">9 + landDuration[0] = 13</code>.</li> </ul> </li> </ul> <p data-end="1161" data-is-last-node="" data-is-only-node="" data-start="1116">Plan A gives the earliest finish time of 9.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul data-end="1589" data-start="1086"> <li data-end="1124" data-start="1088">Plan A (water ride 0 &rarr; land ride 0): <ul> <li data-end="1219" data-start="1129">Start water ride 0 at time <code data-end="1179" data-start="1156">waterStartTime[0] = 1</code>. Finish at <code data-end="1218" data-start="1191">1 + waterDuration[0] = 11</code>.</li> <li data-end="1338" data-start="1224">Land ride 0 opened at <code data-end="1268" data-start="1246">landStartTime[0] = 5</code>. Start immediately at <code data-end="1295" data-start="1291">11</code> and finish at <code data-end="1337" data-start="1310">11 + landDuration[0] = 14</code>.</li> </ul> </li> <li data-end="1378" data-start="1342">Plan B (land ride 0 &rarr; water ride 0): <ul> <li data-end="1469" data-start="1383">Start land ride 0 at time <code data-end="1431" data-start="1409">landStartTime[0] = 5</code>. Finish at <code data-end="1468" data-start="1443">5 + landDuration[0] = 8</code>.</li> <li data-end="1589" data-start="1474">Water ride 0 opened at <code data-end="1520" data-start="1497">waterStartTime[0] = 1</code>. Start immediately at <code data-end="1546" data-start="1543">8</code> and finish at <code data-end="1588" data-start="1561">8 + waterDuration[0] = 18</code>.</li> </ul> </li> </ul> <p data-end="1640" data-is-last-node="" data-is-only-node="" data-start="1591">Plan A provides the earliest finish time of 14.<strong>​​​​​​​</strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="38" data-start="16"><code data-end="36" data-start="16">1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li> <li data-end="93" data-start="41"><code data-end="91" data-start="41">landStartTime.length == landDuration.length == n</code></li> <li data-end="150" data-start="96"><code data-end="148" data-start="96">waterStartTime.length == waterDuration.length == m</code></li> <li data-end="237" data-start="153"><code data-end="235" data-start="153">1 &lt;= landStartTime[i], landDuration[i], waterStartTime[j], waterDuration[j] &lt;= 10<sup>5</sup></code></li> </ul>
Go
func earliestFinishTime(landStartTime []int, landDuration []int, waterStartTime []int, waterDuration []int) int { x := calc(landStartTime, landDuration, waterStartTime, waterDuration) y := calc(waterStartTime, waterDuration, landStartTime, landDuration) return min(x, y) } func calc(a1 []int, t1 []int, a2 []int, t2 []int) int { minEnd := math.MaxInt32 for i := 0; i < len(a1); i++ { minEnd = min(minEnd, a1[i]+t1[i]) } ans := math.MaxInt32 for i := 0; i < len(a2); i++ { ans = min(ans, max(minEnd, a2[i])+t2[i]) } return ans }
3,635
Earliest Finish Time for Land and Water Rides II
Medium
<p data-end="143" data-start="53">You are given two categories of theme park attractions: <strong data-end="122" data-start="108">land rides</strong> and <strong data-end="142" data-start="127">water rides</strong>.</p> <ul> <li data-end="163" data-start="147"><strong data-end="161" data-start="147">Land rides</strong> <ul> <li data-end="245" data-start="168"><code data-end="186" data-start="168">landStartTime[i]</code> &ndash; the earliest time the <code>i<sup>th</sup></code> land ride can be boarded.</li> <li data-end="306" data-start="250"><code data-end="267" data-start="250">landDuration[i]</code> &ndash; how long the <code>i<sup>th</sup></code> land ride lasts.</li> </ul> </li> <li><strong data-end="325" data-start="310">Water rides</strong> <ul> <li><code data-end="351" data-start="332">waterStartTime[j]</code> &ndash; the earliest time the <code>j<sup>th</sup></code> water ride can be boarded.</li> <li><code data-end="434" data-start="416">waterDuration[j]</code> &ndash; how long the <code>j<sup>th</sup></code> water ride lasts.</li> </ul> </li> </ul> <p data-end="569" data-start="476">A tourist must experience <strong data-end="517" data-start="502">exactly one</strong> ride from <strong data-end="536" data-start="528">each</strong> category, in <strong data-end="566" data-start="550">either order</strong>.</p> <ul> <li data-end="641" data-start="573">A ride may be started at its opening time or <strong data-end="638" data-start="618">any later moment</strong>.</li> <li data-end="715" data-start="644">If a ride is started at time <code data-end="676" data-start="673">t</code>, it finishes at time <code data-end="712" data-start="698">t + duration</code>.</li> <li data-end="834" data-start="718">Immediately after finishing one ride the tourist may board the other (if it is already open) or wait until it opens.</li> </ul> <p data-end="917" data-start="836">Return the <strong data-end="873" data-start="847">earliest possible time</strong> at which the tourist can finish both rides.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul> <li data-end="181" data-start="145">Plan A (land ride 0 &rarr; water ride 0): <ul> <li data-end="272" data-start="186">Start land ride 0 at time <code data-end="234" data-start="212">landStartTime[0] = 2</code>. Finish at <code data-end="271" data-start="246">2 + landDuration[0] = 6</code>.</li> <li data-end="392" data-start="277">Water ride 0 opens at time <code data-end="327" data-start="304">waterStartTime[0] = 6</code>. Start immediately at <code data-end="353" data-start="350">6</code>, finish at <code data-end="391" data-start="365">6 + waterDuration[0] = 9</code>.</li> </ul> </li> <li data-end="432" data-start="396">Plan B (water ride 0 &rarr; land ride 1): <ul> <li data-end="526" data-start="437">Start water ride 0 at time <code data-end="487" data-start="464">waterStartTime[0] = 6</code>. Finish at <code data-end="525" data-start="499">6 + waterDuration[0] = 9</code>.</li> <li data-end="632" data-start="531">Land ride 1 opens at <code data-end="574" data-start="552">landStartTime[1] = 8</code>. Start at time <code data-end="593" data-start="590">9</code>, finish at <code data-end="631" data-start="605">9 + landDuration[1] = 10</code>.</li> </ul> </li> <li data-end="672" data-start="636">Plan C (land ride 1 &rarr; water ride 0): <ul> <li data-end="763" data-start="677">Start land ride 1 at time <code data-end="725" data-start="703">landStartTime[1] = 8</code>. Finish at <code data-end="762" data-start="737">8 + landDuration[1] = 9</code>.</li> <li data-end="873" data-start="768">Water ride 0 opened at <code data-end="814" data-start="791">waterStartTime[0] = 6</code>. Start at time <code data-end="833" data-start="830">9</code>, finish at <code data-end="872" data-start="845">9 + waterDuration[0] = 12</code>.</li> </ul> </li> <li data-end="913" data-start="877">Plan D (water ride 0 &rarr; land ride 0): <ul> <li data-end="1007" data-start="918">Start water ride 0 at time <code data-end="968" data-start="945">waterStartTime[0] = 6</code>. Finish at <code data-end="1006" data-start="980">6 + waterDuration[0] = 9</code>.</li> <li data-end="1114" data-start="1012">Land ride 0 opened at <code data-end="1056" data-start="1034">landStartTime[0] = 2</code>. Start at time <code data-end="1075" data-start="1072">9</code>, finish at <code data-end="1113" data-start="1087">9 + landDuration[0] = 13</code>.</li> </ul> </li> </ul> <p data-end="1161" data-is-last-node="" data-is-only-node="" data-start="1116">Plan A gives the earliest finish time of 9.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul data-end="1589" data-start="1086"> <li data-end="1124" data-start="1088">Plan A (water ride 0 &rarr; land ride 0): <ul> <li data-end="1219" data-start="1129">Start water ride 0 at time <code data-end="1179" data-start="1156">waterStartTime[0] = 1</code>. Finish at <code data-end="1218" data-start="1191">1 + waterDuration[0] = 11</code>.</li> <li data-end="1338" data-start="1224">Land ride 0 opened at <code data-end="1268" data-start="1246">landStartTime[0] = 5</code>. Start immediately at <code data-end="1295" data-start="1291">11</code> and finish at <code data-end="1337" data-start="1310">11 + landDuration[0] = 14</code>.</li> </ul> </li> <li data-end="1378" data-start="1342">Plan B (land ride 0 &rarr; water ride 0): <ul> <li data-end="1469" data-start="1383">Start land ride 0 at time <code data-end="1431" data-start="1409">landStartTime[0] = 5</code>. Finish at <code data-end="1468" data-start="1443">5 + landDuration[0] = 8</code>.</li> <li data-end="1589" data-start="1474">Water ride 0 opened at <code data-end="1520" data-start="1497">waterStartTime[0] = 1</code>. Start immediately at <code data-end="1546" data-start="1543">8</code> and finish at <code data-end="1588" data-start="1561">8 + waterDuration[0] = 18</code>.</li> </ul> </li> </ul> <p data-end="1640" data-is-last-node="" data-is-only-node="" data-start="1591">Plan A provides the earliest finish time of 14.<strong>​​​​​​​</strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="38" data-start="16"><code data-end="36" data-start="16">1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li> <li data-end="93" data-start="41"><code data-end="91" data-start="41">landStartTime.length == landDuration.length == n</code></li> <li data-end="150" data-start="96"><code data-end="148" data-start="96">waterStartTime.length == waterDuration.length == m</code></li> <li data-end="237" data-start="153"><code data-end="235" data-start="153">1 &lt;= landStartTime[i], landDuration[i], waterStartTime[j], waterDuration[j] &lt;= 10<sup>5</sup></code></li> </ul>
Java
class Solution { public int earliestFinishTime( int[] landStartTime, int[] landDuration, int[] waterStartTime, int[] waterDuration) { int x = calc(landStartTime, landDuration, waterStartTime, waterDuration); int y = calc(waterStartTime, waterDuration, landStartTime, landDuration); return Math.min(x, y); } private int calc(int[] a1, int[] t1, int[] a2, int[] t2) { int minEnd = Integer.MAX_VALUE; for (int i = 0; i < a1.length; ++i) { minEnd = Math.min(minEnd, a1[i] + t1[i]); } int ans = Integer.MAX_VALUE; for (int i = 0; i < a2.length; ++i) { ans = Math.min(ans, Math.max(minEnd, a2[i]) + t2[i]); } return ans; } }
3,635
Earliest Finish Time for Land and Water Rides II
Medium
<p data-end="143" data-start="53">You are given two categories of theme park attractions: <strong data-end="122" data-start="108">land rides</strong> and <strong data-end="142" data-start="127">water rides</strong>.</p> <ul> <li data-end="163" data-start="147"><strong data-end="161" data-start="147">Land rides</strong> <ul> <li data-end="245" data-start="168"><code data-end="186" data-start="168">landStartTime[i]</code> &ndash; the earliest time the <code>i<sup>th</sup></code> land ride can be boarded.</li> <li data-end="306" data-start="250"><code data-end="267" data-start="250">landDuration[i]</code> &ndash; how long the <code>i<sup>th</sup></code> land ride lasts.</li> </ul> </li> <li><strong data-end="325" data-start="310">Water rides</strong> <ul> <li><code data-end="351" data-start="332">waterStartTime[j]</code> &ndash; the earliest time the <code>j<sup>th</sup></code> water ride can be boarded.</li> <li><code data-end="434" data-start="416">waterDuration[j]</code> &ndash; how long the <code>j<sup>th</sup></code> water ride lasts.</li> </ul> </li> </ul> <p data-end="569" data-start="476">A tourist must experience <strong data-end="517" data-start="502">exactly one</strong> ride from <strong data-end="536" data-start="528">each</strong> category, in <strong data-end="566" data-start="550">either order</strong>.</p> <ul> <li data-end="641" data-start="573">A ride may be started at its opening time or <strong data-end="638" data-start="618">any later moment</strong>.</li> <li data-end="715" data-start="644">If a ride is started at time <code data-end="676" data-start="673">t</code>, it finishes at time <code data-end="712" data-start="698">t + duration</code>.</li> <li data-end="834" data-start="718">Immediately after finishing one ride the tourist may board the other (if it is already open) or wait until it opens.</li> </ul> <p data-end="917" data-start="836">Return the <strong data-end="873" data-start="847">earliest possible time</strong> at which the tourist can finish both rides.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul> <li data-end="181" data-start="145">Plan A (land ride 0 &rarr; water ride 0): <ul> <li data-end="272" data-start="186">Start land ride 0 at time <code data-end="234" data-start="212">landStartTime[0] = 2</code>. Finish at <code data-end="271" data-start="246">2 + landDuration[0] = 6</code>.</li> <li data-end="392" data-start="277">Water ride 0 opens at time <code data-end="327" data-start="304">waterStartTime[0] = 6</code>. Start immediately at <code data-end="353" data-start="350">6</code>, finish at <code data-end="391" data-start="365">6 + waterDuration[0] = 9</code>.</li> </ul> </li> <li data-end="432" data-start="396">Plan B (water ride 0 &rarr; land ride 1): <ul> <li data-end="526" data-start="437">Start water ride 0 at time <code data-end="487" data-start="464">waterStartTime[0] = 6</code>. Finish at <code data-end="525" data-start="499">6 + waterDuration[0] = 9</code>.</li> <li data-end="632" data-start="531">Land ride 1 opens at <code data-end="574" data-start="552">landStartTime[1] = 8</code>. Start at time <code data-end="593" data-start="590">9</code>, finish at <code data-end="631" data-start="605">9 + landDuration[1] = 10</code>.</li> </ul> </li> <li data-end="672" data-start="636">Plan C (land ride 1 &rarr; water ride 0): <ul> <li data-end="763" data-start="677">Start land ride 1 at time <code data-end="725" data-start="703">landStartTime[1] = 8</code>. Finish at <code data-end="762" data-start="737">8 + landDuration[1] = 9</code>.</li> <li data-end="873" data-start="768">Water ride 0 opened at <code data-end="814" data-start="791">waterStartTime[0] = 6</code>. Start at time <code data-end="833" data-start="830">9</code>, finish at <code data-end="872" data-start="845">9 + waterDuration[0] = 12</code>.</li> </ul> </li> <li data-end="913" data-start="877">Plan D (water ride 0 &rarr; land ride 0): <ul> <li data-end="1007" data-start="918">Start water ride 0 at time <code data-end="968" data-start="945">waterStartTime[0] = 6</code>. Finish at <code data-end="1006" data-start="980">6 + waterDuration[0] = 9</code>.</li> <li data-end="1114" data-start="1012">Land ride 0 opened at <code data-end="1056" data-start="1034">landStartTime[0] = 2</code>. Start at time <code data-end="1075" data-start="1072">9</code>, finish at <code data-end="1113" data-start="1087">9 + landDuration[0] = 13</code>.</li> </ul> </li> </ul> <p data-end="1161" data-is-last-node="" data-is-only-node="" data-start="1116">Plan A gives the earliest finish time of 9.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul data-end="1589" data-start="1086"> <li data-end="1124" data-start="1088">Plan A (water ride 0 &rarr; land ride 0): <ul> <li data-end="1219" data-start="1129">Start water ride 0 at time <code data-end="1179" data-start="1156">waterStartTime[0] = 1</code>. Finish at <code data-end="1218" data-start="1191">1 + waterDuration[0] = 11</code>.</li> <li data-end="1338" data-start="1224">Land ride 0 opened at <code data-end="1268" data-start="1246">landStartTime[0] = 5</code>. Start immediately at <code data-end="1295" data-start="1291">11</code> and finish at <code data-end="1337" data-start="1310">11 + landDuration[0] = 14</code>.</li> </ul> </li> <li data-end="1378" data-start="1342">Plan B (land ride 0 &rarr; water ride 0): <ul> <li data-end="1469" data-start="1383">Start land ride 0 at time <code data-end="1431" data-start="1409">landStartTime[0] = 5</code>. Finish at <code data-end="1468" data-start="1443">5 + landDuration[0] = 8</code>.</li> <li data-end="1589" data-start="1474">Water ride 0 opened at <code data-end="1520" data-start="1497">waterStartTime[0] = 1</code>. Start immediately at <code data-end="1546" data-start="1543">8</code> and finish at <code data-end="1588" data-start="1561">8 + waterDuration[0] = 18</code>.</li> </ul> </li> </ul> <p data-end="1640" data-is-last-node="" data-is-only-node="" data-start="1591">Plan A provides the earliest finish time of 14.<strong>​​​​​​​</strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="38" data-start="16"><code data-end="36" data-start="16">1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li> <li data-end="93" data-start="41"><code data-end="91" data-start="41">landStartTime.length == landDuration.length == n</code></li> <li data-end="150" data-start="96"><code data-end="148" data-start="96">waterStartTime.length == waterDuration.length == m</code></li> <li data-end="237" data-start="153"><code data-end="235" data-start="153">1 &lt;= landStartTime[i], landDuration[i], waterStartTime[j], waterDuration[j] &lt;= 10<sup>5</sup></code></li> </ul>
Python
class Solution: def earliestFinishTime( self, landStartTime: List[int], landDuration: List[int], waterStartTime: List[int], waterDuration: List[int], ) -> int: def calc(a1, t1, a2, t2): min_end = min(a + t for a, t in zip(a1, t1)) return min(max(a, min_end) + t for a, t in zip(a2, t2)) x = calc(landStartTime, landDuration, waterStartTime, waterDuration) y = calc(waterStartTime, waterDuration, landStartTime, landDuration) return min(x, y)
3,635
Earliest Finish Time for Land and Water Rides II
Medium
<p data-end="143" data-start="53">You are given two categories of theme park attractions: <strong data-end="122" data-start="108">land rides</strong> and <strong data-end="142" data-start="127">water rides</strong>.</p> <ul> <li data-end="163" data-start="147"><strong data-end="161" data-start="147">Land rides</strong> <ul> <li data-end="245" data-start="168"><code data-end="186" data-start="168">landStartTime[i]</code> &ndash; the earliest time the <code>i<sup>th</sup></code> land ride can be boarded.</li> <li data-end="306" data-start="250"><code data-end="267" data-start="250">landDuration[i]</code> &ndash; how long the <code>i<sup>th</sup></code> land ride lasts.</li> </ul> </li> <li><strong data-end="325" data-start="310">Water rides</strong> <ul> <li><code data-end="351" data-start="332">waterStartTime[j]</code> &ndash; the earliest time the <code>j<sup>th</sup></code> water ride can be boarded.</li> <li><code data-end="434" data-start="416">waterDuration[j]</code> &ndash; how long the <code>j<sup>th</sup></code> water ride lasts.</li> </ul> </li> </ul> <p data-end="569" data-start="476">A tourist must experience <strong data-end="517" data-start="502">exactly one</strong> ride from <strong data-end="536" data-start="528">each</strong> category, in <strong data-end="566" data-start="550">either order</strong>.</p> <ul> <li data-end="641" data-start="573">A ride may be started at its opening time or <strong data-end="638" data-start="618">any later moment</strong>.</li> <li data-end="715" data-start="644">If a ride is started at time <code data-end="676" data-start="673">t</code>, it finishes at time <code data-end="712" data-start="698">t + duration</code>.</li> <li data-end="834" data-start="718">Immediately after finishing one ride the tourist may board the other (if it is already open) or wait until it opens.</li> </ul> <p data-end="917" data-start="836">Return the <strong data-end="873" data-start="847">earliest possible time</strong> at which the tourist can finish both rides.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul> <li data-end="181" data-start="145">Plan A (land ride 0 &rarr; water ride 0): <ul> <li data-end="272" data-start="186">Start land ride 0 at time <code data-end="234" data-start="212">landStartTime[0] = 2</code>. Finish at <code data-end="271" data-start="246">2 + landDuration[0] = 6</code>.</li> <li data-end="392" data-start="277">Water ride 0 opens at time <code data-end="327" data-start="304">waterStartTime[0] = 6</code>. Start immediately at <code data-end="353" data-start="350">6</code>, finish at <code data-end="391" data-start="365">6 + waterDuration[0] = 9</code>.</li> </ul> </li> <li data-end="432" data-start="396">Plan B (water ride 0 &rarr; land ride 1): <ul> <li data-end="526" data-start="437">Start water ride 0 at time <code data-end="487" data-start="464">waterStartTime[0] = 6</code>. Finish at <code data-end="525" data-start="499">6 + waterDuration[0] = 9</code>.</li> <li data-end="632" data-start="531">Land ride 1 opens at <code data-end="574" data-start="552">landStartTime[1] = 8</code>. Start at time <code data-end="593" data-start="590">9</code>, finish at <code data-end="631" data-start="605">9 + landDuration[1] = 10</code>.</li> </ul> </li> <li data-end="672" data-start="636">Plan C (land ride 1 &rarr; water ride 0): <ul> <li data-end="763" data-start="677">Start land ride 1 at time <code data-end="725" data-start="703">landStartTime[1] = 8</code>. Finish at <code data-end="762" data-start="737">8 + landDuration[1] = 9</code>.</li> <li data-end="873" data-start="768">Water ride 0 opened at <code data-end="814" data-start="791">waterStartTime[0] = 6</code>. Start at time <code data-end="833" data-start="830">9</code>, finish at <code data-end="872" data-start="845">9 + waterDuration[0] = 12</code>.</li> </ul> </li> <li data-end="913" data-start="877">Plan D (water ride 0 &rarr; land ride 0): <ul> <li data-end="1007" data-start="918">Start water ride 0 at time <code data-end="968" data-start="945">waterStartTime[0] = 6</code>. Finish at <code data-end="1006" data-start="980">6 + waterDuration[0] = 9</code>.</li> <li data-end="1114" data-start="1012">Land ride 0 opened at <code data-end="1056" data-start="1034">landStartTime[0] = 2</code>. Start at time <code data-end="1075" data-start="1072">9</code>, finish at <code data-end="1113" data-start="1087">9 + landDuration[0] = 13</code>.</li> </ul> </li> </ul> <p data-end="1161" data-is-last-node="" data-is-only-node="" data-start="1116">Plan A gives the earliest finish time of 9.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong>​​​​​​​</p> <ul data-end="1589" data-start="1086"> <li data-end="1124" data-start="1088">Plan A (water ride 0 &rarr; land ride 0): <ul> <li data-end="1219" data-start="1129">Start water ride 0 at time <code data-end="1179" data-start="1156">waterStartTime[0] = 1</code>. Finish at <code data-end="1218" data-start="1191">1 + waterDuration[0] = 11</code>.</li> <li data-end="1338" data-start="1224">Land ride 0 opened at <code data-end="1268" data-start="1246">landStartTime[0] = 5</code>. Start immediately at <code data-end="1295" data-start="1291">11</code> and finish at <code data-end="1337" data-start="1310">11 + landDuration[0] = 14</code>.</li> </ul> </li> <li data-end="1378" data-start="1342">Plan B (land ride 0 &rarr; water ride 0): <ul> <li data-end="1469" data-start="1383">Start land ride 0 at time <code data-end="1431" data-start="1409">landStartTime[0] = 5</code>. Finish at <code data-end="1468" data-start="1443">5 + landDuration[0] = 8</code>.</li> <li data-end="1589" data-start="1474">Water ride 0 opened at <code data-end="1520" data-start="1497">waterStartTime[0] = 1</code>. Start immediately at <code data-end="1546" data-start="1543">8</code> and finish at <code data-end="1588" data-start="1561">8 + waterDuration[0] = 18</code>.</li> </ul> </li> </ul> <p data-end="1640" data-is-last-node="" data-is-only-node="" data-start="1591">Plan A provides the earliest finish time of 14.<strong>​​​​​​​</strong></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="38" data-start="16"><code data-end="36" data-start="16">1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li> <li data-end="93" data-start="41"><code data-end="91" data-start="41">landStartTime.length == landDuration.length == n</code></li> <li data-end="150" data-start="96"><code data-end="148" data-start="96">waterStartTime.length == waterDuration.length == m</code></li> <li data-end="237" data-start="153"><code data-end="235" data-start="153">1 &lt;= landStartTime[i], landDuration[i], waterStartTime[j], waterDuration[j] &lt;= 10<sup>5</sup></code></li> </ul>
TypeScript
function earliestFinishTime( landStartTime: number[], landDuration: number[], waterStartTime: number[], waterDuration: number[], ): number { const x = calc(landStartTime, landDuration, waterStartTime, waterDuration); const y = calc(waterStartTime, waterDuration, landStartTime, landDuration); return Math.min(x, y); } function calc(a1: number[], t1: number[], a2: number[], t2: number[]): number { let minEnd = Number.MAX_SAFE_INTEGER; for (let i = 0; i < a1.length; i++) { minEnd = Math.min(minEnd, a1[i] + t1[i]); } let ans = Number.MAX_SAFE_INTEGER; for (let i = 0; i < a2.length; i++) { ans = Math.min(ans, Math.max(minEnd, a2[i]) + t2[i]); } return ans; }
3,637
Trionic Array I
Easy
<p data-end="128" data-start="0">You are given an integer array <code data-end="37" data-start="31">nums</code> of length <code data-end="51" data-start="48">n</code>.</p> <p data-end="128" data-start="0">An array is <strong data-end="76" data-start="65">trionic</strong> if there exist indices <code data-end="117" data-start="100">0 &lt; p &lt; q &lt; n &minus; 1</code> such that:</p> <ul> <li data-end="170" data-start="132"><code data-end="144" data-start="132">nums[0...p]</code> is <strong>strictly</strong> increasing,</li> <li data-end="211" data-start="173"><code data-end="185" data-start="173">nums[p...q]</code> is <strong>strictly</strong> decreasing,</li> <li data-end="252" data-start="214"><code data-end="228" data-start="214">nums[q...n &minus; 1]</code> is <strong>strictly</strong> increasing.</li> </ul> <p data-end="315" data-is-last-node="" data-is-only-node="" data-start="254">Return <code data-end="267" data-start="261">true</code> if <code data-end="277" data-start="271">nums</code> is trionic, otherwise return <code data-end="314" data-start="307">false</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">nums = [1,3,5,4,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>Pick <code data-end="91" data-start="84">p = 2</code>, <code data-end="100" data-start="93">q = 4</code>:</p> <ul> <li><code data-end="130" data-start="108">nums[0...2] = [1, 3, 5]</code> is strictly increasing (<code data-end="166" data-start="155">1 &lt; 3 &lt; 5</code>).</li> <li><code data-end="197" data-start="175">nums[2...4] = [5, 4, 2]</code> is strictly decreasing (<code data-end="233" data-start="222">5 &gt; 4 &gt; 2</code>).</li> <li><code data-end="262" data-start="242">nums[4...5] = [2, 6]</code> is strictly increasing (<code data-end="294" data-start="287">2 &lt; 6</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no way to pick <code>p</code> and <code>q</code> to form the required three segments.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="41" data-start="26"><code data-end="39" data-start="26">3 &lt;= n &lt;= 100</code></li> <li data-end="70" data-start="44"><code data-end="70" data-start="44">-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
C++
class Solution { public: bool isTrionic(vector<int>& nums) { int n = nums.size(); int p = 0; while (p < n - 2 && nums[p] < nums[p + 1]) { p++; } if (p == 0) { return false; } int q = p; while (q < n - 1 && nums[q] > nums[q + 1]) { q++; } if (q == p || q == n - 1) { return false; } while (q < n - 1 && nums[q] < nums[q + 1]) { q++; } return q == n - 1; } };
3,637
Trionic Array I
Easy
<p data-end="128" data-start="0">You are given an integer array <code data-end="37" data-start="31">nums</code> of length <code data-end="51" data-start="48">n</code>.</p> <p data-end="128" data-start="0">An array is <strong data-end="76" data-start="65">trionic</strong> if there exist indices <code data-end="117" data-start="100">0 &lt; p &lt; q &lt; n &minus; 1</code> such that:</p> <ul> <li data-end="170" data-start="132"><code data-end="144" data-start="132">nums[0...p]</code> is <strong>strictly</strong> increasing,</li> <li data-end="211" data-start="173"><code data-end="185" data-start="173">nums[p...q]</code> is <strong>strictly</strong> decreasing,</li> <li data-end="252" data-start="214"><code data-end="228" data-start="214">nums[q...n &minus; 1]</code> is <strong>strictly</strong> increasing.</li> </ul> <p data-end="315" data-is-last-node="" data-is-only-node="" data-start="254">Return <code data-end="267" data-start="261">true</code> if <code data-end="277" data-start="271">nums</code> is trionic, otherwise return <code data-end="314" data-start="307">false</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">nums = [1,3,5,4,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>Pick <code data-end="91" data-start="84">p = 2</code>, <code data-end="100" data-start="93">q = 4</code>:</p> <ul> <li><code data-end="130" data-start="108">nums[0...2] = [1, 3, 5]</code> is strictly increasing (<code data-end="166" data-start="155">1 &lt; 3 &lt; 5</code>).</li> <li><code data-end="197" data-start="175">nums[2...4] = [5, 4, 2]</code> is strictly decreasing (<code data-end="233" data-start="222">5 &gt; 4 &gt; 2</code>).</li> <li><code data-end="262" data-start="242">nums[4...5] = [2, 6]</code> is strictly increasing (<code data-end="294" data-start="287">2 &lt; 6</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no way to pick <code>p</code> and <code>q</code> to form the required three segments.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="41" data-start="26"><code data-end="39" data-start="26">3 &lt;= n &lt;= 100</code></li> <li data-end="70" data-start="44"><code data-end="70" data-start="44">-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Go
func isTrionic(nums []int) bool { n := len(nums) p := 0 for p < n-2 && nums[p] < nums[p+1] { p++ } if p == 0 { return false } q := p for q < n-1 && nums[q] > nums[q+1] { q++ } if q == p || q == n-1 { return false } for q < n-1 && nums[q] < nums[q+1] { q++ } return q == n-1 }
3,637
Trionic Array I
Easy
<p data-end="128" data-start="0">You are given an integer array <code data-end="37" data-start="31">nums</code> of length <code data-end="51" data-start="48">n</code>.</p> <p data-end="128" data-start="0">An array is <strong data-end="76" data-start="65">trionic</strong> if there exist indices <code data-end="117" data-start="100">0 &lt; p &lt; q &lt; n &minus; 1</code> such that:</p> <ul> <li data-end="170" data-start="132"><code data-end="144" data-start="132">nums[0...p]</code> is <strong>strictly</strong> increasing,</li> <li data-end="211" data-start="173"><code data-end="185" data-start="173">nums[p...q]</code> is <strong>strictly</strong> decreasing,</li> <li data-end="252" data-start="214"><code data-end="228" data-start="214">nums[q...n &minus; 1]</code> is <strong>strictly</strong> increasing.</li> </ul> <p data-end="315" data-is-last-node="" data-is-only-node="" data-start="254">Return <code data-end="267" data-start="261">true</code> if <code data-end="277" data-start="271">nums</code> is trionic, otherwise return <code data-end="314" data-start="307">false</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">nums = [1,3,5,4,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>Pick <code data-end="91" data-start="84">p = 2</code>, <code data-end="100" data-start="93">q = 4</code>:</p> <ul> <li><code data-end="130" data-start="108">nums[0...2] = [1, 3, 5]</code> is strictly increasing (<code data-end="166" data-start="155">1 &lt; 3 &lt; 5</code>).</li> <li><code data-end="197" data-start="175">nums[2...4] = [5, 4, 2]</code> is strictly decreasing (<code data-end="233" data-start="222">5 &gt; 4 &gt; 2</code>).</li> <li><code data-end="262" data-start="242">nums[4...5] = [2, 6]</code> is strictly increasing (<code data-end="294" data-start="287">2 &lt; 6</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no way to pick <code>p</code> and <code>q</code> to form the required three segments.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="41" data-start="26"><code data-end="39" data-start="26">3 &lt;= n &lt;= 100</code></li> <li data-end="70" data-start="44"><code data-end="70" data-start="44">-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Java
class Solution { public boolean isTrionic(int[] nums) { int n = nums.length; int p = 0; while (p < n - 2 && nums[p] < nums[p + 1]) { p++; } if (p == 0) { return false; } int q = p; while (q < n - 1 && nums[q] > nums[q + 1]) { q++; } if (q == p || q == n - 1) { return false; } while (q < n - 1 && nums[q] < nums[q + 1]) { q++; } return q == n - 1; } }
3,637
Trionic Array I
Easy
<p data-end="128" data-start="0">You are given an integer array <code data-end="37" data-start="31">nums</code> of length <code data-end="51" data-start="48">n</code>.</p> <p data-end="128" data-start="0">An array is <strong data-end="76" data-start="65">trionic</strong> if there exist indices <code data-end="117" data-start="100">0 &lt; p &lt; q &lt; n &minus; 1</code> such that:</p> <ul> <li data-end="170" data-start="132"><code data-end="144" data-start="132">nums[0...p]</code> is <strong>strictly</strong> increasing,</li> <li data-end="211" data-start="173"><code data-end="185" data-start="173">nums[p...q]</code> is <strong>strictly</strong> decreasing,</li> <li data-end="252" data-start="214"><code data-end="228" data-start="214">nums[q...n &minus; 1]</code> is <strong>strictly</strong> increasing.</li> </ul> <p data-end="315" data-is-last-node="" data-is-only-node="" data-start="254">Return <code data-end="267" data-start="261">true</code> if <code data-end="277" data-start="271">nums</code> is trionic, otherwise return <code data-end="314" data-start="307">false</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">nums = [1,3,5,4,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>Pick <code data-end="91" data-start="84">p = 2</code>, <code data-end="100" data-start="93">q = 4</code>:</p> <ul> <li><code data-end="130" data-start="108">nums[0...2] = [1, 3, 5]</code> is strictly increasing (<code data-end="166" data-start="155">1 &lt; 3 &lt; 5</code>).</li> <li><code data-end="197" data-start="175">nums[2...4] = [5, 4, 2]</code> is strictly decreasing (<code data-end="233" data-start="222">5 &gt; 4 &gt; 2</code>).</li> <li><code data-end="262" data-start="242">nums[4...5] = [2, 6]</code> is strictly increasing (<code data-end="294" data-start="287">2 &lt; 6</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no way to pick <code>p</code> and <code>q</code> to form the required three segments.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="41" data-start="26"><code data-end="39" data-start="26">3 &lt;= n &lt;= 100</code></li> <li data-end="70" data-start="44"><code data-end="70" data-start="44">-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Python
class Solution: def isTrionic(self, nums: List[int]) -> bool: n = len(nums) p = 0 while p < n - 2 and nums[p] < nums[p + 1]: p += 1 if p == 0: return False q = p while q < n - 1 and nums[q] > nums[q + 1]: q += 1 if q == p or q == n - 1: return False while q < n - 1 and nums[q] < nums[q + 1]: q += 1 return q == n - 1
3,637
Trionic Array I
Easy
<p data-end="128" data-start="0">You are given an integer array <code data-end="37" data-start="31">nums</code> of length <code data-end="51" data-start="48">n</code>.</p> <p data-end="128" data-start="0">An array is <strong data-end="76" data-start="65">trionic</strong> if there exist indices <code data-end="117" data-start="100">0 &lt; p &lt; q &lt; n &minus; 1</code> such that:</p> <ul> <li data-end="170" data-start="132"><code data-end="144" data-start="132">nums[0...p]</code> is <strong>strictly</strong> increasing,</li> <li data-end="211" data-start="173"><code data-end="185" data-start="173">nums[p...q]</code> is <strong>strictly</strong> decreasing,</li> <li data-end="252" data-start="214"><code data-end="228" data-start="214">nums[q...n &minus; 1]</code> is <strong>strictly</strong> increasing.</li> </ul> <p data-end="315" data-is-last-node="" data-is-only-node="" data-start="254">Return <code data-end="267" data-start="261">true</code> if <code data-end="277" data-start="271">nums</code> is trionic, otherwise return <code data-end="314" data-start="307">false</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">nums = [1,3,5,4,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>Pick <code data-end="91" data-start="84">p = 2</code>, <code data-end="100" data-start="93">q = 4</code>:</p> <ul> <li><code data-end="130" data-start="108">nums[0...2] = [1, 3, 5]</code> is strictly increasing (<code data-end="166" data-start="155">1 &lt; 3 &lt; 5</code>).</li> <li><code data-end="197" data-start="175">nums[2...4] = [5, 4, 2]</code> is strictly decreasing (<code data-end="233" data-start="222">5 &gt; 4 &gt; 2</code>).</li> <li><code data-end="262" data-start="242">nums[4...5] = [2, 6]</code> is strictly increasing (<code data-end="294" data-start="287">2 &lt; 6</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no way to pick <code>p</code> and <code>q</code> to form the required three segments.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="41" data-start="26"><code data-end="39" data-start="26">3 &lt;= n &lt;= 100</code></li> <li data-end="70" data-start="44"><code data-end="70" data-start="44">-1000 &lt;= nums[i] &lt;= 1000</code></li> </ul>
TypeScript
function isTrionic(nums: number[]): boolean { const n = nums.length; let p = 0; while (p < n - 2 && nums[p] < nums[p + 1]) { p++; } if (p === 0) { return false; } let q = p; while (q < n - 1 && nums[q] > nums[q + 1]) { q++; } if (q === p || q === n - 1) { return false; } while (q < n - 1 && nums[q] < nums[q + 1]) { q++; } return q === n - 1; }
3,638
Maximum Balanced Shipments
Medium
<p data-end="365" data-start="23">You are given an integer array <code data-end="62" data-start="54">weight</code> of length <code data-end="76" data-start="73">n</code>, representing the weights of <code data-end="109" data-start="106">n</code> parcels arranged in a straight line. A <strong data-end="161" data-start="149">shipment</strong> is defined as a contiguous subarray of parcels. A shipment is considered <strong data-end="247" data-start="235">balanced</strong> if the weight of the <strong data-end="284" data-start="269">last parcel</strong> is <strong>strictly less</strong> than the <strong data-end="329" data-start="311">maximum weight</strong> among all parcels in that shipment.</p> <p data-end="528" data-start="371">Select a set of <strong data-end="406" data-start="387">non-overlapping</strong>, contiguous, balanced shipments such that <strong data-end="496" data-start="449">each parcel appears in at most one shipment</strong> (parcels may remain unshipped).</p> <p data-end="587" data-start="507">Return the <strong data-end="545" data-start="518">maximum possible number</strong> of balanced shipments that can be formed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [2,5,1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p data-end="136" data-start="62">We can form the maximum of two balanced shipments as follows:</p> <ul> <li data-end="163" data-start="140">Shipment 1: <code>[2, 5, 1]</code> <ul> <li data-end="195" data-start="168">Maximum parcel weight = 5</li> <li data-end="275" data-start="200">Last parcel weight = 1, which is strictly less than 5. Thus, it&#39;s balanced.</li> </ul> </li> <li data-end="299" data-start="279">Shipment 2: <code>[4, 3]</code> <ul> <li data-end="331" data-start="304">Maximum parcel weight = 4</li> <li data-end="411" data-start="336">Last parcel weight = 3, which is strictly less than 4. Thus, it&#39;s balanced.</li> </ul> </li> </ul> <p data-end="519" data-start="413">It is impossible to partition the parcels to achieve more than two balanced shipments, so the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p data-end="635" data-start="574">No balanced shipment can be formed in this case:</p> <ul> <li data-end="772" data-start="639">A shipment <code>[4, 4]</code> has maximum weight 4 and the last parcel&#39;s weight is also 4, which is not strictly less. Thus, it&#39;s not balanced.</li> <li data-end="885" data-start="775">Single-parcel shipments <code>[4]</code> have the last parcel weight equal to the maximum parcel weight, thus not balanced.</li> </ul> <p data-end="958" data-is-last-node="" data-is-only-node="" data-start="887">As there is no way to form even one balanced shipment, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="8706" data-start="8671"><code data-end="8704" data-start="8671">2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li data-end="8733" data-start="8709"><code data-end="8733" data-start="8709">1 &lt;= weight[i] &lt;= 10<sup>9</sup></code></li> </ul>
C++
class Solution { public: int maxBalancedShipments(vector<int>& weight) { int ans = 0; int mx = 0; for (int x : weight) { mx = max(mx, x); if (x < mx) { ++ans; mx = 0; } } return ans; } };
3,638
Maximum Balanced Shipments
Medium
<p data-end="365" data-start="23">You are given an integer array <code data-end="62" data-start="54">weight</code> of length <code data-end="76" data-start="73">n</code>, representing the weights of <code data-end="109" data-start="106">n</code> parcels arranged in a straight line. A <strong data-end="161" data-start="149">shipment</strong> is defined as a contiguous subarray of parcels. A shipment is considered <strong data-end="247" data-start="235">balanced</strong> if the weight of the <strong data-end="284" data-start="269">last parcel</strong> is <strong>strictly less</strong> than the <strong data-end="329" data-start="311">maximum weight</strong> among all parcels in that shipment.</p> <p data-end="528" data-start="371">Select a set of <strong data-end="406" data-start="387">non-overlapping</strong>, contiguous, balanced shipments such that <strong data-end="496" data-start="449">each parcel appears in at most one shipment</strong> (parcels may remain unshipped).</p> <p data-end="587" data-start="507">Return the <strong data-end="545" data-start="518">maximum possible number</strong> of balanced shipments that can be formed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [2,5,1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p data-end="136" data-start="62">We can form the maximum of two balanced shipments as follows:</p> <ul> <li data-end="163" data-start="140">Shipment 1: <code>[2, 5, 1]</code> <ul> <li data-end="195" data-start="168">Maximum parcel weight = 5</li> <li data-end="275" data-start="200">Last parcel weight = 1, which is strictly less than 5. Thus, it&#39;s balanced.</li> </ul> </li> <li data-end="299" data-start="279">Shipment 2: <code>[4, 3]</code> <ul> <li data-end="331" data-start="304">Maximum parcel weight = 4</li> <li data-end="411" data-start="336">Last parcel weight = 3, which is strictly less than 4. Thus, it&#39;s balanced.</li> </ul> </li> </ul> <p data-end="519" data-start="413">It is impossible to partition the parcels to achieve more than two balanced shipments, so the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p data-end="635" data-start="574">No balanced shipment can be formed in this case:</p> <ul> <li data-end="772" data-start="639">A shipment <code>[4, 4]</code> has maximum weight 4 and the last parcel&#39;s weight is also 4, which is not strictly less. Thus, it&#39;s not balanced.</li> <li data-end="885" data-start="775">Single-parcel shipments <code>[4]</code> have the last parcel weight equal to the maximum parcel weight, thus not balanced.</li> </ul> <p data-end="958" data-is-last-node="" data-is-only-node="" data-start="887">As there is no way to form even one balanced shipment, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="8706" data-start="8671"><code data-end="8704" data-start="8671">2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li data-end="8733" data-start="8709"><code data-end="8733" data-start="8709">1 &lt;= weight[i] &lt;= 10<sup>9</sup></code></li> </ul>
Go
func maxBalancedShipments(weight []int) (ans int) { mx := 0 for _, x := range weight { mx = max(mx, x) if x < mx { ans++ mx = 0 } } return }
3,638
Maximum Balanced Shipments
Medium
<p data-end="365" data-start="23">You are given an integer array <code data-end="62" data-start="54">weight</code> of length <code data-end="76" data-start="73">n</code>, representing the weights of <code data-end="109" data-start="106">n</code> parcels arranged in a straight line. A <strong data-end="161" data-start="149">shipment</strong> is defined as a contiguous subarray of parcels. A shipment is considered <strong data-end="247" data-start="235">balanced</strong> if the weight of the <strong data-end="284" data-start="269">last parcel</strong> is <strong>strictly less</strong> than the <strong data-end="329" data-start="311">maximum weight</strong> among all parcels in that shipment.</p> <p data-end="528" data-start="371">Select a set of <strong data-end="406" data-start="387">non-overlapping</strong>, contiguous, balanced shipments such that <strong data-end="496" data-start="449">each parcel appears in at most one shipment</strong> (parcels may remain unshipped).</p> <p data-end="587" data-start="507">Return the <strong data-end="545" data-start="518">maximum possible number</strong> of balanced shipments that can be formed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [2,5,1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p data-end="136" data-start="62">We can form the maximum of two balanced shipments as follows:</p> <ul> <li data-end="163" data-start="140">Shipment 1: <code>[2, 5, 1]</code> <ul> <li data-end="195" data-start="168">Maximum parcel weight = 5</li> <li data-end="275" data-start="200">Last parcel weight = 1, which is strictly less than 5. Thus, it&#39;s balanced.</li> </ul> </li> <li data-end="299" data-start="279">Shipment 2: <code>[4, 3]</code> <ul> <li data-end="331" data-start="304">Maximum parcel weight = 4</li> <li data-end="411" data-start="336">Last parcel weight = 3, which is strictly less than 4. Thus, it&#39;s balanced.</li> </ul> </li> </ul> <p data-end="519" data-start="413">It is impossible to partition the parcels to achieve more than two balanced shipments, so the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p data-end="635" data-start="574">No balanced shipment can be formed in this case:</p> <ul> <li data-end="772" data-start="639">A shipment <code>[4, 4]</code> has maximum weight 4 and the last parcel&#39;s weight is also 4, which is not strictly less. Thus, it&#39;s not balanced.</li> <li data-end="885" data-start="775">Single-parcel shipments <code>[4]</code> have the last parcel weight equal to the maximum parcel weight, thus not balanced.</li> </ul> <p data-end="958" data-is-last-node="" data-is-only-node="" data-start="887">As there is no way to form even one balanced shipment, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="8706" data-start="8671"><code data-end="8704" data-start="8671">2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li data-end="8733" data-start="8709"><code data-end="8733" data-start="8709">1 &lt;= weight[i] &lt;= 10<sup>9</sup></code></li> </ul>
Java
class Solution { public int maxBalancedShipments(int[] weight) { int ans = 0; int mx = 0; for (int x : weight) { mx = Math.max(mx, x); if (x < mx) { ++ans; mx = 0; } } return ans; } }
3,638
Maximum Balanced Shipments
Medium
<p data-end="365" data-start="23">You are given an integer array <code data-end="62" data-start="54">weight</code> of length <code data-end="76" data-start="73">n</code>, representing the weights of <code data-end="109" data-start="106">n</code> parcels arranged in a straight line. A <strong data-end="161" data-start="149">shipment</strong> is defined as a contiguous subarray of parcels. A shipment is considered <strong data-end="247" data-start="235">balanced</strong> if the weight of the <strong data-end="284" data-start="269">last parcel</strong> is <strong>strictly less</strong> than the <strong data-end="329" data-start="311">maximum weight</strong> among all parcels in that shipment.</p> <p data-end="528" data-start="371">Select a set of <strong data-end="406" data-start="387">non-overlapping</strong>, contiguous, balanced shipments such that <strong data-end="496" data-start="449">each parcel appears in at most one shipment</strong> (parcels may remain unshipped).</p> <p data-end="587" data-start="507">Return the <strong data-end="545" data-start="518">maximum possible number</strong> of balanced shipments that can be formed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [2,5,1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p data-end="136" data-start="62">We can form the maximum of two balanced shipments as follows:</p> <ul> <li data-end="163" data-start="140">Shipment 1: <code>[2, 5, 1]</code> <ul> <li data-end="195" data-start="168">Maximum parcel weight = 5</li> <li data-end="275" data-start="200">Last parcel weight = 1, which is strictly less than 5. Thus, it&#39;s balanced.</li> </ul> </li> <li data-end="299" data-start="279">Shipment 2: <code>[4, 3]</code> <ul> <li data-end="331" data-start="304">Maximum parcel weight = 4</li> <li data-end="411" data-start="336">Last parcel weight = 3, which is strictly less than 4. Thus, it&#39;s balanced.</li> </ul> </li> </ul> <p data-end="519" data-start="413">It is impossible to partition the parcels to achieve more than two balanced shipments, so the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p data-end="635" data-start="574">No balanced shipment can be formed in this case:</p> <ul> <li data-end="772" data-start="639">A shipment <code>[4, 4]</code> has maximum weight 4 and the last parcel&#39;s weight is also 4, which is not strictly less. Thus, it&#39;s not balanced.</li> <li data-end="885" data-start="775">Single-parcel shipments <code>[4]</code> have the last parcel weight equal to the maximum parcel weight, thus not balanced.</li> </ul> <p data-end="958" data-is-last-node="" data-is-only-node="" data-start="887">As there is no way to form even one balanced shipment, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="8706" data-start="8671"><code data-end="8704" data-start="8671">2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li data-end="8733" data-start="8709"><code data-end="8733" data-start="8709">1 &lt;= weight[i] &lt;= 10<sup>9</sup></code></li> </ul>
Python
class Solution: def maxBalancedShipments(self, weight: List[int]) -> int: ans = mx = 0 for x in weight: mx = max(mx, x) if x < mx: ans += 1 mx = 0 return ans
3,638
Maximum Balanced Shipments
Medium
<p data-end="365" data-start="23">You are given an integer array <code data-end="62" data-start="54">weight</code> of length <code data-end="76" data-start="73">n</code>, representing the weights of <code data-end="109" data-start="106">n</code> parcels arranged in a straight line. A <strong data-end="161" data-start="149">shipment</strong> is defined as a contiguous subarray of parcels. A shipment is considered <strong data-end="247" data-start="235">balanced</strong> if the weight of the <strong data-end="284" data-start="269">last parcel</strong> is <strong>strictly less</strong> than the <strong data-end="329" data-start="311">maximum weight</strong> among all parcels in that shipment.</p> <p data-end="528" data-start="371">Select a set of <strong data-end="406" data-start="387">non-overlapping</strong>, contiguous, balanced shipments such that <strong data-end="496" data-start="449">each parcel appears in at most one shipment</strong> (parcels may remain unshipped).</p> <p data-end="587" data-start="507">Return the <strong data-end="545" data-start="518">maximum possible number</strong> of balanced shipments that can be formed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [2,5,1,4,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p data-end="136" data-start="62">We can form the maximum of two balanced shipments as follows:</p> <ul> <li data-end="163" data-start="140">Shipment 1: <code>[2, 5, 1]</code> <ul> <li data-end="195" data-start="168">Maximum parcel weight = 5</li> <li data-end="275" data-start="200">Last parcel weight = 1, which is strictly less than 5. Thus, it&#39;s balanced.</li> </ul> </li> <li data-end="299" data-start="279">Shipment 2: <code>[4, 3]</code> <ul> <li data-end="331" data-start="304">Maximum parcel weight = 4</li> <li data-end="411" data-start="336">Last parcel weight = 3, which is strictly less than 4. Thus, it&#39;s balanced.</li> </ul> </li> </ul> <p data-end="519" data-start="413">It is impossible to partition the parcels to achieve more than two balanced shipments, so the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weight = [4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p data-end="635" data-start="574">No balanced shipment can be formed in this case:</p> <ul> <li data-end="772" data-start="639">A shipment <code>[4, 4]</code> has maximum weight 4 and the last parcel&#39;s weight is also 4, which is not strictly less. Thus, it&#39;s not balanced.</li> <li data-end="885" data-start="775">Single-parcel shipments <code>[4]</code> have the last parcel weight equal to the maximum parcel weight, thus not balanced.</li> </ul> <p data-end="958" data-is-last-node="" data-is-only-node="" data-start="887">As there is no way to form even one balanced shipment, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="8706" data-start="8671"><code data-end="8704" data-start="8671">2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li data-end="8733" data-start="8709"><code data-end="8733" data-start="8709">1 &lt;= weight[i] &lt;= 10<sup>9</sup></code></li> </ul>
TypeScript
function maxBalancedShipments(weight: number[]): number { let [ans, mx] = [0, 0]; for (const x of weight) { mx = Math.max(mx, x); if (x < mx) { ans++; mx = 0; } } return ans; }
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
C++
class Solution { public: int longestSubarray(vector<int>& nums, int k) { unordered_map<int, int> cnt; int ans = 0, cur = 0, l = 0; for (int r = 0; r < nums.size(); ++r) { if (++cnt[nums[r]] == 2) { ++cur; } while (cur > k) { if (--cnt[nums[l++]] == 1) { --cur; } } ans = max(ans, r - l + 1); } return ans; } };
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
Go
func longestSubarray(nums []int, k int) (ans int) { cnt := make(map[int]int) cur, l := 0, 0 for r := 0; r < len(nums); r++ { if cnt[nums[r]]++; cnt[nums[r]] == 2 { cur++ } for cur > k { if cnt[nums[l]]--; cnt[nums[l]] == 1 { cur-- } l++ } ans = max(ans, r-l+1) } return }
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
Java
class Solution { public int longestSubarray(int[] nums, int k) { Map<Integer, Integer> cnt = new HashMap<>(); int ans = 0, cur = 0, l = 0; for (int r = 0; r < nums.length; ++r) { if (cnt.merge(nums[r], 1, Integer::sum) == 2) { ++cur; } while (cur > k) { if (cnt.merge(nums[l++], -1, Integer::sum) == 1) { --cur; } } ans = Math.max(ans, r - l + 1); } return ans; } }
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
Python
class Solution: def longestSubarray(self, nums: List[int], k: int) -> int: cnt = defaultdict(int) ans = cur = l = 0 for r, x in enumerate(nums): cnt[x] += 1 cur += cnt[x] == 2 while cur > k: cnt[nums[l]] -= 1 cur -= cnt[nums[l]] == 1 l += 1 ans = max(ans, r - l + 1) return ans
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
Rust
use std::collections::HashMap; impl Solution { pub fn longest_subarray(nums: Vec<i32>, k: i32) -> i32 { let mut cnt = HashMap::new(); let mut ans = 0; let mut cur = 0; let mut l = 0; for r in 0..nums.len() { let entry = cnt.entry(nums[r]).or_insert(0); *entry += 1; if *entry == 2 { cur += 1; } while cur > k { let entry = cnt.entry(nums[l]).or_insert(0); *entry -= 1; if *entry == 1 { cur -= 1; } l += 1; } ans = ans.max(r - l + 1); } ans as i32 } }
3,641
Longest Semi-Repeating Subarray
Medium
<p>You are given an integer arrayβ€―<code>nums</code> of lengthβ€―<code>n</code> and an integerβ€―<code>k</code>.</p> <p>A <strong>semi‑repeating</strong> subarray is a contiguous subarray in which at mostβ€―<code>k</code>β€―elements repeat (i.e., appear more than once).</p> <p>Return the length of the longest <strong>semi‑repeating</strong> subarray inβ€―<code>nums</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">nums = [1,2,3,1,2,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[2, 3, 1, 2, 3, 4]</code>, which has two repeating elements (2 and 3).</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1, 1, 1, 1, 1]</code>, which has only one repeating element (1).</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1,1], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The longest semi-repeating subarray is <code>[1]</code>, which has no repeating elements.</p> </div> <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>5</sup></code></li> <li><code>0 &lt;= k &lt;= nums.length</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:-2000%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style> <input class="spoilerbutton" onclick="this.value=this.value=='Show Message'?'Hide Message':'Show Message';" type="button" value="Show Message" /> <div class="spoiler"> <div> <p><strong>FOR TESTING ONLY. WILL BE DELETED LATER.</strong></p> // Model solution has runtime of O(n log n), O(n*n) and above should TLE. <pre> # Bromelia import sys import random, json, string import math import datetime from collections import defaultdict ri = random.randint MAX_N = 100_000 MAX_VAL = 100_000 def randomString(n, allowed): return &#39;&#39;.join(random.choices(allowed, k=n)) def randomUnique(x, y, n): return random.sample(range(x, y + 1), n) def randomArray(x, y, n): return [ri(x, y) for _ in range(n)] def shuffle(arr): random.shuffle(arr) return arr def pr(a): file.write(str(a).replace(&quot; &quot;, &quot;&quot;).replace(&quot;\&#39;&quot;, &quot;\&quot;&quot;).replace(&quot;\&quot;null\&quot;&quot;, &quot;null&quot;) + &#39;\n&#39;) def prstr(a): pr(&quot;\&quot;&quot; + a + &quot;\&quot;&quot;) def prtc(tc): nums, k = tc pr(nums) pr(k) def examples(): yield ([1, 2, 3, 1, 2, 3, 4], 2) yield ([1, 1, 1, 1, 1], 4) yield ([1, 1, 1, 1, 1], 0) def smallCases(): yield ([MAX_VAL], 0) yield ([MAX_VAL], 1) for len in range(1, 3 + 1): nums = [0] * len def recursiveGenerate(idx: int): if idx == len: for k in range(0, len + 1): yield (nums, k) else: for nextElement in range(1, len + 1): nums[idx] = nextElement yield from recursiveGenerate(idx + 1) yield from recursiveGenerate(0) def randomCases(): params = [ ( 4, 20, 10, 400), ( 21, 2000, 1000, 100), (MAX_N, MAX_N, 10, 2), (MAX_N, MAX_N, 500, 2), (MAX_N, MAX_N, MAX_VAL, 2), ] for minLen, maxLen, maxVal, testCount in params: for _ in range(testCount): len = ri(minLen, maxLen) k = ri(1, len) nums = [0] * len for i in range(len): nums[i] = ri(1, maxVal) yield (nums, k) def cornerCases(): yield ([MAX_VAL] * MAX_N, 0) yield ([MAX_VAL] * MAX_N, MAX_N) yield ([i for i in range(1, MAX_N + 1)], 0) yield ([i for i in range(1, MAX_N + 1)], MAX_N) yield ([i // 2 + 1 for i in range(MAX_N)], MAX_N // 2 - 1) yield ([i % (MAX_N // 2) + 1 for i in range(MAX_N)], MAX_N // 2 - 1) with open(&#39;test.txt&#39;, &#39;w&#39;) as file: random.seed(0) for tc in examples(): prtc(tc) for tc in smallCases(): prtc(tc) for tc in sorted(list(randomCases()), key = lambda x: len(x[0])): prtc(tc) for tc in cornerCases(): prtc(tc) </pre> </div> </div>
TypeScript
function longestSubarray(nums: number[], k: number): number { const cnt: Map<number, number> = new Map(); let [ans, cur, l] = [0, 0, 0]; for (let r = 0; r < nums.length; r++) { cnt.set(nums[r], (cnt.get(nums[r]) || 0) + 1); if (cnt.get(nums[r]) === 2) { cur++; } while (cur > k) { cnt.set(nums[l], cnt.get(nums[l])! - 1); if (cnt.get(nums[l]) === 1) { cur--; } l++; } ans = Math.max(ans, r - l + 1); } return ans; }
3,642
Find Books with Polarized Opinions
Easy
<p>Table: <code>books</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | book_id | int | | title | varchar | | author | varchar | | genre | varchar | | pages | int | +-------------+---------+ book_id is the unique ID for this table. Each row contains information about a book including its genre and page count. </pre> <p>Table: <code>reading_sessions</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | session_id | int | | book_id | int | | reader_name | varchar | | pages_read | int | | session_rating | int | +----------------+---------+ session_id is the unique ID for this table. Each row represents a reading session where someone read a portion of a book. session_rating is on a scale of 1-5. </pre> <p>Write a solution to find books that have <strong>polarized opinions</strong> - books that receive both very high ratings and very low ratings from different readers.</p> <ul> <li>A book has polarized opinions if it has <code>at least one rating &ge; 4</code> and <code>at least one rating &le; 2</code></li> <li>Only consider books that have <strong>at least </strong><code>5</code><strong> reading sessions</strong></li> <li>Calculate the <strong>rating spread</strong> as (<code>highest_rating - lowest_rating</code>)</li> <li>Calculate the <strong>polarization score</strong> as the number of extreme ratings (<code>ratings &le; 2 or &ge; 4</code>) divided by total sessions</li> <li><strong>Only include</strong> books where <code>polarization score &ge; 0.6</code> (at least <code>60%</code> extreme ratings)</li> </ul> <p>Return <em>the result table ordered by polarization score in <strong>descending</strong> order, then by title in <strong>descending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>books table:</p> <pre class="example-io"> +---------+------------------------+---------------+----------+-------+ | book_id | title | author | genre | pages | +---------+------------------------+---------------+----------+-------+ | 1 | The Great Gatsby | F. Scott | Fiction | 180 | | 2 | To Kill a Mockingbird | Harper Lee | Fiction | 281 | | 3 | 1984 | George Orwell | Dystopian| 328 | | 4 | Pride and Prejudice | Jane Austen | Romance | 432 | | 5 | The Catcher in the Rye | J.D. Salinger | Fiction | 277 | +---------+------------------------+---------------+----------+-------+ </pre> <p>reading_sessions table:</p> <pre class="example-io"> +------------+---------+-------------+------------+----------------+ | session_id | book_id | reader_name | pages_read | session_rating | +------------+---------+-------------+------------+----------------+ | 1 | 1 | Alice | 50 | 5 | | 2 | 1 | Bob | 60 | 1 | | 3 | 1 | Carol | 40 | 4 | | 4 | 1 | David | 30 | 2 | | 5 | 1 | Emma | 45 | 5 | | 6 | 2 | Frank | 80 | 4 | | 7 | 2 | Grace | 70 | 4 | | 8 | 2 | Henry | 90 | 5 | | 9 | 2 | Ivy | 60 | 4 | | 10 | 2 | Jack | 75 | 4 | | 11 | 3 | Kate | 100 | 2 | | 12 | 3 | Liam | 120 | 1 | | 13 | 3 | Mia | 80 | 2 | | 14 | 3 | Noah | 90 | 1 | | 15 | 3 | Olivia | 110 | 4 | | 16 | 3 | Paul | 95 | 5 | | 17 | 4 | Quinn | 150 | 3 | | 18 | 4 | Ruby | 140 | 3 | | 19 | 5 | Sam | 80 | 1 | | 20 | 5 | Tara | 70 | 2 | +------------+---------+-------------+------------+----------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------+---------------+-----------+-------+---------------+--------------------+ | book_id | title | author | genre | pages | rating_spread | polarization_score | +---------+------------------+---------------+-----------+-------+---------------+--------------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 180 | 4 | 1.00 | | 3 | 1984 | George Orwell | Dystopian | 328 | 4 | 1.00 | +---------+------------------+---------------+-----------+-------+---------------+--------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>The Great Gatsby (book_id = 1):</strong> <ul> <li>Has 5 reading sessions (meets minimum requirement)</li> <li>Ratings: 5, 1, 4, 2, 5</li> <li>Has ratings &ge; 4: 5, 4, 5 (3 sessions)</li> <li>Has ratings &le; 2: 1, 2 (2 sessions)</li> <li>Rating spread: 5 - 1 = 4</li> <li>Extreme ratings (&le;2 or &ge;4): All 5 sessions (5, 1, 4, 2, 5)</li> <li>Polarization score: 5/5 = 1.00 (&ge; 0.6, qualifies)</li> </ul> </li> <li><strong>1984 (book_id = 3):</strong> <ul> <li>Has 6 reading sessions (meets minimum requirement)</li> <li>Ratings: 2, 1, 2, 1, 4, 5</li> <li>Has ratings &ge; 4: 4, 5 (2 sessions)</li> <li>Has ratings &le; 2: 2, 1, 2, 1 (4 sessions)</li> <li>Rating spread: 5 - 1 = 4</li> <li>Extreme ratings (&le;2 or &ge;4): All 6 sessions (2, 1, 2, 1, 4, 5)</li> <li>Polarization score: 6/6 = 1.00 (&ge; 0.6, qualifies)</li> </ul> </li> <li><strong>Books not included:</strong> <ul> <li>To Kill a Mockingbird (book_id = 2): All ratings are 4-5, no low ratings (&le;2)</li> <li>Pride and Prejudice (book_id = 4): Only 2 sessions (&lt; 5 minimum)</li> <li>The Catcher in the Rye (book_id = 5): Only 2 sessions (&lt; 5 minimum)</li> </ul> </li> </ul> <p>The result table is ordered by polarization score in descending order, then by book title in descending order.</p> </div>
Database
Python
import pandas as pd from decimal import Decimal, ROUND_HALF_UP def find_polarized_books( books: pd.DataFrame, reading_sessions: pd.DataFrame ) -> pd.DataFrame: df = books.merge(reading_sessions, on="book_id") agg_df = ( df.groupby(["book_id", "title", "author", "genre", "pages"]) .agg( max_rating=("session_rating", "max"), min_rating=("session_rating", "min"), rating_spread=("session_rating", lambda x: x.max() - x.min()), count_sessions=("session_rating", "count"), low_or_high_count=("session_rating", lambda x: ((x <= 2) | (x >= 4)).sum()), ) .reset_index() ) agg_df["polarization_score"] = agg_df.apply( lambda r: float( Decimal(r["low_or_high_count"] / r["count_sessions"]).quantize( Decimal("0.01"), rounding=ROUND_HALF_UP ) ), axis=1, ) result = agg_df[ (agg_df["count_sessions"] >= 5) & (agg_df["max_rating"] >= 4) & (agg_df["min_rating"] <= 2) & (agg_df["polarization_score"] >= 0.6) ] return result.sort_values( by=["polarization_score", "title"], ascending=[False, False] )[ [ "book_id", "title", "author", "genre", "pages", "rating_spread", "polarization_score", ] ]
3,642
Find Books with Polarized Opinions
Easy
<p>Table: <code>books</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | book_id | int | | title | varchar | | author | varchar | | genre | varchar | | pages | int | +-------------+---------+ book_id is the unique ID for this table. Each row contains information about a book including its genre and page count. </pre> <p>Table: <code>reading_sessions</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | session_id | int | | book_id | int | | reader_name | varchar | | pages_read | int | | session_rating | int | +----------------+---------+ session_id is the unique ID for this table. Each row represents a reading session where someone read a portion of a book. session_rating is on a scale of 1-5. </pre> <p>Write a solution to find books that have <strong>polarized opinions</strong> - books that receive both very high ratings and very low ratings from different readers.</p> <ul> <li>A book has polarized opinions if it has <code>at least one rating &ge; 4</code> and <code>at least one rating &le; 2</code></li> <li>Only consider books that have <strong>at least </strong><code>5</code><strong> reading sessions</strong></li> <li>Calculate the <strong>rating spread</strong> as (<code>highest_rating - lowest_rating</code>)</li> <li>Calculate the <strong>polarization score</strong> as the number of extreme ratings (<code>ratings &le; 2 or &ge; 4</code>) divided by total sessions</li> <li><strong>Only include</strong> books where <code>polarization score &ge; 0.6</code> (at least <code>60%</code> extreme ratings)</li> </ul> <p>Return <em>the result table ordered by polarization score in <strong>descending</strong> order, then by title in <strong>descending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>books table:</p> <pre class="example-io"> +---------+------------------------+---------------+----------+-------+ | book_id | title | author | genre | pages | +---------+------------------------+---------------+----------+-------+ | 1 | The Great Gatsby | F. Scott | Fiction | 180 | | 2 | To Kill a Mockingbird | Harper Lee | Fiction | 281 | | 3 | 1984 | George Orwell | Dystopian| 328 | | 4 | Pride and Prejudice | Jane Austen | Romance | 432 | | 5 | The Catcher in the Rye | J.D. Salinger | Fiction | 277 | +---------+------------------------+---------------+----------+-------+ </pre> <p>reading_sessions table:</p> <pre class="example-io"> +------------+---------+-------------+------------+----------------+ | session_id | book_id | reader_name | pages_read | session_rating | +------------+---------+-------------+------------+----------------+ | 1 | 1 | Alice | 50 | 5 | | 2 | 1 | Bob | 60 | 1 | | 3 | 1 | Carol | 40 | 4 | | 4 | 1 | David | 30 | 2 | | 5 | 1 | Emma | 45 | 5 | | 6 | 2 | Frank | 80 | 4 | | 7 | 2 | Grace | 70 | 4 | | 8 | 2 | Henry | 90 | 5 | | 9 | 2 | Ivy | 60 | 4 | | 10 | 2 | Jack | 75 | 4 | | 11 | 3 | Kate | 100 | 2 | | 12 | 3 | Liam | 120 | 1 | | 13 | 3 | Mia | 80 | 2 | | 14 | 3 | Noah | 90 | 1 | | 15 | 3 | Olivia | 110 | 4 | | 16 | 3 | Paul | 95 | 5 | | 17 | 4 | Quinn | 150 | 3 | | 18 | 4 | Ruby | 140 | 3 | | 19 | 5 | Sam | 80 | 1 | | 20 | 5 | Tara | 70 | 2 | +------------+---------+-------------+------------+----------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------+---------------+-----------+-------+---------------+--------------------+ | book_id | title | author | genre | pages | rating_spread | polarization_score | +---------+------------------+---------------+-----------+-------+---------------+--------------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 180 | 4 | 1.00 | | 3 | 1984 | George Orwell | Dystopian | 328 | 4 | 1.00 | +---------+------------------+---------------+-----------+-------+---------------+--------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>The Great Gatsby (book_id = 1):</strong> <ul> <li>Has 5 reading sessions (meets minimum requirement)</li> <li>Ratings: 5, 1, 4, 2, 5</li> <li>Has ratings &ge; 4: 5, 4, 5 (3 sessions)</li> <li>Has ratings &le; 2: 1, 2 (2 sessions)</li> <li>Rating spread: 5 - 1 = 4</li> <li>Extreme ratings (&le;2 or &ge;4): All 5 sessions (5, 1, 4, 2, 5)</li> <li>Polarization score: 5/5 = 1.00 (&ge; 0.6, qualifies)</li> </ul> </li> <li><strong>1984 (book_id = 3):</strong> <ul> <li>Has 6 reading sessions (meets minimum requirement)</li> <li>Ratings: 2, 1, 2, 1, 4, 5</li> <li>Has ratings &ge; 4: 4, 5 (2 sessions)</li> <li>Has ratings &le; 2: 2, 1, 2, 1 (4 sessions)</li> <li>Rating spread: 5 - 1 = 4</li> <li>Extreme ratings (&le;2 or &ge;4): All 6 sessions (2, 1, 2, 1, 4, 5)</li> <li>Polarization score: 6/6 = 1.00 (&ge; 0.6, qualifies)</li> </ul> </li> <li><strong>Books not included:</strong> <ul> <li>To Kill a Mockingbird (book_id = 2): All ratings are 4-5, no low ratings (&le;2)</li> <li>Pride and Prejudice (book_id = 4): Only 2 sessions (&lt; 5 minimum)</li> <li>The Catcher in the Rye (book_id = 5): Only 2 sessions (&lt; 5 minimum)</li> </ul> </li> </ul> <p>The result table is ordered by polarization score in descending order, then by book title in descending order.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT book_id, title, author, genre, pages, (MAX(session_rating) - MIN(session_rating)) AS rating_spread, ROUND((SUM(session_rating <= 2) + SUM(session_rating >= 4)) / COUNT(1), 2) polarization_score FROM books JOIN reading_sessions USING (book_id) GROUP BY book_id HAVING COUNT(1) >= 5 AND MAX(session_rating) >= 4 AND MIN(session_rating) <= 2 AND polarization_score >= 0.6 ORDER BY polarization_score DESC, title DESC;
3,643
Flip Square Submatrix Vertically
Easy
<p>You are given an <code>m x n</code> integer matrix <code>grid</code>, and three integers <code>x</code>, <code>y</code>, and <code>k</code>.</p> <p>The integers <code>x</code> and <code>y</code> represent the row and column indices of the <strong>top-left</strong> corner of a <strong>square</strong> submatrix and the integer <code>k</code> represents the size (side length) of the square submatrix.</p> <p>Your task is to flip the submatrix by reversing the order of its rows vertically.</p> <p>Return the updated matrix.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexmdrawio.png" style="width: 300px; height: 116px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = </span>[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]<span class="example-io">, x = 1, y = 0, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexm2drawio.png" style="width: 350px; height: 68px;" />​​​​​​​ <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[3,4,4,2],[2,3,2,3]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <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;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 100</code></li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>1 &lt;= k &lt;= min(m - x, n - y)</code></li> </ul>
C++
class Solution { public: vector<vector<int>> reverseSubmatrix(vector<vector<int>>& grid, int x, int y, int k) { for (int i = x; i < x + k / 2; i++) { int i2 = x + k - 1 - (i - x); for (int j = y; j < y + k; j++) { swap(grid[i][j], grid[i2][j]); } } return grid; } };
3,643
Flip Square Submatrix Vertically
Easy
<p>You are given an <code>m x n</code> integer matrix <code>grid</code>, and three integers <code>x</code>, <code>y</code>, and <code>k</code>.</p> <p>The integers <code>x</code> and <code>y</code> represent the row and column indices of the <strong>top-left</strong> corner of a <strong>square</strong> submatrix and the integer <code>k</code> represents the size (side length) of the square submatrix.</p> <p>Your task is to flip the submatrix by reversing the order of its rows vertically.</p> <p>Return the updated matrix.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexmdrawio.png" style="width: 300px; height: 116px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = </span>[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]<span class="example-io">, x = 1, y = 0, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexm2drawio.png" style="width: 350px; height: 68px;" />​​​​​​​ <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[3,4,4,2],[2,3,2,3]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <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;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 100</code></li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>1 &lt;= k &lt;= min(m - x, n - y)</code></li> </ul>
Go
func reverseSubmatrix(grid [][]int, x int, y int, k int) [][]int { for i := x; i < x+k/2; i++ { i2 := x + k - 1 - (i - x) for j := y; j < y+k; j++ { grid[i][j], grid[i2][j] = grid[i2][j], grid[i][j] } } return grid }
3,643
Flip Square Submatrix Vertically
Easy
<p>You are given an <code>m x n</code> integer matrix <code>grid</code>, and three integers <code>x</code>, <code>y</code>, and <code>k</code>.</p> <p>The integers <code>x</code> and <code>y</code> represent the row and column indices of the <strong>top-left</strong> corner of a <strong>square</strong> submatrix and the integer <code>k</code> represents the size (side length) of the square submatrix.</p> <p>Your task is to flip the submatrix by reversing the order of its rows vertically.</p> <p>Return the updated matrix.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexmdrawio.png" style="width: 300px; height: 116px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = </span>[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]<span class="example-io">, x = 1, y = 0, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexm2drawio.png" style="width: 350px; height: 68px;" />​​​​​​​ <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[3,4,4,2],[2,3,2,3]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <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;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 100</code></li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>1 &lt;= k &lt;= min(m - x, n - y)</code></li> </ul>
Java
class Solution { public int[][] reverseSubmatrix(int[][] grid, int x, int y, int k) { for (int i = x; i < x + k / 2; i++) { int i2 = x + k - 1 - (i - x); for (int j = y; j < y + k; j++) { int t = grid[i][j]; grid[i][j] = grid[i2][j]; grid[i2][j] = t; } } return grid; } }
3,643
Flip Square Submatrix Vertically
Easy
<p>You are given an <code>m x n</code> integer matrix <code>grid</code>, and three integers <code>x</code>, <code>y</code>, and <code>k</code>.</p> <p>The integers <code>x</code> and <code>y</code> represent the row and column indices of the <strong>top-left</strong> corner of a <strong>square</strong> submatrix and the integer <code>k</code> represents the size (side length) of the square submatrix.</p> <p>Your task is to flip the submatrix by reversing the order of its rows vertically.</p> <p>Return the updated matrix.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexmdrawio.png" style="width: 300px; height: 116px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = </span>[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]<span class="example-io">, x = 1, y = 0, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexm2drawio.png" style="width: 350px; height: 68px;" />​​​​​​​ <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[3,4,4,2],[2,3,2,3]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <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;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 100</code></li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>1 &lt;= k &lt;= min(m - x, n - y)</code></li> </ul>
Python
class Solution: def reverseSubmatrix( self, grid: List[List[int]], x: int, y: int, k: int ) -> List[List[int]]: for i in range(x, x + k // 2): i2 = x + k - 1 - (i - x) for j in range(y, y + k): grid[i][j], grid[i2][j] = grid[i2][j], grid[i][j] return grid
3,643
Flip Square Submatrix Vertically
Easy
<p>You are given an <code>m x n</code> integer matrix <code>grid</code>, and three integers <code>x</code>, <code>y</code>, and <code>k</code>.</p> <p>The integers <code>x</code> and <code>y</code> represent the row and column indices of the <strong>top-left</strong> corner of a <strong>square</strong> submatrix and the integer <code>k</code> represents the size (side length) of the square submatrix.</p> <p>Your task is to flip the submatrix by reversing the order of its rows vertically.</p> <p>Return the updated matrix.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexmdrawio.png" style="width: 300px; height: 116px;" /> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = </span>[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]<span class="example-io">, x = 1, y = 0, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2,3,4],[13,14,15,8],[9,10,11,12],[5,6,7,16]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3600-3699/3643.Flip%20Square%20Submatrix%20Vertically/images/gridexm2drawio.png" style="width: 350px; height: 68px;" />​​​​​​​ <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,4,2,3],[2,3,4,2]], x = 0, y = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[3,4,4,2],[2,3,2,3]]</span></p> <p><strong>Explanation:</strong></p> <p>The diagram above shows the grid before and after the transformation.</p> </div> <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;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 100</code></li> <li><code>0 &lt;= x &lt; m</code></li> <li><code>0 &lt;= y &lt; n</code></li> <li><code>1 &lt;= k &lt;= min(m - x, n - y)</code></li> </ul>
TypeScript
function reverseSubmatrix(grid: number[][], x: number, y: number, k: number): number[][] { for (let i = x; i < x + Math.floor(k / 2); i++) { const i2 = x + k - 1 - (i - x); for (let j = y; j < y + k; j++) { [grid[i][j], grid[i2][j]] = [grid[i2][j], grid[i][j]]; } } return grid; }
3,644
Maximum K to Sort a Permutation
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>, where <code>nums</code> is a <strong><span data-keyword="permutation-array">permutation</span></strong> of the numbers in the range <code>[0..n - 1]</code>.</p> <p>You may swap elements at indices <code>i</code> and <code>j</code> <strong>only if</strong> <code>nums[i] AND nums[j] == k</code>, where <code>AND</code> denotes the bitwise AND operation and <code>k</code> is a <strong>non-negative</strong> integer.</p> <p>Return the <strong>maximum</strong> value of <code>k</code> such that the array can be sorted in <strong>non-decreasing</strong> order using any number of such swaps. If <code>nums</code> is already sorted, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 1</code>. Swapping <code>nums[1] = 3</code> and <code>nums[3] = 1</code> is allowed since <code>nums[1] AND nums[3] == 1</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 2</code>. Swapping <code>nums[2] = 3</code> and <code>nums[3] = 2</code> is allowed since <code>nums[2] AND nums[3] == 2</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Only <code>k = 0</code> allows sorting since no greater <code>k</code> allows the required swaps where <code>nums[i] AND nums[j] == k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n - 1</code></li> <li><code>nums</code> is a permutation of integers from <code>0</code> to <code>n - 1</code>.</li> </ul>
C++
class Solution { public: int sortPermutation(vector<int>& nums) { int ans = -1; for (int i = 0; i < nums.size(); ++i) { if (i != nums[i]) { ans &= nums[i]; } } return max(ans, 0); } };
3,644
Maximum K to Sort a Permutation
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>, where <code>nums</code> is a <strong><span data-keyword="permutation-array">permutation</span></strong> of the numbers in the range <code>[0..n - 1]</code>.</p> <p>You may swap elements at indices <code>i</code> and <code>j</code> <strong>only if</strong> <code>nums[i] AND nums[j] == k</code>, where <code>AND</code> denotes the bitwise AND operation and <code>k</code> is a <strong>non-negative</strong> integer.</p> <p>Return the <strong>maximum</strong> value of <code>k</code> such that the array can be sorted in <strong>non-decreasing</strong> order using any number of such swaps. If <code>nums</code> is already sorted, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 1</code>. Swapping <code>nums[1] = 3</code> and <code>nums[3] = 1</code> is allowed since <code>nums[1] AND nums[3] == 1</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 2</code>. Swapping <code>nums[2] = 3</code> and <code>nums[3] = 2</code> is allowed since <code>nums[2] AND nums[3] == 2</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Only <code>k = 0</code> allows sorting since no greater <code>k</code> allows the required swaps where <code>nums[i] AND nums[j] == k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n - 1</code></li> <li><code>nums</code> is a permutation of integers from <code>0</code> to <code>n - 1</code>.</li> </ul>
Go
func sortPermutation(nums []int) int { ans := -1 for i, x := range nums { if i != x { ans &= x } } return max(ans, 0) }
3,644
Maximum K to Sort a Permutation
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>, where <code>nums</code> is a <strong><span data-keyword="permutation-array">permutation</span></strong> of the numbers in the range <code>[0..n - 1]</code>.</p> <p>You may swap elements at indices <code>i</code> and <code>j</code> <strong>only if</strong> <code>nums[i] AND nums[j] == k</code>, where <code>AND</code> denotes the bitwise AND operation and <code>k</code> is a <strong>non-negative</strong> integer.</p> <p>Return the <strong>maximum</strong> value of <code>k</code> such that the array can be sorted in <strong>non-decreasing</strong> order using any number of such swaps. If <code>nums</code> is already sorted, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 1</code>. Swapping <code>nums[1] = 3</code> and <code>nums[3] = 1</code> is allowed since <code>nums[1] AND nums[3] == 1</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 2</code>. Swapping <code>nums[2] = 3</code> and <code>nums[3] = 2</code> is allowed since <code>nums[2] AND nums[3] == 2</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Only <code>k = 0</code> allows sorting since no greater <code>k</code> allows the required swaps where <code>nums[i] AND nums[j] == k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n - 1</code></li> <li><code>nums</code> is a permutation of integers from <code>0</code> to <code>n - 1</code>.</li> </ul>
Java
class Solution { public int sortPermutation(int[] nums) { int ans = -1; for (int i = 0; i < nums.length; ++i) { if (i != nums[i]) { ans &= nums[i]; } } return Math.max(ans, 0); } }
3,644
Maximum K to Sort a Permutation
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>, where <code>nums</code> is a <strong><span data-keyword="permutation-array">permutation</span></strong> of the numbers in the range <code>[0..n - 1]</code>.</p> <p>You may swap elements at indices <code>i</code> and <code>j</code> <strong>only if</strong> <code>nums[i] AND nums[j] == k</code>, where <code>AND</code> denotes the bitwise AND operation and <code>k</code> is a <strong>non-negative</strong> integer.</p> <p>Return the <strong>maximum</strong> value of <code>k</code> such that the array can be sorted in <strong>non-decreasing</strong> order using any number of such swaps. If <code>nums</code> is already sorted, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 1</code>. Swapping <code>nums[1] = 3</code> and <code>nums[3] = 1</code> is allowed since <code>nums[1] AND nums[3] == 1</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 2</code>. Swapping <code>nums[2] = 3</code> and <code>nums[3] = 2</code> is allowed since <code>nums[2] AND nums[3] == 2</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Only <code>k = 0</code> allows sorting since no greater <code>k</code> allows the required swaps where <code>nums[i] AND nums[j] == k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n - 1</code></li> <li><code>nums</code> is a permutation of integers from <code>0</code> to <code>n - 1</code>.</li> </ul>
Python
class Solution: def sortPermutation(self, nums: List[int]) -> int: ans = -1 for i, x in enumerate(nums): if i != x: ans &= x return max(ans, 0)
3,644
Maximum K to Sort a Permutation
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>, where <code>nums</code> is a <strong><span data-keyword="permutation-array">permutation</span></strong> of the numbers in the range <code>[0..n - 1]</code>.</p> <p>You may swap elements at indices <code>i</code> and <code>j</code> <strong>only if</strong> <code>nums[i] AND nums[j] == k</code>, where <code>AND</code> denotes the bitwise AND operation and <code>k</code> is a <strong>non-negative</strong> integer.</p> <p>Return the <strong>maximum</strong> value of <code>k</code> such that the array can be sorted in <strong>non-decreasing</strong> order using any number of such swaps. If <code>nums</code> is already sorted, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 1</code>. Swapping <code>nums[1] = 3</code> and <code>nums[3] = 1</code> is allowed since <code>nums[1] AND nums[3] == 1</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Choose <code>k = 2</code>. Swapping <code>nums[2] = 3</code> and <code>nums[3] = 2</code> is allowed since <code>nums[2] AND nums[3] == 2</code>, resulting in a sorted permutation: <code>[0, 1, 2, 3]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Only <code>k = 0</code> allows sorting since no greater <code>k</code> allows the required swaps where <code>nums[i] AND nums[j] == k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= n - 1</code></li> <li><code>nums</code> is a permutation of integers from <code>0</code> to <code>n - 1</code>.</li> </ul>
TypeScript
function sortPermutation(nums: number[]): number { let ans = -1; for (let i = 0; i < nums.length; ++i) { if (i != nums[i]) { ans &= nums[i]; } } return Math.max(ans, 0); }
3,645
Maximum Total from Optimal Activation Order
Medium
<p>You are given two integer arrays <code>value</code> and <code>limit</code>, both of length <code>n</code>.</p> <p>Initially, all elements are <strong>inactive</strong>. You may activate them in any order.</p> <ul> <li>To activate an inactive element at index <code>i</code>, the number of <strong>currently</strong> active elements must be <strong>strictly less</strong> than <code>limit[i]</code>.</li> <li>When you activate the element at index <code>i</code>, it adds <code>value[i]</code> to the <strong>total</strong> activation value (i.e., the sum of <code>value[i]</code> for all elements that have undergone activation operations).</li> <li>After each activation, if the number of <strong>currently</strong> active elements becomes <code>x</code>, then <strong>all</strong> elements <code>j</code> with <code>limit[j] &lt;= x</code> become <strong>permanently</strong> inactive, even if they are already active.</li> </ul> <p>Return the <strong>maximum</strong> <strong>total</strong> you can obtain by choosing the activation order optimally.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [3,5,8], limit = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 1</code> as <code>limit[1] = 1</code></td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">8</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">8</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 0</code> as <code>limit[0] = 2</code></td> <td align="center" style="border: 1px solid black;">[1, 2]</td> <td align="center" style="border: 1px solid black;">16</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 16.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,2,6], limit = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">6</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 2</code> as <code>limit[j] = 1</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2]</td> <td align="center" style="border: 1px solid black;">6</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 6.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,1,5,2], limit = [3,3,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:​​​​​​​<strong>​​​​​​​</strong></p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[ ]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 2</code> as <code>limit[2] = 2</code></td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">9</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">10</td> </tr> <tr> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 3</code> as <code>limit[j] = 3</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2, 3]</td> <td align="center" style="border: 1px solid black;">12</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 12.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == value.length == limit.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= value[i] &lt;= 10<sup>5</sup></code>​​​​​​​</li> <li><code>1 &lt;= limit[i] &lt;= n</code></li> </ul>
C++
class Solution { public: long long maxTotal(vector<int>& value, vector<int>& limit) { unordered_map<int, vector<int>> g; int n = value.size(); for (int i = 0; i < n; ++i) { g[limit[i]].push_back(value[i]); } long long ans = 0; for (auto& [lim, vs] : g) { sort(vs.begin(), vs.end(), greater<int>()); for (int i = 0; i < min(lim, (int) vs.size()); ++i) { ans += vs[i]; } } return ans; } };
3,645
Maximum Total from Optimal Activation Order
Medium
<p>You are given two integer arrays <code>value</code> and <code>limit</code>, both of length <code>n</code>.</p> <p>Initially, all elements are <strong>inactive</strong>. You may activate them in any order.</p> <ul> <li>To activate an inactive element at index <code>i</code>, the number of <strong>currently</strong> active elements must be <strong>strictly less</strong> than <code>limit[i]</code>.</li> <li>When you activate the element at index <code>i</code>, it adds <code>value[i]</code> to the <strong>total</strong> activation value (i.e., the sum of <code>value[i]</code> for all elements that have undergone activation operations).</li> <li>After each activation, if the number of <strong>currently</strong> active elements becomes <code>x</code>, then <strong>all</strong> elements <code>j</code> with <code>limit[j] &lt;= x</code> become <strong>permanently</strong> inactive, even if they are already active.</li> </ul> <p>Return the <strong>maximum</strong> <strong>total</strong> you can obtain by choosing the activation order optimally.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [3,5,8], limit = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 1</code> as <code>limit[1] = 1</code></td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">8</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">8</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 0</code> as <code>limit[0] = 2</code></td> <td align="center" style="border: 1px solid black;">[1, 2]</td> <td align="center" style="border: 1px solid black;">16</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 16.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,2,6], limit = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">6</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 2</code> as <code>limit[j] = 1</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2]</td> <td align="center" style="border: 1px solid black;">6</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 6.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,1,5,2], limit = [3,3,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:​​​​​​​<strong>​​​​​​​</strong></p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[ ]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 2</code> as <code>limit[2] = 2</code></td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">9</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">10</td> </tr> <tr> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 3</code> as <code>limit[j] = 3</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2, 3]</td> <td align="center" style="border: 1px solid black;">12</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 12.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == value.length == limit.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= value[i] &lt;= 10<sup>5</sup></code>​​​​​​​</li> <li><code>1 &lt;= limit[i] &lt;= n</code></li> </ul>
Go
func maxTotal(value []int, limit []int) (ans int64) { g := make(map[int][]int) for i := range value { g[limit[i]] = append(g[limit[i]], value[i]) } for lim, vs := range g { slices.SortFunc(vs, func(a, b int) int { return b - a }) for i := 0; i < min(lim, len(vs)); i++ { ans += int64(vs[i]) } } return }
3,645
Maximum Total from Optimal Activation Order
Medium
<p>You are given two integer arrays <code>value</code> and <code>limit</code>, both of length <code>n</code>.</p> <p>Initially, all elements are <strong>inactive</strong>. You may activate them in any order.</p> <ul> <li>To activate an inactive element at index <code>i</code>, the number of <strong>currently</strong> active elements must be <strong>strictly less</strong> than <code>limit[i]</code>.</li> <li>When you activate the element at index <code>i</code>, it adds <code>value[i]</code> to the <strong>total</strong> activation value (i.e., the sum of <code>value[i]</code> for all elements that have undergone activation operations).</li> <li>After each activation, if the number of <strong>currently</strong> active elements becomes <code>x</code>, then <strong>all</strong> elements <code>j</code> with <code>limit[j] &lt;= x</code> become <strong>permanently</strong> inactive, even if they are already active.</li> </ul> <p>Return the <strong>maximum</strong> <strong>total</strong> you can obtain by choosing the activation order optimally.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [3,5,8], limit = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 1</code> as <code>limit[1] = 1</code></td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">8</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">8</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 0</code> as <code>limit[0] = 2</code></td> <td align="center" style="border: 1px solid black;">[1, 2]</td> <td align="center" style="border: 1px solid black;">16</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 16.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,2,6], limit = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">6</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 2</code> as <code>limit[j] = 1</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2]</td> <td align="center" style="border: 1px solid black;">6</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 6.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,1,5,2], limit = [3,3,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:​​​​​​​<strong>​​​​​​​</strong></p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[ ]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 2</code> as <code>limit[2] = 2</code></td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">9</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">10</td> </tr> <tr> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 3</code> as <code>limit[j] = 3</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2, 3]</td> <td align="center" style="border: 1px solid black;">12</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 12.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == value.length == limit.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= value[i] &lt;= 10<sup>5</sup></code>​​​​​​​</li> <li><code>1 &lt;= limit[i] &lt;= n</code></li> </ul>
Java
class Solution { public long maxTotal(int[] value, int[] limit) { Map<Integer, List<Integer>> g = new HashMap<>(); for (int i = 0; i < value.length; ++i) { g.computeIfAbsent(limit[i], k -> new ArrayList<>()).add(value[i]); } long ans = 0; for (var e : g.entrySet()) { int lim = e.getKey(); var vs = e.getValue(); vs.sort((a, b) -> b - a); for (int i = 0; i < Math.min(lim, vs.size()); ++i) { ans += vs.get(i); } } return ans; } }
3,645
Maximum Total from Optimal Activation Order
Medium
<p>You are given two integer arrays <code>value</code> and <code>limit</code>, both of length <code>n</code>.</p> <p>Initially, all elements are <strong>inactive</strong>. You may activate them in any order.</p> <ul> <li>To activate an inactive element at index <code>i</code>, the number of <strong>currently</strong> active elements must be <strong>strictly less</strong> than <code>limit[i]</code>.</li> <li>When you activate the element at index <code>i</code>, it adds <code>value[i]</code> to the <strong>total</strong> activation value (i.e., the sum of <code>value[i]</code> for all elements that have undergone activation operations).</li> <li>After each activation, if the number of <strong>currently</strong> active elements becomes <code>x</code>, then <strong>all</strong> elements <code>j</code> with <code>limit[j] &lt;= x</code> become <strong>permanently</strong> inactive, even if they are already active.</li> </ul> <p>Return the <strong>maximum</strong> <strong>total</strong> you can obtain by choosing the activation order optimally.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [3,5,8], limit = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 1</code> as <code>limit[1] = 1</code></td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">8</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">8</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 0</code> as <code>limit[0] = 2</code></td> <td align="center" style="border: 1px solid black;">[1, 2]</td> <td align="center" style="border: 1px solid black;">16</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 16.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,2,6], limit = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">6</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 2</code> as <code>limit[j] = 1</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2]</td> <td align="center" style="border: 1px solid black;">6</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 6.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,1,5,2], limit = [3,3,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:​​​​​​​<strong>​​​​​​​</strong></p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[ ]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 2</code> as <code>limit[2] = 2</code></td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">9</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">10</td> </tr> <tr> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 3</code> as <code>limit[j] = 3</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2, 3]</td> <td align="center" style="border: 1px solid black;">12</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 12.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == value.length == limit.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= value[i] &lt;= 10<sup>5</sup></code>​​​​​​​</li> <li><code>1 &lt;= limit[i] &lt;= n</code></li> </ul>
Python
class Solution: def maxTotal(self, value: List[int], limit: List[int]) -> int: g = defaultdict(list) for v, lim in zip(value, limit): g[lim].append(v) ans = 0 for lim, vs in g.items(): vs.sort() ans += sum(vs[-lim:]) return ans
3,645
Maximum Total from Optimal Activation Order
Medium
<p>You are given two integer arrays <code>value</code> and <code>limit</code>, both of length <code>n</code>.</p> <p>Initially, all elements are <strong>inactive</strong>. You may activate them in any order.</p> <ul> <li>To activate an inactive element at index <code>i</code>, the number of <strong>currently</strong> active elements must be <strong>strictly less</strong> than <code>limit[i]</code>.</li> <li>When you activate the element at index <code>i</code>, it adds <code>value[i]</code> to the <strong>total</strong> activation value (i.e., the sum of <code>value[i]</code> for all elements that have undergone activation operations).</li> <li>After each activation, if the number of <strong>currently</strong> active elements becomes <code>x</code>, then <strong>all</strong> elements <code>j</code> with <code>limit[j] &lt;= x</code> become <strong>permanently</strong> inactive, even if they are already active.</li> </ul> <p>Return the <strong>maximum</strong> <strong>total</strong> you can obtain by choosing the activation order optimally.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [3,5,8], limit = [2,1,3]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 1</code> as <code>limit[1] = 1</code></td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[1]</td> <td align="center" style="border: 1px solid black;">8</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">8</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 0</code> as <code>limit[0] = 2</code></td> <td align="center" style="border: 1px solid black;">[1, 2]</td> <td align="center" style="border: 1px solid black;">16</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 16.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,2,6], limit = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:</p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">6</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 2</code> as <code>limit[j] = 1</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2]</td> <td align="center" style="border: 1px solid black;">6</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 6.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">value = [4,1,5,2], limit = [3,3,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>One optimal activation order is:​​​​​​​<strong>​​​​​​​</strong></p> <table style="border: 1px solid black;"> <thead> <tr> <th align="center" style="border: 1px solid black;">Step</th> <th align="center" style="border: 1px solid black;">Activated <code>i</code></th> <th align="center" style="border: 1px solid black;"><code>value[i]</code></th> <th align="center" style="border: 1px solid black;">Active Before <code>i</code></th> <th align="center" style="border: 1px solid black;">Active After <code>i</code></th> <th align="center" style="border: 1px solid black;">Becomes Inactive <code>j</code></th> <th align="center" style="border: 1px solid black;">Inactive Elements</th> <th align="center" style="border: 1px solid black;">Total</th> </tr> </thead> <tbody> <tr> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">5</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[ ]</td> <td align="center" style="border: 1px solid black;">5</td> </tr> <tr> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">0</td> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;"><code>j = 2</code> as <code>limit[2] = 2</code></td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">9</td> </tr> <tr> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">1</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">-</td> <td align="center" style="border: 1px solid black;">[2]</td> <td align="center" style="border: 1px solid black;">10</td> </tr> <tr> <td align="center" style="border: 1px solid black;">4</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">2</td> <td align="center" style="border: 1px solid black;">3</td> <td align="center" style="border: 1px solid black;"><code>j = 0, 1, 3</code> as <code>limit[j] = 3</code></td> <td align="center" style="border: 1px solid black;">[0, 1, 2, 3]</td> <td align="center" style="border: 1px solid black;">12</td> </tr> </tbody> </table> <p>Thus, the maximum possible total is 12.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == value.length == limit.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= value[i] &lt;= 10<sup>5</sup></code>​​​​​​​</li> <li><code>1 &lt;= limit[i] &lt;= n</code></li> </ul>
TypeScript
function maxTotal(value: number[], limit: number[]): number { const g = new Map<number, number[]>(); for (let i = 0; i < value.length; i++) { if (!g.has(limit[i])) { g.set(limit[i], []); } g.get(limit[i])!.push(value[i]); } let ans = 0; for (const [lim, vs] of g) { vs.sort((a, b) => b - a); ans += vs.slice(0, lim).reduce((acc, v) => acc + v, 0); } return ans; }
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
C++
class Solution { public: int maxWeight(vector<int>& weights, int w1, int w2) { vector<vector<int>> f(w1 + 1, vector<int>(w2 + 1)); for (int x : weights) { for (int j = w1; j >= 0; --j) { for (int k = w2; k >= 0; --k) { if (x <= j) { f[j][k] = max(f[j][k], f[j - x][k] + x); } if (x <= k) { f[j][k] = max(f[j][k], f[j][k - x] + x); } } } } return f[w1][w2]; } };
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
Go
func maxWeight(weights []int, w1 int, w2 int) int { f := make([][]int, w1+1) for i := range f { f[i] = make([]int, w2+1) } for _, x := range weights { for j := w1; j >= 0; j-- { for k := w2; k >= 0; k-- { if x <= j { f[j][k] = max(f[j][k], f[j-x][k]+x) } if x <= k { f[j][k] = max(f[j][k], f[j][k-x]+x) } } } } return f[w1][w2] }
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
Java
class Solution { public int maxWeight(int[] weights, int w1, int w2) { int[][] f = new int[w1 + 1][w2 + 1]; for (int x : weights) { for (int j = w1; j >= 0; --j) { for (int k = w2; k >= 0; --k) { if (x <= j) { f[j][k] = Math.max(f[j][k], f[j - x][k] + x); } if (x <= k) { f[j][k] = Math.max(f[j][k], f[j][k - x] + x); } } } } return f[w1][w2]; } }
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
Python
class Solution: def maxWeight(self, weights: List[int], w1: int, w2: int) -> int: f = [[0] * (w2 + 1) for _ in range(w1 + 1)] max = lambda a, b: a if a > b else b for x in weights: for j in range(w1, -1, -1): for k in range(w2, -1, -1): if x <= j: f[j][k] = max(f[j][k], f[j - x][k] + x) if x <= k: f[j][k] = max(f[j][k], f[j][k - x] + x) return f[w1][w2]
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
Rust
impl Solution { pub fn max_weight(weights: Vec<i32>, w1: i32, w2: i32) -> i32 { let w1 = w1 as usize; let w2 = w2 as usize; let mut f = vec![vec![0; w2 + 1]; w1 + 1]; for &x in &weights { let x = x as usize; for j in (0..=w1).rev() { for k in (0..=w2).rev() { if x <= j { f[j][k] = f[j][k].max(f[j - x][k] + x as i32); } if x <= k { f[j][k] = f[j][k].max(f[j][k - x] + x as i32); } } } } f[w1][w2] } }
3,647
Maximum Weight in Two Bags
Medium
<p>You are given an integer array <code>weights</code> and two integers <code>w1</code> and <code>w2</code> representing the <strong>maximum</strong> capacities of two bags.</p> <p>Each item may be placed in <strong>at most</strong> one bag such that:</p> <ul> <li>Bag 1 holds <strong>at most</strong> <code>w1</code> total weight.</li> <li>Bag 2 holds <strong>at most</strong> <code>w2</code> total weight.</li> </ul> <p>Return the <strong>maximum</strong> total weight that can be packed into the two bags.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [1,4,3,2], w1 = 5, w2 = 4</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[2] = 3</code> and <code>weights[3] = 2</code> as <code>3 + 2 = 5 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[1] = 4</code> as <code>4 &lt;= w2</code></li> <li>Total weight: <code>5 + 4 = 9</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [3,6,4,8], w1 = 9, w2 = 7</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Bag 1: Place <code>weights[3] = 8</code> as <code>8 &lt;= w1</code></li> <li>Bag 2: Place <code>weights[0] = 3</code> and <code>weights[2] = 4</code> as <code>3 + 4 = 7 &lt;= w2</code></li> <li>Total weight: <code>8 + 7 = 15</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">weights = [5,7], w1 = 2, w2 = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>No weight fits in either bag, thus the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= weights.length &lt;= 100</code></li> <li><code>1 &lt;= weights[i] &lt;= 100</code></li> <li><code>1 &lt;= w1, w2 &lt;= 300</code></li> </ul>
TypeScript
function maxWeight(weights: number[], w1: number, w2: number): number { const f: number[][] = Array.from({ length: w1 + 1 }, () => Array(w2 + 1).fill(0)); for (const x of weights) { for (let j = w1; j >= 0; j--) { for (let k = w2; k >= 0; k--) { if (x <= j) { f[j][k] = Math.max(f[j][k], f[j - x][k] + x); } if (x <= k) { f[j][k] = Math.max(f[j][k], f[j][k - x] + x); } } } } return f[w1][w2]; }