# My Leetcode Solution (Medium 2001 - 2500)
###### tags: `Other`
:::warning
[TOC]
:::
---
### []()
> ##### []()
> [color=#6CE26C]
```javascript=
```
---
### [2462. Total Cost to Hire K Workers](https://leetcode.com/problems/total-cost-to-hire-k-workers/)
> ##### [Runtime: 80% / Memory: 60%](https://leetcode.com/problems/total-cost-to-hire-k-workers/submissions/940121800/)
> [color=#6CE26C]
```javascript=
var totalCost = function(costs, k, candidates) {
let lIdx = candidates - 1;
let rIdx = costs.length - candidates;
let pq = new MinPriorityQueue({
compare: (a, b) => {
if ( a.val !== b.val ){
return a.val - b.val;
}
return a.idx - b.idx;
}
});
if ( lIdx < rIdx ){
for(let i=0; i<=lIdx; i++){
pq.enqueue({idx: i, val: costs[i]});
}
for(let i=rIdx; i<costs.length; i++){
pq.enqueue({idx: i, val: costs[i]});
}
} else {
for(let i=0; i<costs.length; i++){
pq.enqueue({idx: i, val: costs[i]});
}
}
let sum = 0;
while(k-- > 0){
let { idx, val } = pq.dequeue();
sum += val;
let nextIdx = (idx <= lIdx) ? ++lIdx : --rIdx;
if ( lIdx < rIdx ){
pq.enqueue({idx: nextIdx, val: costs[nextIdx]});
}
}
return sum;
};
```
---
### [2461. Maximum Sum of Distinct Subarrays With Length K](https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/)
> ##### [Runtime: 68.89% / Memory: 13.33%](https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/submissions/939945934/)
> [color=#6CE26C]
```javascript=
var maximumSubarraySum = function(nums, k) {
let map = new Map();
let max = 0;
let sum = 0;
let idx = 0;
while( idx+k-1 < nums.length ){
if ( idx === 0 ){
for ( let i=idx; i<=idx+k-1; i++ ){
map.set( nums[i], (map.get(nums[i]) || 0) + 1);
sum += nums[i];
}
} else {
if ( map.get( nums[idx-1] ) === 1 ){
map.delete( nums[idx-1] );
} else {
map.set( nums[idx-1], map.get(nums[idx-1]) - 1);
}
map.set( nums[idx+k-1], (map.get(nums[idx+k-1]) || 0) + 1);
sum -= nums[idx-1];
sum += nums[idx+k-1];
}
if ( map.size === k ){
max = Math.max(max, sum);
}
idx ++;
}
return max;
};
```
---
### [2457. Minimum Addition to Make Integer Beautiful](https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/)
> ##### [Runtime: 80.77% / Memory: 73.8%](https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/submissions/936917767/)
> [color=#6CE26C]
```javascript=
var makeIntegerBeautiful = function(n, target) {
for( let i=1; i<=10**12; i*=10 ){
let newN = Math.ceil(n/i) * i;
if ( String(newN).split('').reduce((acc, val) => +acc + +val ) <= target ){
return newN - n
}
}
};
```
---
### [2453. Destroy Sequential Targets](https://leetcode.com/problems/destroy-sequential-targets/)
> ##### [Runtime: 25% / Memory: 43.75%](https://leetcode.com/problems/destroy-sequential-targets/submissions/929598510/)
> [color=#6CE26C]
```javascript=
var destroyTargets = function(nums, space) {
let N = nums.sort((a,b)=>a-b)
let map = new Map()
for(let num of N){
let grp = num % space
if ( map.has(grp) ){
map.get(grp)[0] += 1
} else {
map.set(grp, [1, num])
}
}
let LM = [0, Infinity]
for (let [key, val] of map){
if (val[0] >= LM[0]){
LM[1] = val[0] > LM[0] ? val[1] : Math.min(val[1], LM[1])
LM[0] = val[0]
}
}
return LM[1]
};
```
---
### [2439. Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/)
> ##### [Runtime: 21.94% / Memory: 20.79%](https://leetcode.com/problems/minimize-maximum-of-array/submissions/936838202/)
> [color=#6CE26C]
```javascript=
var minimizeArrayValue = function(nums) {
let max = nums[0];
let sum = nums[0];
for (let i=1; i<nums.length; i++){
sum += nums[i];
max = Math.max( max, Math.ceil( sum / (1+i) ) );
}
return max;
};
```
---
### [2438. Range Product Queries of Powers](https://leetcode.com/problems/range-product-queries-of-powers/)
> ##### [Runtime: 66.67% / Memory: 33.33%](https://leetcode.com/problems/range-product-queries-of-powers/submissions/933542578/)
> [color=#6CE26C]
```javascript=
var productQueries = function(n, queries) {
let MOD = 10**9 + 7;
let powers = (n).toString(2).split('').reverse().map((e,i) => (e == 1) ? 2**i : 0 ).filter(e => e!= 0);
let resArr = [];
for (let [st, ed] of queries){
let res = 1
for( let i=st; i<=ed; i++ ){
res *= powers[i];
}
resArr.push( res % MOD );
}
return resArr;
};
```
---
### [2428. Maximum Sum of an Hourglass](https://leetcode.com/problems/maximum-sum-of-an-hourglass/)
> ##### [Runtime: 70.51% / Memory: 100%](https://leetcode.com/problems/maximum-sum-of-an-hourglass/submissions/875465034/)
> [color=#6CE26C]
```javascript=
var maxSum = function(grid) {
let max = 0
let row = 0
let col = 0
while ( grid?.[row+2]?.[col+2] !== undefined ){
let sum = grid[row+1][col+1]
for (let c=0; c<=2; c++){
sum += grid[row+0][col+c]
sum += grid[row+2][col+c]
}
max = Math.max( max, sum )
if (col + 2 === grid[0].length-1 ){
row ++
col = 0
} else {
col ++
}
}
return max
};
```
---
### [2420. Find All Good Indices](https://leetcode.com/problems/find-all-good-indices/)
> ##### [Runtime: 93.33% / Memory: 100%](https://leetcode.com/problems/find-all-good-indices/submissions/866283681/)
> [color=#6CE26C]
```javascript=
var goodIndices = function(nums, k) {
const len = nums.length
const left = Array(len).fill(1)
const right = Array(len).fill(1)
for( let i=1; i<len; i++ ){
if ( nums[i-1] >= nums[i] ){
left[i] += left[i-1]
}
}
for( let i=len-2; i>=0; i-- ){
if ( nums[i+1] >= nums[i] ){
right[i] += right[i+1]
}
}
const res = []
for( let i=k; i<len-k; i++ ){
if ( left[i-1] >= k && right[i+1] >= k ){
res.push(i)
}
}
return res
};
```
---
### [2419. Longest Subarray With Maximum Bitwise AND](https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/)
> ##### [Runtime: 100% / Memory: 37.50%](https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/submissions/875973948/)
> [color=#6CE26C]
```javascript=
var longestSubarray = function(nums) {
let max = Math.max(...nums)
let maxLen = 0
let cnt = 0
for ( let i=0; i<nums.length; i++ ){
cnt = ( nums[i] === max ) ? cnt + 1 : 0
maxLen = Math.max(maxLen, cnt)
}
return maxLen
};
```
---
### [2414. Length of the Longest Alphabetical Continuous Substring](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/)
> ##### [Runtime: 42.10% / Memory: 92.98%](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/submissions/858520226/)
> [color=#6CE26C]
```javascript=
var longestContinuousSubstring = function(s) {
let max = 1
let con = 1
let char = null
for ( let i=0; i<s.length; i++ ){
let newChar = s.charCodeAt(i)
if ( char + 1 === newChar ){
con += 1
max = Math.max( max, con )
} else {
con = 1
}
char = newChar
if ( max === 26 ){ return 26 }
}
return max
};
```
---
### [2405. Optimal Partition of String](https://leetcode.com/problems/optimal-partition-of-string/)
> ##### [Runtime: 74.22% / Memory: 86.63%](https://leetcode.com/problems/optimal-partition-of-string/submissions/820813236/)
> [color=#6CE26C]
```javascript=
var partitionString = function(s) {
let cnt = 1
let tmpArr = []
for ( let i=0; i<s.length; i++ ){
if ( tmpArr.indexOf( s[i] ) > -1 ){
cnt ++
tmpArr = []
}
tmpArr.push( s[i] )
}
return cnt
};
```
---
### [2401. Longest Nice Subarray](https://leetcode.com/problems/longest-nice-subarray/)
> ##### [Runtime: 58.13% / Memory: 54.68%](https://leetcode.com/problems/longest-nice-subarray/submissions/820772496/)
> [color=#6CE26C]
```javascript=
/**
* @param {number[]} nums
* @return {number}
*/
var longestNiceSubarray = function(nums) {
let stIdx = 0
let max = 1
for (let i=1; i<nums.length; i++){
let edIdx = i-1
for ( let j=edIdx; j>=stIdx; j-- ){
if ( (nums[j] & nums[i]) !== 0 ){
stIdx = j+1
break
}
}
max = Math.max( max, edIdx - stIdx + 1 + 1 ) // ( +1 +1 => +StartToEndLength +thisIndex )
}
return max
};
```
---
### [2400. Number of Ways to Reach a Position After Exactly k Steps](https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/)
> ##### [Runtime: 48.77% / Memory: 50.31%](https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/submissions/820796979/)
> [color=#6CE26C]
```javascript=
var numberOfWays = function(startPos, endPos, k) {
if ( Math.abs(endPos - startPos) % 2 !== k % 2 ){ return 0 }
let memo = {}
function run( nowPos, remainK ){
let key = nowPos + ',' + remainK
if ( key in memo ){ return memo[key] }
if ( remainK === 0 ){
memo[key] = (nowPos === endPos) ? 1 : 0
return memo[key]
}
if ( Math.abs(nowPos - endPos) > remainK ){
memo[key] = 0
return memo[key]
}
memo[key] = run( nowPos - 1, remainK - 1 ) + run( nowPos + 1, remainK - 1 )
return memo[key] % (10**9 + 7)
}
return run( startPos, k )
};
```
---
### [2397. Maximum Rows Covered by Columns](https://leetcode.com/problems/maximum-rows-covered-by-columns/)
> ##### [Runtime: 75.61% / Memory: 30.89%](https://leetcode.com/problems/maximum-rows-covered-by-columns/submissions/817245239/)
> [color=#6CE26C]
```javascript=
var maximumRows = function(matrix, numSelect) {
let rLen = matrix.length
let cLen = matrix[0].length
let colArr = Array( cLen ).fill(null)
for (let r=0; r<rLen; r++){
for (let c=0; c<cLen; c++){
if ( matrix[r][c] === 0 ){ continue }
if ( colArr[c] !== null ){
colArr[c].push(r)
} else {
colArr[c] = [r]
}
}
}
let max = 0
function chooseX ( lv, idx=0, willDel = [] ){
if ( lv === 0 ){
let newArr = [...colArr]
willDel.forEach( e => {
newArr[e] = null
})
let rowOnes = newArr.flat().filter( (e,i,a) => {
if ( e === null ){ return false }
return a.indexOf( e ) === i
})
max = Math.max( max, rLen - rowOnes.length )
return
}
for ( let i=idx; i<colArr.length; i++ ){
chooseX( lv-1, i+1, [...willDel, i ] )
}
return
}
chooseX ( numSelect )
return max
};
```
---
### [2391. Minimum Amount of Time to Collect Garbage](https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/)
> ###### [Runtime: 98.86% / Memory: 49.81%](https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/submissions/816512797/)
> [color=#6CE26C]
```javascript=
var garbageCollection = function(garbage, travel) {
let trucks = ['M','P','G']
let allGarbage = garbage.join('').length
let allTruckTraveled = 0
let traveled = travel.reduce((a,b)=>(a+b), 0)
for( let i=garbage.length-1; i>=1; i-- ){
if ( trucks.length === 0 ){ break; }
trucks = trucks.filter( e => {
if ( garbage[i].includes(e) ){
allTruckTraveled += traveled
return false
}
return true
})
traveled -= travel[i-1]
}
return allTruckTraveled + allGarbage
};
```
---
### [2390. Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/)
> ##### [Runtime: 63.83% / Memory: 61.87%](https://leetcode.com/problems/removing-stars-from-a-string/submissions/816550204/)
> [color=#6CE26C]
```javascript=
var removeStars = function(s) {
let arr = []
for (let i=0; i<s.length; i++ ){
if ( s[i] === '*' ){
arr.pop()
} else {
arr.push( s[i] )
}
}
return arr.join('')
};
```
---
### [2384. Largest Palindromic Number](https://leetcode.com/problems/largest-palindromic-number/)
> ###### [Runtime: 62.41% / Memory: 98.91%](https://leetcode.com/problems/largest-palindromic-number/submissions/816418674/)
> [color=#6CE26C]
```javascript=
var largestPalindromic = function(num) {
let numCnt = Array(10).fill(0)
let evenUse = Array(10).fill(0)
let oddMax = null
for( let i=0; i<num.length; i++ ){
numCnt[ num[i] ] += 1
}
for( let i=numCnt.length - 1; i>=0; i-- ){
if ( numCnt[i] === 0 ){ continue }
evenUse[i] = Math.floor( numCnt[i] / 2 )
if ( numCnt[i] % 2 === 1 && oddMax === null ){
oddMax = i
}
}
let biggerThen0 = evenUse.some( (e,i)=> e!==0 && i!==0 )
let resArr = (oddMax === null) ? [] : [ oddMax ]
if ( biggerThen0 === true ){
for( let i=0; i<evenUse.length; i++ ){
let str = String(i).repeat( evenUse[i] )
resArr.push( str )
resArr.unshift( str )
}
}
let res = resArr.join('')
return (res.length > 0) ? res : "0"
};
```
---
### [2375. Construct Smallest Number From DI String](https://leetcode.com/problems/construct-smallest-number-from-di-string/)
> ###### [Runtime: 80.70% / Memory: 56.76%](https://leetcode.com/problems/construct-smallest-number-from-di-string/submissions/805129383/)
> [color=#6CE26C]
```javascript=
var smallestNumber = function(pattern) {
let res = Array( pattern.length + 1 ).fill('')
let cntD = 0
let numI = 1
// input I
for( let i=0; i<res.length; i++ ){
if ( i === res.length-1 ){
res[i] = numI
break
}
if ( pattern[i] === 'D' ){
cntD ++
continue
}
if ( pattern[i] === 'I' ){
res[i] = numI
numI += 1 + cntD // next I
cntD = 0
}
}
// input D
for( let i=res.length-1; i >= 0; i-- ){
if ( res[i] !== '' ){ continue }
res[i] = res[i+1] + 1
}
return res.join('')
};
```
---
### [2374. Node With Highest Edge Score](https://leetcode.com/problems/node-with-highest-edge-score/)
> ###### [Runtime: 70.27% / Memory: 78.38%](https://leetcode.com/problems/node-with-highest-edge-score/submissions/805212879/)
> [color=#6CE26C]
```javascript=
var edgeScore = function(edges) {
let obj = {}
let maxKey = Infinity
let maxVal = 0
for (let i=0; i<edges.length; i++){
obj[edges[i]] = obj[edges[i]] ? obj[edges[i]] + i : i
if (( maxVal < obj[edges[i]] ) ||
( maxVal === obj[edges[i]] && maxKey > edges[i] ) ){
maxVal = obj[edges[i]]
maxKey = edges[i]
}
}
return maxKey
};
```
---
### [2370. Longest Ideal Subsequence](https://leetcode.com/problems/longest-ideal-subsequence/)
> ##### [Runtime: 100% / Memory: 83.33%](https://leetcode.com/problems/longest-ideal-subsequence/submissions/805199093/)
> [color=#6CE26C]
```javascript=
var longestIdealString = function(s, k) {
let alph = Array(26).fill(0)
for ( let a of s ){
let ai = a.charCodeAt() - 97
let max = 0
let st = ai-k >= 0 ? ai-k : 0
let ed = ai+k <= 25 ? ai+k : 25
for ( let i=st; i<=ed; i++ ){
max = Math.max( max, alph[i] )
}
alph[ai] = max + 1
}
return Math.max( ...alph )
};
```
---
### [2369. Check if There is a Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/)
Runtime: 123 ms, faster than 81.55% of JavaScript online submissions for Check if There is a Valid Partition For The Array.
Memory Usage: 59.4 MB, less than 59.22% of JavaScript online submissions for Check if There is a Valid Partition For The Array.
```javascript=
var validPartition = function(nums) {
let nowNums = [-1]
while ( nowNums.length > 0 ){
let tmpNums = []
nowNums.forEach( v => {
if ( nums[v+2] && nums[v+1] === nums[v+2] ){
tmpNums.push( v+2 )
}
if ( nums[v+3] ){
if ((nums[v+1] === nums[v+2] && nums[v+2] === nums[v+3]) ||
(nums[v+1] + 1 === nums[v+2] && nums[v+2] + 1 === nums[v+3] )){
tmpNums.push( v+3 )
}
}
})
if ( tmpNums.indexOf( nums.length-1 ) > -1 ){ return true }
nowNums = [...new Set(tmpNums)]
if ( nowNums.length > 2 || ( nowNums[1] && nowNums[0] + 2 < nowNums[1] ) ){
nowNums.sort((a,b)=>a-b)
nowNums.shift()
}
}
return false
};
```
---
### [2368. Reachable Nodes With Restrictions](https://leetcode.com/problems/reachable-nodes-with-restrictions/)
Runtime: 614 ms, faster than 68.65% of JavaScript online submissions for Reachable Nodes With Restrictions.
Memory Usage: 136.8 MB, less than 57.54% of JavaScript online submissions for Reachable Nodes With Restrictions.
```javascript=
var reachableNodes = function(n, edges, restricted) {
let maps = Array.from( {length: n}, (e)=>[] )
edges.forEach( ([v0, v1]) => {
maps[v1].push(v0)
maps[v0].push(v1)
})
restricted.forEach( (v) => {
maps[v] = null
})
let cnt = 1
goNextNode(0)
function goNextNode( idx ){
let nodes = maps[idx]
maps[idx] = null
cnt += nodes.length
nodes.forEach( (num) => {
if ( maps[num] === null ){
cnt --
return
}
goNextNode( num )
})
}
return cnt
};
```
---
### [2365. Task Scheduler II](https://leetcode.com/problems/task-scheduler-ii/)
Runtime: 273 ms, faster than 28.39% of JavaScript online submissions for Task Scheduler II.
Memory Usage: 59.9 MB, less than 50.62% of JavaScript online submissions for Task Scheduler II.
```javascript=
var taskSchedulerII = function(tasks, space) {
let reTaskDay = {}
let day = 0
tasks.forEach( (val)=>{
day ++
if ( reTaskDay[val] && day < reTaskDay[val] ){
day = reTaskDay[val];
}
reTaskDay[val] = day + space + 1
})
return day
};
```
---
### [2364. Count Number of Bad Pairs](https://leetcode.com/problems/count-number-of-bad-pairs/)
Runtime: 175 ms, faster than 83.87% of JavaScript online submissions for Count Number of Bad Pairs.
Memory Usage: 68.5 MB, less than 51.61% of JavaScript online submissions for Count Number of Bad Pairs.
```javascript=
var countBadPairs = function(nums) {
let map = new Map()
for (let i = 0; i < nums.length; i++) {
const height = nums[i] - i
map.set(height, (map.get(height)||0) + 1 )
}
// C4取2
// => (4*3) / (2*1)
// => (nums.length * (nums.length-1)) / 2
let totalPairs = (nums.length * (nums.length-1)) / 2
let goodPairs = 0
for (let [key,val] of map ) {
goodPairs += (val * (val-1)) / 2
}
return totalPairs - goodPairs
};
```
---
### [2358. Maximum Number of Groups Entering a Competition](https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/)
Runtime: 105 ms, faster than 72.80% of JavaScript online submissions for Maximum Number of Groups Entering a Competition.
Memory Usage: 49.5 MB, less than 92.00% of JavaScript online submissions for Maximum Number of Groups Entering a Competition.
```javascript=
var maximumGroups = function(grades) {
// 1+2+3....+x = grades.length
// => (1+x)x/2 = L ( 下+上*高/2 )
// => x²+x-L*2 = 0 ( 一元二次: aX²+bX+c=0 )
// -1+√1+4*L*2 ┌ -b+√b²-4ac ┐
// => x = ----------- │ X = ---------- │
// 2 └ 2a ┘
return Math.floor( (-1 + Math.sqrt( 1+8*grades.length ) ) / 2 )
};
```
---
### [2353. Design a Food Rating System](https://leetcode.com/problems/design-a-food-rating-system/)
Runtime: 4420 ms, faster than 25.39% of JavaScript online submissions for Design a Food Rating System.
Memory Usage: 87.1 MB, less than 85.39% of JavaScript online submissions for Design a Food Rating System.
```javascript=
var FoodRatings = function(foods, cuisines, ratings) {
this.data = [
// { food, cuisine, rating }
]
this.map = {
// cuisine: {
// dataIdx: [ 1,4,8... ],
// maxIdx: 4,
// }
}
for ( let i=0; i<foods.length; i++){
this.data.push({
food: foods[i],
cuisine: cuisines[i],
rating: ratings[i]
})
if ( this.map[ cuisines[i] ] ){
let mpC = this.map[ cuisines[i] ]
if ( ratings[i] > this.data[mpC.maxIdx].rating ||
( ratings[i] === this.data[mpC.maxIdx].rating && foods[i][0] < this.data[mpC.maxIdx].food[0] )
){
mpC.maxIdx = i
}
this.map[ cuisines[i] ].dataIdx.push(i)
} else {
this.map[ cuisines[i] ] = {
"dataIdx": [i],
"maxIdx": i,
}
}
}
};
FoodRatings.prototype.changeRating = function(food, newRating) {
let dIdx = this.data.findIndex( e => e.food === food )
this.data[dIdx].rating = newRating
let data = this.data
let cuisine = data[dIdx].cuisine
let mpC = this.map[cuisine]
function findMax( idx ){
if ((data[idx].rating > data[mpC.maxIdx].rating) ||
(data[idx].rating === data[mpC.maxIdx].rating && data[idx].food[0] < data[mpC.maxIdx].food[0]) ){
mpC.maxIdx = idx
}
}
if ( dIdx === mpC.maxIdx ){
this.map[ cuisine ].dataIdx.forEach( num => {
findMax( num )
})
return null
}
findMax( dIdx )
};
FoodRatings.prototype.highestRated = function(cuisine) {
return this.data[ this.map[cuisine].maxIdx ].food
};
```
---
### [2352. Equal Row and Column Pairs](https://leetcode.com/problems/equal-row-and-column-pairs/)
Runtime: 295 ms, faster than 17.20% of JavaScript online submissions for Equal Row and Column Pairs.
Memory Usage: 56.1 MB, less than 29.94% of JavaScript online submissions for Equal Row and Column Pairs.
```javascript=
var equalPairs = function(grid) {
let rowMap = new Map()
let colMap = new Map()
grid.forEach( e => {
if ( rowMap.has(String(e)) ){
rowMap.set( String(e), rowMap.get(String(e)) + 1 )
} else {
rowMap.set( String(e), 1 )
}
})
for ( let row=0; row<grid.length; row++ ){
let c = []
for( let col=0; col<grid.length; col++ ){
c.push(grid[col][row])
}
if ( colMap.has(String(c)) ){
colMap.set( String(c), colMap.get(String(c)) + 1 )
} else {
colMap.set( String(c), 1 )
}
}
let cnt = 0
for ( let [key,val] of rowMap ){
if ( colMap.has(key) ){
cnt += colMap.get(key) * val
}
}
return cnt
};
```
---
### [2349. Design a Number Container System](https://leetcode.com/problems/design-a-number-container-system/)
Runtime: 1884 ms, faster than 17.68% of JavaScript online submissions for Design a Number Container System.
Memory Usage: 112.4 MB, less than 17.01% of JavaScript online submissions for Design a Number Container System.
```javascript=
var NumberContainers = function() {
this.idx_num = {
// '1': 10,
// '2': 20,
}
this.num_idx = {
// 10: [1]
// 20: [2]
}
};
NumberContainers.prototype.change = function(index, number) {
let oldNum = this.idx_num[index]
// (1) 更新 num_idx
// 刪除舊的
if ( oldNum ){
let idx = this.num_idx[oldNum].findIndex( e => e === index )
this.num_idx[oldNum].splice(idx, 1)
if ( idx === 0 && this.num_idx[oldNum].length >= 2 ){
this.num_idx[oldNum].sort((a,b)=>a-b)
}
}
// 新增新的
if ( this.num_idx[number] ){
if ( this.num_idx[number][0] < index ){
this.num_idx[number].push( index )
} else {
this.num_idx[number].unshift( index )
}
} else {
this.num_idx[number] = [ index ]
}
// (2) 更新 idx_num
this.idx_num[index] = number
};
NumberContainers.prototype.find = function(number) {
return this.num_idx[number] ? this.num_idx[number][0] || -1 : -1
};
```
---
### [2348. Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/)
Runtime: 114 ms, faster than 84.23% of JavaScript online submissions for Number of Zero-Filled Subarrays.
Memory Usage: 53.5 MB, less than 63.06% of JavaScript online submissions for Number of Zero-Filled Subarrays.
```javascript=
var zeroFilledSubarray = function(nums) {
let n = 0
let sum = 0
nums.forEach( e => {
n = e === 0 ? n+1 : 0
sum += n
})
return sum
};
```
---
### [2342. Max Sum of a Pair With Equal Sum of Digits](https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/)
Runtime: 507 ms, faster than 30.46% of JavaScript online submissions for Max Sum of a Pair With Equal Sum of Digits.
Memory Usage: 68 MB, less than 33.11% of JavaScript online submissions for Max Sum of a Pair With Equal Sum of Digits.
```javascript=
var maximumSum = function(nums) {
let map = new Map()
for (let i=0; i<nums.length; i++){
let sum = 0
for (let s=0; s<String(nums[i]).length; s++){
sum += +String(nums[i])[s]
}
if ( map.has(sum) ){
map.get(sum).push(nums[i])
} else {
map.set(sum, [nums[i]])
}
}
let max = -1
for (let [key,arr] of map){
if ( arr.length >= 2 ){
arr.sort( (a,b) => b-a )
max = Math.max( max, arr[0]+arr[1] )
}
}
return max
};
```
---
### [2337. Move Pieces to Obtain a String](https://leetcode.com/problems/move-pieces-to-obtain-a-string/)
Runtime: 134 ms, faster than 76.60% of JavaScript online submissions for Move Pieces to Obtain a String.
Memory Usage: 47.2 MB, less than 93.62% of JavaScript online submissions for Move Pieces to Obtain a String.
```javascript=
var canChange = function(start, target) {
let tL=0
let sR=0
for (let i=0; i<start.length; i++){
if ( start[i] === 'R' ){ sR++ }
if ( target[i] === 'L' ){ tL++ }
if ( start[i] === 'R' && tL > 0 ){ return false }
if ( target[i] === 'L' && sR > 0 ){ return false }
if ( target[i] === 'R' && sR <= 0 ){ return false }
if ( start[i] === 'L' && tL <= 0 ){ return false }
if ( target[i] === 'R' ){ sR-- }
if ( start[i] === 'L' ){ tL-- }
}
if ( tL != 0 || sR != 0 ){ return false }
return true
};
```
---
### [2336. Smallest Number in Infinite Set](https://leetcode.com/problems/smallest-number-in-infinite-set/)
Runtime: 343 ms, faster than 37.88% of JavaScript online submissions for Smallest Number in Infinite Set.
Memory Usage: 49.9 MB, less than 62.88% of JavaScript online submissions for Smallest Number in Infinite Set.
```javascript=
var SmallestInfiniteSet = function() {
let set = new Set()
this.set = set
for (let i=1; i<=1000; i++){
this.set.add(i)
}
};
SmallestInfiniteSet.prototype.popSmallest = function() {
let min = Math.min( ...Array.from(this.set) )
this.set.delete(min)
return min
};
SmallestInfiniteSet.prototype.addBack = function(num) {
this.set.add(num)
};
```
---
### [2333. Minimum Sum of Squared Difference](https://leetcode.com/problems/minimum-sum-of-squared-difference/)
Runtime: 241 ms, faster than 78.00% of JavaScript online submissions for Minimum Sum of Squared Difference.
Memory Usage: 66.6 MB, less than 46.00% of JavaScript online submissions for Minimum Sum of Squared Difference.
```javascript=
var minSumSquareDiff = function(nums1, nums2, k1, k2) {
let k = k1 + k2
let len = nums1.length
let nums = Array(len)
for (let i=0; i<len; i++ ){
nums[i] = Math.abs( nums1[i] - nums2[i] )
}
nums.sort((a,b)=>b-a)
let subs = Array(len)
for (let i=0; i<len; i++ ){
let next = nums[i+1] ? nums[i+1] : 0
subs[i] = ( nums[i] - next ) * (i+1)
}
let kCnt = k
let subIdx = 0
let kIsBigger = false
for (let i=0; i<len; i++){
subIdx = i
if ( kCnt - subs[i] >= 0 ){
kCnt -= subs[i]
if ( i === len - 1 ){
kIsBigger = true
}
} else {
kCnt = subs[i] - kCnt
break
}
}
if ( kIsBigger ){ return 0 }
let baseIdx = subIdx + 1
let preAdd = Math.floor( kCnt / baseIdx )
let preExAdd = kCnt % baseIdx
let baseNum = nums[baseIdx] ? nums[baseIdx] : 0
let preNum = baseNum + preAdd
let preSum = preNum**2 * ( baseIdx - preExAdd )
let endSum = (preNum+1)**2 * preExAdd
let leftSum = 0
if ( baseIdx !== len ){
nums.splice( 0, baseIdx )
leftSum = nums.reduce( (acc, val)=>{
return acc + (val ** 2)
}, 0)
}
return preSum + endSum + leftSum
};
```
---
### [2332. The Latest Time to Catch a Bus](https://leetcode.com/problems/the-latest-time-to-catch-a-bus/)
Runtime: 286 ms, faster than 70.27% of JavaScript online submissions for The Latest Time to Catch a Bus.
Memory Usage: 75.6 MB, less than 22.97% of JavaScript online submissions for The Latest Time to Catch a Bus.
```javascript=
var latestTimeCatchTheBus = function(buses, passengers, capacity) {
buses.sort((a,b)=>a-b)
passengers.sort((a,b)=>a-b)
let inBus = Array( buses.length ).fill(null).map( e => [] )
let pStart = 0
for (let b=0; b<buses.length; b++){
for (let p=pStart; p<passengers.length; p++){
if ( passengers[p] <= buses[b] && inBus[b].length < capacity ){
inBus[b].push( passengers[p] )
pStart ++
} else {
break
}
}
}
const lastInBus = inBus[inBus.length-1] // 最後一車乘客們 [...]
const lastBusNum = buses[buses.length-1] // 最後一車底線號碼 num
const lastInBusPs = lastInBus[lastInBus.length-1] // 最後一車乘客號碼 num
let useArray = null
let uselastNum = null
if ( lastInBus.length === capacity ){ // 最後一車客滿
useArray = inBus.flat()
uselastNum = lastInBusPs
} else {
useArray = passengers
uselastNum = lastBusNum
}
while ( true ){
if ( useArray.indexOf(uselastNum) > -1 ){
uselastNum --
} else {
return uselastNum
}
}
};
```
---
### [2327. Number of People Aware of a Secret](https://leetcode.com/problems/number-of-people-aware-of-a-secret/)
Runtime: 185 ms, faster than 34.96% of JavaScript online submissions for Number of People Aware of a Secret.
Memory Usage: 43.8 MB, less than 71.54% of JavaScript online submissions for Number of People Aware of a Secret.
```javascript=
var peopleAwareOfSecret = function(n, delay, forget) {
let mod = 10**9 + 7
let secret = [ [1+delay, 1+forget, 1] ]
for (let day=1; day<=n; day++){
// share
for (let s=0; s<secret.length; s++){
if ( secret[s][0] <= day && day < secret[s][1] ){
if ( secret[secret.length-1][0] === day+delay ){
secret[secret.length-1][2] += secret[s][2] % mod
} else {
secret.push( [ day+delay, day+forget, secret[s][2] % mod ] )
}
}
}
// forget
if ( secret[0][1] === day ){
secret.shift()
}
}
let res = secret.reduce( (acc,val) => acc + val[2], 0)
return res % mod
};
```
---
### [2295. Replace Elements in an Array](https://leetcode.com/problems/replace-elements-in-an-array/)
Runtime: 340 ms, faster than 87.41% of JavaScript online submissions for Replace Elements in an Array.
Memory Usage: 94.1 MB, less than 64.53% of JavaScript online submissions for Replace Elements in an Array.
```javascript=
var arrayChange = function(nums, operations) {
let map = new Map()
nums.forEach((e,i)=>{
map.set(e,i)
})
for (let i=0; i<operations.length; i++){
let idx = map.get( operations[i][0] )
nums[idx] = operations[i][1]
map.delete( operations[i][0] )
map.set( operations[i][1] , idx )
}
return nums
};
```
---
### [2285. Maximum Total Importance of Roads](https://leetcode.com/problems/maximum-total-importance-of-roads/)
Runtime: 380 ms, faster than 49.62% of JavaScript online submissions for Maximum Total Importance of Roads.
Memory Usage: 80.8 MB, less than 51.54% of JavaScript online submissions for Maximum Total Importance of Roads.
```javascript=
var maximumImportance = function(n, roads) {
let map = new Map()
for (let i=0; i<roads.length; i++){
let oVal0 = map.get(roads[i][0])
map.set(roads[i][0], oVal0 === undefined ? 1 : oVal0 + 1 )
let oVal1 = map.get(roads[i][1])
map.set(roads[i][1], oVal1 === undefined ? 1 : oVal1 + 1 )
}
let mapArr = [...map].sort( (a,b)=> b[1] - a[1] )
let impMap = new Map()
for( let i=0; i<mapArr.length; i++ ){
impMap.set( mapArr[i][0], n )
n--
}
let cnt = 0
for (let i=0; i<roads.length; i++){
cnt += impMap.get(roads[i][0]) + impMap.get(roads[i][1])
}
return cnt
};
```
---
### [2284. Sender With Largest Word Count](https://leetcode.com/problems/sender-with-largest-word-count/)
Runtime: 230 ms, faster than 69.70% of JavaScript online submissions for Sender With Largest Word Count.
Memory Usage: 70.4 MB, less than 20.30% of JavaScript online submissions for Sender With Largest Word Count.
```javascript=
var largestWordCount = function(messages, senders) {
let map = new Map()
for (let i=0; i<messages.length; i++){
let msgLen = messages[i].split(' ').length
let oVal = map.get(senders[i])
map.set(senders[i], oVal === undefined ? msgLen : oVal + msgLen )
}
let maxVal = 0
let maxKey = null
for ( let [key,val] of map ){
if ( val > maxVal ){
maxKey = key
maxVal = val
} else if ( val === maxVal ){
maxKey = [key, maxKey].sort()[1]
}
}
return maxKey
};
```
---
### [2280. Minimum Lines to Represent a Line Chart](https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/)
Runtime: 406 ms, faster than 60.00% of JavaScript online submissions for Minimum Lines to Represent a Line Chart.
Memory Usage: 87.7 MB, less than 58.95% of JavaScript online submissions for Minimum Lines to Represent a Line Chart.
```javascript=
var minimumLines = function(stockPrices) {
function gcd(a, b) {
return b == 0 ? a : gcd(b, a % b)
}
stockPrices.sort((a,b)=>a[0]-b[0])
let pre0 = stockPrices[0][0]
let pre1 = stockPrices[0][1]
let preS = null
let cnt = 0
for ( let i=1; i<stockPrices.length; i++ ){
let d0 = stockPrices[i][0] - pre0
let d1 = stockPrices[i][1] - pre1
let g = gcd( d0, d1 )
let s = (d0/g) + '|' + (d1/g)
if ( preS !== s ){
cnt ++
}
preS = s
pre0 = stockPrices[i][0]
pre1 = stockPrices[i][1]
}
return cnt
};
```
---
### [2279. Maximum Bags With Full Capacity of Rocks](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/)
Runtime: 235 ms, faster than 56.90% of JavaScript online submissions for Maximum Bags With Full Capacity of Rocks.
Memory Usage: 54.5 MB, less than 95.98% of JavaScript online submissions for Maximum Bags With Full Capacity of Rocks.
```javascript=
var maximumBags = function(capacity, rocks, additionalRocks) {
let remainRock = additionalRocks
for (let i=0; i<capacity.length; i++){
capacity[i] -= rocks[i]
}
capacity.sort( (a,b)=> a-b )
let res = 0
for (let i=0; i<capacity.length; i++){
if ( remainRock >= capacity[i] ){
remainRock -= capacity[i]
capacity[i] = 0
}
if ( capacity[i] === 0 ){
res ++
}
}
return res
};
```
---
### [2274. Maximum Consecutive Floors Without Special Floors](https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/)
Runtime: 239 ms, faster than 92.07% of JavaScript online submissions for Maximum Consecutive Floors Without Special Floors.
Memory Usage: 54.4 MB, less than 71.95% of JavaScript online submissions for Maximum Consecutive Floors Without Special Floors.
```javascript=
var maxConsecutive = function(bottom, top, special) {
special.sort( (a,b) => a-b )
let max = -1
max = Math.max(special[0] - bottom, max)
for( let i=1; i<special.length; i++ ){
max = Math.max(special[i] - special[i-1] - 1, max)
}
max = Math.max(top - special[special.length-1], max)
return max
};
```
---
### [2271. Maximum White Tiles Covered by a Carpet](https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/)
Runtime: 397 ms, faster than 25.97% of JavaScript online submissions for Maximum White Tiles Covered by a Carpet.
Memory Usage: 71.4 MB, less than 25.41% of JavaScript online submissions for Maximum White Tiles Covered by a Carpet.
```javascript=
var maximumWhiteTiles = function(tiles, carpetLen) {
tiles.sort( (a,b)=> a[0] - b[0] )
tiles = tiles.map( (v) => {
return {
start: v[0],
end: v[1],
total: v[1] - v[0] + 1
}
})
let max = 0
let floorEnd = 0
let preCnt = 0
let preStartCnt = 0
let preEndCnt = 0
for ( let i=0; i<tiles.length; i++ ){
let endPos = tiles[i].start + carpetLen - 1
let cnt = 0
if ( i > 0 && preCnt - preStartCnt - preEndCnt > 0 ){
cnt = preCnt - preStartCnt - preEndCnt
}
floorEnd = floorEnd > i ? floorEnd : i
for ( let j = floorEnd; j < tiles.length; j++ ){
if ( endPos >= tiles[j].start ){
floorEnd = j
let coverEndFloor = tiles[j].total
if ( endPos < tiles[j].end ){ // 比地板短
coverEndFloor -= tiles[j].end - endPos
}
cnt += coverEndFloor
preEndCnt = coverEndFloor
if ( endPos < tiles[j].end ){ break }
if ( endPos > tiles[j].end && j === tiles.length - 1 ){ break }
}
}
max = Math.max( cnt, max )
if ( max === carpetLen ){ break }
preCnt = cnt
preStartCnt = tiles[i].total
}
return max
};
```
---
### [2270. Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/)
Runtime: 93 ms, faster than 100.00% of JavaScript online submissions for Number of Ways to Split Array.
Memory Usage: 54.9 MB, less than 61.36% of JavaScript online submissions for Number of Ways to Split Array.
```javascript=
var waysToSplitArray = function(nums) {
let left = 0
let right = nums.reduce((acc,val)=> acc + val)
let cnt = 0
for (let i=0; i<nums.length-1; i++){
left += nums[i]
right -= nums[i]
if (left >= right){
cnt ++
}
}
return cnt
};
```
---
### [2261. K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/)
Runtime: 774 ms, faster than 86.61% of JavaScript online submissions for K Divisible Elements Subarrays.
Memory Usage: 65.9 MB, less than 79.46% of JavaScript online submissions for K Divisible Elements Subarrays.
```javascript=
var countDistinct = function(nums, k, p) {
let set = new Set()
for (let i=0; i<nums.length; i++ ){
let str = ''
let times = k
for ( let j=i; j<nums.length; j++ ){
if ( nums[j] % p === 0 ){
times --
}
if ( times < 0 ){
break
}
str += nums[j] + '.'
set.add( str )
}
}
return set.size
};
```
---
### [2260. Minimum Consecutive Cards to Pick Up](https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/)
Runtime: 182 ms, faster than 90.17% of JavaScript online submissions for Minimum Consecutive Cards to Pick Up.
Memory Usage: 75.6 MB, less than 89.60% of JavaScript online submissions for Minimum Consecutive Cards to Pick Up.
```javascript=
var minimumCardPickup = function(cards) {
if ( cards.length === 1 ){ return -1 }
let min = Infinity
let map = new Map()
for( let i=0; i<cards.length; i++ ){
if ( map.has( cards[i] ) ){
let idx = map.get( cards[i] )
min = Math.min( min, i-idx+1 )
}
map.set( cards[i], i )
}
min = min === Infinity ? -1 : min
return min
};
```
---
### [2257. Count Unguarded Cells in the Grid](https://leetcode.com/problems/count-unguarded-cells-in-the-grid/)
Runtime: 402 ms, faster than 89.80% of JavaScript online submissions for Count Unguarded Cells in the Grid.
Memory Usage: 102.6 MB, less than 53.06% of JavaScript online submissions for Count Unguarded Cells in the Grid.
```javascript=
var countUnguarded = function(m, n, guards, walls) {
let map = Array(m).fill().map( col => Array(n).fill('0') )
let safeZone = m * n - guards.length - walls.length
guards.forEach( pos => {
map[pos[0]][pos[1]] = 'G'
})
walls.forEach( pos => {
map[pos[0]][pos[1]] = 'W'
})
for( let x=0; x<m; x++ ){ // 左右
let pW = -1
let pG = false
for( let y=0; y<n; y++ ){
if ( map[x][y] === '0' ){
if ( pG === true ){
safeZone --
map[x][y] = '1'
}
}
if ( map[x][y] === 'G' ){
if ( pG === false ){
for ( let back = y-1; back > pW; back-- ){
if ( map[x][back] === '0' ){
safeZone --
map[x][back] = '1'
}
}
pG = true
}
}
if ( map[x][y] === 'W' ){
pW = y
pG = false
}
}
}
for( let y=0; y<n; y++ ){ // 上下
let pW = -1
let pG = false
for( let x=0; x<m; x++ ){
if ( map[x][y] === '0' ){
if ( pG === true ){
safeZone --
map[x][y] = '1'
}
}
if ( map[x][y] === 'G' ){
if ( pG === false ){
for ( let back = x-1; back > pW; back-- ){
if ( map[back][y] === '0' ){
safeZone --
map[back][y] = '1'
}
}
pG = true
}
}
if ( map[x][y] === 'W' ){
pW = x
pG = false
}
}
}
return safeZone
};
```
---
### [2256. Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/)
Runtime: 87 ms, faster than 96.32% of JavaScript online submissions for Minimum Average Difference.
Memory Usage: 52.7 MB, less than 82.35% of JavaScript online submissions for Minimum Average Difference.
```javascript=
var minimumAverageDifference = function(nums) {
let nLen = nums.length
let minIdx = null
let minVal = Infinity
let sum = nums.reduce( (acc,val) => {
return acc + val
}, 0)
let left = 0
let right = sum
for( let i=0; i<nLen; i++ ){
left += nums[i]
right -= nums[i]
let L = Math.floor( left / (i+1) )
let R = ( nLen-i-1 === 0 ) ? 0 : Math.floor( right / (nLen-i-1) )
let res = Math.abs( L - R )
if ( res < minVal ){
minIdx = i
minVal = res
}
}
return minIdx
};
```
---
### [2250. Count Number of Rectangles Containing Each Point](https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/)
Runtime: 493 ms, faster than 89.74% of JavaScript online submissions for Count Number of Rectangles Containing Each Point.
Memory Usage: 67.6 MB, less than 97.44% of JavaScript online submissions for Count Number of Rectangles Containing Each Point.
```javascript=
var countRectangles = function(rectangles, points) {
let heights = Array(101).fill().map( e => [] )
rectangles.forEach( e => {
heights[e[1]].push( e[0] )
})
heights.forEach( e => {
e.sort((a,b)=>a-b)
})
let res = []
points.forEach( point => {
let cnt = 0
for( let h=point[1]; h<101; h++ ){
cnt += heights[h].length - binarySearch( heights[h], point[0] )
}
res.push( cnt )
})
return res
function binarySearch( widths, point ){
let min = 0
let max = widths.length
while ( min < max ) {
let mid = Math.floor((min + max) / 2)
if (widths[mid] >= point) {
max = mid
} else {
min = mid + 1
}
}
return min
}
};
```
---
### [2245. Maximum Trailing Zeros in a Cornered Path](https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/)
Runtime: 2483 ms, faster than 25.92% of JavaScript online submissions for Maximum Trailing Zeros in a Cornered Path.
Memory Usage: 123 MB, less than 59.26% of JavaScript online submissions for Maximum Trailing Zeros in a Cornered Path.
:::danger
:poop: 題目太爛
:::
---
### [2244. Minimum Rounds to Complete All Tasks](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/)
Runtime: 145 ms, faster than 78.26% of JavaScript online submissions for Minimum Rounds to Complete All Tasks.
Memory Usage: 61 MB, less than 39.61% of JavaScript online submissions for Minimum Rounds to Complete All Tasks.
```javascript=
var minimumRounds = function(tasks) {
let map = new Map()
tasks.forEach((e,i)=>{
if ( !map.get(e) ){
map.set(e,1)
} else {
map.set(e,map.get(e) + 1 )
}
})
let res = 0
for( let [key,val] of map ){
if ( val === 1 ){ return -1; }
res += Math.ceil(val / 3)
}
return res
};
```
---
### [2241. Design an ATM Machine](https://leetcode.com/problems/design-an-atm-machine/)
Runtime: 293 ms, faster than 98.32% of JavaScript online submissions for Design an ATM Machine.
Memory Usage: 55.1 MB, less than 65.55% of JavaScript online submissions for Design an ATM Machine.
```javascript=
var ATM = function() {
this.money = [20,50,100,200,500]
this.count = [0,0,0,0,0]
}
ATM.prototype.deposit = function(banknotesCount) {
for ( let i=0; i<this.money.length; i++ ){
this.count[i] += banknotesCount[i]
}
}
ATM.prototype.withdraw = function(amount) {
let resArr = [0,0,0,0,0]
for (let i=resArr.length-1; i>=0; i--){
if ( amount >= this.money[i] ){
let total = Math.min( this.count[i], Math.floor( amount / this.money[i] ) )
resArr[i] += total
amount -= total * this.money[i]
}
if ( amount === 0 ){
for (let j=0; j<resArr.length; j++){
this.count[j] -= resArr[j]
}
return resArr
}
}
return [-1]
}
```
---
### [2240. Number of Ways to Buy Pens and Pencils](https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/)
Runtime: 83 ms, faster than 75.17% of JavaScript online submissions for Number of Ways to Buy Pens and Pencils.
Memory Usage: 42 MB, less than 69.80% of JavaScript online submissions for Number of Ways to Buy Pens and Pencils.
```javascript=
var waysToBuyPensPencils = function(total, cost1, cost2) {
let times = Math.floor(total / cost1)
let res = 0
for( let i=0; i<=times; i++ ){
let remain = total - ( i * cost1 )
res += Math.floor(remain / cost2) + 1
}
return res
};
```
---
### [2233. Maximum Product After K Increments](https://leetcode.com/problems/maximum-product-after-k-increments/)
:::info
sort後填補最小值 (水位填補低處)
:::
Runtime: 282 ms, faster than 81.40% of JavaScript online submissions for Maximum Product After K Increments.
Memory Usage: 57.3 MB, less than 74.42% of JavaScript online submissions for Maximum Product After K Increments.
```javascript=
var maximumProduct = function(nums, k) {
nums.sort((a,b)=>a-b)
let remain = k
while ( remain > 0 ){
let width = nums.length
let height = Infinity
for ( let i=1; i<nums.length; i++ ){
if ( nums[0] !== nums[i] ){
width = i
height = nums[i] - nums[0]
break;
}
}
if ( remain >= width * height ){
for ( let w=0; w<width; w++ ){
nums[w] = nums[width]
}
remain -= width * height
} else {
let reHei = Math.floor(remain / width)
let reAdd1 = remain % width
for ( let w=0; w<width; w++ ){
if ( w < width - reAdd1 ){
nums[w] += reHei
} else {
nums[w] += reHei + 1
}
}
remain = 0
}
}
let res = nums.reduce( (acc, val) => {
return acc * val % (10**9 + 7)
})
return res
};
```
---
### [2232. Minimize Result by Adding Parentheses to Expression](https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/)
Runtime: 70 ms, faster than 83.52% of JavaScript online submissions for Minimize Result by Adding Parentheses to Expression.
Memory Usage: 44 MB, less than 28.57% of JavaScript online submissions for Minimize Result by Adding Parentheses to Expression.
```javascript=
var minimizeResult = function(expression) {
let sp = expression.split('+')
let strL = sp[0]
let strR = sp[1]
let min = Infinity
let minStr = ''
for( let L=0; L<strL.length; L++ ){
for( let R=0; R<strR.length; R++ ){
let mL = (L===0) ? '':'*'
let mR = (R===strR.length-1) ? '':'*'
let sumL = strL.substring(0,L) + mL + '(' + strL.substring(L)
let sumR = strR.substring(0,R+1) + ')' + mR + strR.substring(R+1)
let sumStr = sumL + '+' + sumR
let sum = eval( sumStr )
if ( sum < min ){
min = sum
minStr = sumStr.split('*').join('')
}
}
}
return minStr
};
```
---
### [2226. Maximum Candies Allocated to K Children](https://leetcode.com/problems/maximum-candies-allocated-to-k-children/)
Runtime: 315 ms, faster than 19.68% of JavaScript online submissions for Maximum Candies Allocated to K Children.
Memory Usage: 57.9 MB, less than 34.15% of JavaScript online submissions for Maximum Candies Allocated to K Children.
```javascript=
var maximumCandies = function(candies, k) {
let max = Math.max(...candies)
let min = 0
while ( min !== max-1 ) {
let guess = Math.floor( (max + min) / 2 )
let k0 = candies.reduce( (acc,val) => {
return acc + Math.floor(val / guess)
},0)
if ( k0 < k ){
max = guess
} else if ( k0 >= k ) {
min = guess
}
}
let kmax = candies.reduce( (acc,val) => {
return acc + Math.floor(val / max)
},0)
return kmax >= k ? max : min
};
```
---
### [2225. Find Players With Zero or One Losses](https://leetcode.com/problems/find-players-with-zero-or-one-losses/)
Runtime: 472 ms, faster than 87.81% of JavaScript online submissions for Find Players With Zero or One Losses.
Memory Usage: 98.6 MB, less than 75.96% of JavaScript online submissions for Find Players With Zero or One Losses.
```javascript=
var findWinners = function(matches) {
let Lost0 = new Set()
let Lost1 = new Set()
let Lost2 = new Set()
matches.forEach( (val)=>{
let win = val[0]
let lost = val[1]
if ( Lost2.has( lost ) ){
// do_nothing
} else if ( Lost1.has( lost ) ){
Lost1.delete( lost )
Lost2.add( lost )
} else if ( Lost0.has( lost ) ){
Lost0.delete( lost )
Lost1.add( lost )
} else {
Lost1.add( lost )
}
if ( Lost2.has( win ) || Lost1.has( win ) || Lost0.has( win ) ){
// do_nothing
} else {
Lost0.add(win)
}
})
return [ [...Lost0].sort((a,b)=>a-b), [...Lost1].sort((a,b)=>a-b) ]
};
```
---
### [2222. Number of Ways to Select Buildings](https://leetcode.com/problems/number-of-ways-to-select-buildings/)
Runtime: 189 ms, faster than 65.12% of JavaScript online submissions for Number of Ways to Select Buildings.
Memory Usage: 52.8 MB, less than 61.24% of JavaScript online submissions for Number of Ways to Select Buildings.
```javascript=
var numberOfWays = function(s) {
let firstNum = s.substring(0,1)
let amount0 = 0
let amount1 = 0
for ( let i=0; i<s.length; i++ ){
if ( s.charAt(i) === '0' ){ amount0 ++ }
if ( s.charAt(i) === '1' ){ amount1 ++ }
}
function count( midNum ){
let sum = 0
let last0 = amount0
let last1 = amount1
let prevS = firstNum
let startAt0 = firstNum === midNum ? 2 : 1
for( let i=0; i<s.length; i++){
if ( last0 === 0 || last1 === 0 ){ break }
if ( s.charAt(i) === '0' ){ last0 -- }
if ( s.charAt(i) === '1' ){ last1 -- }
if ( i === 0 ) { continue }
if ( startAt0 !== 0 ) {
if ( s.charAt(i) === prevS ){
continue
} else {
startAt0 --
prevS = s.charAt(i)
}
}
if ( startAt0 === 0 && s.charAt(i) === midNum ){
sum += midNum === '1' ?
( amount0 - last0 ) * last0 :
( amount1 - last1 ) * last1
}
}
return sum
}
return count('0') + count('1')
};
```
---
### [2221. Find Triangular Sum of an Array](https://leetcode.com/problems/find-triangular-sum-of-an-array/)
Runtime: 116 ms, faster than 95.73% of JavaScript online submissions for Find Triangular Sum of an Array.
Memory Usage: 43.5 MB, less than 100.00% of JavaScript online submissions for Find Triangular Sum of an Array.
```javascript=
var triangularSum = function(nums) {
while ( nums.length > 1 ){
for ( let i=0; i<nums.length; i++ ){
if ( i===nums.length - 1 ){
nums.pop()
break
}
let sum = nums[i] + nums[i+1]
sum = sum >= 10 ? sum-10 : sum
nums[i] = sum
}
}
return nums[0]
};
```
---
### [2217. Find Palindrome With Fixed Length](https://leetcode.com/problems/find-palindrome-with-fixed-length/)
Runtime: 370 ms, faster than 58.79% of JavaScript online submissions for Find Palindrome With Fixed Length.
Memory Usage: 66.9 MB, less than 84.85% of JavaScript online submissions for Find Palindrome With Fixed Length.
```javascript=
var kthPalindrome = function(queries, intLength) {
let L = Math.ceil(intLength / 2)
let Start1 = Math.pow(10,L-1)
let res = queries.map( e => {
if ( e-1 >= Math.pow(10,L) - Start1 ){
return -1
}
let str = String( e-1 + Start1 )
if ( intLength % 2 == 0 ){ // even
str = str + str.split('').reverse().join('')
} else { // odd
str = str + str.substring(0,str.length-1).split('').reverse().join('')
}
return +str
})
return res
};
```
---
### [2216. Minimum Deletions to Make Array Beautiful](https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/)
Runtime: 115 ms, faster than 68.80% of JavaScript online submissions for Minimum Deletions to Make Array Beautiful.
Memory Usage: 52.8 MB, less than 65.41% of JavaScript online submissions for Minimum Deletions to Make Array Beautiful.
```javascript=
var minDeletion = function(nums) {
let cnt = 0
let i = 0
while ( i<nums.length ){
let Continue = true
let next = 0
while ( Continue && (i-cnt)%2===0 ) {
if ( nums[i+1+next] !== undefined && nums[i] === nums[i+1+next] ){
next ++
} else {
Continue = false
}
}
cnt += next
i = i+1+next
}
if ( (nums.length - cnt) % 2 === 1 ){
cnt += 1
}
return cnt
};
```
---
### [2212. Maximum Points in an Archery Competition](https://leetcode.com/problems/maximum-points-in-an-archery-competition/)
Runtime: 105 ms, faster than 79.17% of JavaScript online submissions for Maximum Points in an Archery Competition.
Memory Usage: 48.3 MB, less than 47.22% of JavaScript online submissions for Maximum Points in an Archery Competition.
```javascript=
var maximumBobPoints = function(numArrows, aliceArrows) {
let maxPoint = 0
let aArrows = aliceArrows.map(e=>e+1)
let maxBobArrows
function BobShoot( idx, arrow, point, bobArrows ){
if ( idx === aArrows.length || arrow === 0 ) { // stop condition
if ( point > maxPoint ){
maxPoint = point
maxBobArrows = [...bobArrows] // [deepClone]
maxBobArrows[0] += arrow // all left arrow shot on [0]
}
return false
}
BobShoot( idx+1, arrow, point, bobArrows ) // no shot
if ( arrow >= aArrows[idx] ){ // enough arrow to get point
let newBobArrows = [...bobArrows] // [deepClone]
newBobArrows[idx] = aArrows[idx]
BobShoot( idx+1, arrow - aArrows[idx], point + idx, newBobArrows ) // shot
}
}
BobShoot( 0, numArrows, 0, Array(aArrows.length).fill(0) )
return maxBobArrows
};
```
---
### [2211. Count Collisions on a Road](https://leetcode.com/problems/count-collisions-on-a-road/)
Runtime: 171 ms, faster than 47.81% of JavaScript online submissions for Count Collisions on a Road.
Memory Usage: 47 MB, less than 71.71% of JavaScript online submissions for Count Collisions on a Road.
```javascript=
var countCollisions = function(directions) {
let res = 0
let collide = false
for ( let i=0; i<directions.length; i++ ){
if ( i == directions.length.length-1 ){ break }
if ( directions[i+1] == 'L' ){
switch ( directions[i] ){
case 'R':
res += 2
collide = true
break;
case 'S':
res += 1
collide = true
break;
case 'L':
if ( collide ) res += 1
break;
default:
break;
}
} else {
collide = false
}
}
for ( let i=directions.length-1; i>=0; i-- ){
if ( i === 0 ){ break }
if ( directions[i-1] === 'R' ){
switch ( directions[i] ){
case 'L':
// res += 2 // already added
collide = true
break;
case 'S':
res += 1
collide = true
break;
case 'R':
if ( collide ) res += 1
break;
default:
break;
}
} else {
collide = false
}
}
return res
};
```
---
### [2207. Maximize Number of Subsequences in a String](https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/)
Runtime: 165 ms, faster than 63.08% of JavaScript online submissions for Maximize Number of Subsequences in a String.
Memory Usage: 51 MB, less than 53.08% of JavaScript online submissions for Maximize Number of Subsequences in a String.
```javascript=
var maximumSubsequenceCount = function(text, pattern) {
let p0 = pattern.substring(0,1)
let p1 = pattern.substring(1,2)
let p0Cnt = 0
let p1Cnt = 0
let res = 0
if ( p0 !== p1 ){
text.split('').forEach((e,i)=>{
if ( e.indexOf(p0) > -1 ){
p0Cnt ++
} else if ( e.indexOf(p1) > -1 ){
p1Cnt ++
res += p0Cnt
}
})
return res + Math.max( p0Cnt, p1Cnt )
}
if ( p0 === p1 ){
res = text.split('').reduce((acc,e,i)=>{
if ( e.indexOf(p0) > -1 ){
p0Cnt ++
return acc + (p0Cnt-1)
} else {
return acc
}
}, 0)
return res + p0Cnt
}
};
```
---
### [2202. Maximize the Topmost Element After K Moves](https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/)
Runtime: 76 ms, faster than 95.07% of JavaScript online submissions for Maximize the Topmost Element After K Moves.
Memory Usage: 52.5 MB, less than 63.55% of JavaScript online submissions for Maximize the Topmost Element After K Moves.
```javascript=
var maximumTop = function(nums, k) {
if ( k === 0 ) return nums[0]
if ( nums.length === 1 ){
if ( k % 2 === 0 ) return nums[0]
if ( k % 2 === 1 ) return -1
}
let arr = nums
if ( nums.length >= k ){
arr = nums.slice( 0, k-1 )
if ( nums.length > k ){
arr.push( nums[k] )
}
}
return Math.max(...arr)
};
```
---
### [2196. Create Binary Tree From Descriptions](https://leetcode.com/problems/create-binary-tree-from-descriptions/)
Runtime: 468 ms, faster than 87.94% of JavaScript online submissions for Create Binary Tree From Descriptions.
Memory Usage: 88.7 MB, less than 38.19% of JavaScript online submissions for Create Binary Tree From Descriptions.
```javascript=
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
var createBinaryTree = function(descriptions) {
let nodes = new Map()
let children = new Set()
for (let [parent, child, isLeft] of descriptions) {
let parentNode = nodes.get(parent) || new TreeNode(parent)
if (!nodes.has(parent)){
nodes.set(parent, parentNode)
}
let childNode = nodes.get(child) || new TreeNode(child)
if (!nodes.has(child)){
nodes.set(child, childNode)
}
if (isLeft===1) {
parentNode.left = childNode;
} else {
parentNode.right = childNode;
}
children.add(child)
}
children.forEach( (val,key) => {
nodes.delete(key)
})
let res = null
nodes.forEach( e => {
res = e
})
return res
};
```
---
### [2195. Append K Integers With Minimal Sum](https://leetcode.com/problems/append-k-integers-with-minimal-sum/)
Runtime: 230 ms, faster than 66.07% of JavaScript online submissions for Append K Integers With Minimal Sum.
Memory Usage: 67.8 MB, less than 32.14% of JavaScript online submissions for Append K Integers With Minimal Sum.
```javascript=
var minimalKSum = function(nums, k) {
let arr = Array.from( new Set(nums) )
arr.sort((a,b)=>a-b)
let sum = 0
function sumM( sm, lg ){
let h = lg - sm - 1
if ( k < h ){ // 若高不夠
lg = sm + k + 1
h = k
}
sum += (lg + sm) * h / 2 // 上底+下底*高/2
k -= h
}
for( i=0; i<arr.length+1; i++ ){
if ( k === 0 ){ break }
if ( i === 0 ){
sumM( 0, arr[i] )
} else if ( arr[i] && arr[i-1] ){
sumM( arr[i-1], arr[i] )
} else if ( arr[i] === undefined ) {
sumM( arr[arr.length-1], Infinity )
}
}
return sum
};
```
---
### [2191. Sort the Jumbled Numbers](https://leetcode.com/problems/sort-the-jumbled-numbers/)
Runtime: 777 ms, faster than 74.58% of JavaScript online submissions for Sort the Jumbled Numbers.
Memory Usage: 70.6 MB, less than 83.28% of JavaScript online submissions for Sort the Jumbled Numbers.
```javascript=
var sortJumbled = function(mapping, nums) {
let twoArr = nums.map( item => {
let newItem = item.toString().split('').map( n => mapping[n] ).join('')
return [ item, +newItem ]
})
return twoArr.sort((a, b) => a[1]-b[1]).flatMap( item => item[0] )
};
```
---
### [2187. Minimum Time to Complete Trips](https://leetcode.com/problems/minimum-time-to-complete-trips/)
Runtime: 194 ms, faster than 73.76% of JavaScript online submissions for Minimum Time to Complete Trips.
Memory Usage: 55.1 MB, less than 53.96% of JavaScript online submissions for Minimum Time to Complete Trips.
```javascript=
var minimumTime = function(time, totalTrips) {
let minBusTime = Math.min( ...time )
let maxTime = minBusTime * totalTrips
let minTime = minBusTime * Math.ceil(totalTrips / time.length)
function tryTrip(){
let guessTime = Math.floor( (minTime + maxTime) / 2 )
if ( minTime === maxTime ) {
resTime = guessTime
return
}
let sumTrip = 0
for (i=0; i<time.length; i++){
sumTrip += Math.floor( guessTime / time[i] )
}
if ( minTime+1 === maxTime ){ // 因guessTime取小值 = minTime
resTime = sumTrip >= totalTrips ? guessTime : guessTime+1
return
}
if ( sumTrip >= totalTrips ){
maxTime = guessTime
} else if ( sumTrip < totalTrips ){
minTime = guessTime
}
tryTrip()
}
tryTrip()
return resTime
};
```
---
### [2186. Minimum Number of Steps to Make Two Strings Anagram II](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/)
Runtime: 156 ms, faster than 83.91% of JavaScript online submissions for Minimum Number of Steps to Make Two Strings Anagram II.
Memory Usage: 52.9 MB, less than 93.39% of JavaScript online submissions for Minimum Number of Steps to Make Two Strings Anagram II.
```javascript=
var minSteps = function(s, t) {
let sArr = new Array(26).fill(0)
let tArr = new Array(26).fill(0)
for ( i=0; i<s.length; i++){
sArr[s.charCodeAt(i) - 97] ++
}
for ( i=0; i<t.length; i++){
tArr[t.charCodeAt(i) - 97] ++
}
let sum = 0
sArr.forEach( (e,i) => {
sum += Math.abs(e - tArr[i])
})
return sum
};
```
---
### [2182. Construct String With Repeat Limit](https://leetcode.com/problems/construct-string-with-repeat-limit/)
Runtime: 108 ms, faster than 98.94% of JavaScript online submissions for Construct String With Repeat Limit.
Memory Usage: 51.5 MB, less than 90.96% of JavaScript online submissions for Construct String With Repeat Limit.
```javascript=
var repeatLimitedString = function(s, repeatLimit) {
let sArr = new Array(26).fill(0)
let charA = 97
for ( i=0; i<s.length; i++){
sArr[s.charCodeAt(i) - charA] ++
}
let str = ''
let prevI = null
let meIns = false
while( sArr.length > 0 ){
for (let i = sArr.length-1; i >= 0; i--) {
if ( sArr[i] === 0 ){
if ( i === sArr.length-1 ){
sArr.pop()
}
continue
}
if ( meIns ) { // 插入值階段
if ( prevI === i ){
sArr[i] = 0
break
}
sArr[i] --
str += String.fromCharCode(charA + i)
meIns = false
break
}
let sub = sArr[i] - repeatLimit
if ( sub >= 0 ){
sArr[i] -= repeatLimit
str += String.fromCharCode(charA + i).repeat( repeatLimit )
if ( sub === 0 ) { break }
// 將進入插入值階段
meIns = true
prevI = i
} else {
str += String.fromCharCode(charA + i).repeat( sArr[i] )
sArr[i] = 0
break
}
}
}
return str
};
```
---
### [2178. Maximum Split of Positive Even Integers](https://leetcode.com/problems/maximum-split-of-positive-even-integers/)
Runtime: 350 ms, faster than 79.72% of JavaScript online submissions for Maximum Split of Positive Even Integers.
Memory Usage: 73.4 MB, less than 93.87% of JavaScript online submissions for Maximum Split of Positive Even Integers.
```javascript=
var maximumEvenSplit = function(finalSum) {
let num2 = 2
let res = []
if ( finalSum % 2 === 1 ) { return res }
let sum = finalSum
while ( sum > 0 ){
if ( sum - num2 < 0 ){
res[res.length-1] += sum
break
} else if ( sum - num2 >= 0 ){
res.push( num2 )
sum = sum - num2
}
num2 += 2
}
return res
};
```
---
### [2177. Find Three Consecutive Integers That Sum to a Given Number](https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/)
Runtime: 55 ms, faster than 99.11% of JavaScript online submissions for Find Three Consecutive Integers That Sum to a Given Number.
Memory Usage: 42.6 MB, less than 21.66% of JavaScript online submissions for Find Three Consecutive Integers That Sum to a Given Number.
:::success
:poop: 題目太簡單
:::
```javascript=
var sumOfThree = function(num) {
if ( num % 3 === 0 ) {
return [ num/3-1, num/3, num/3+1 ]
} else {
return []
}
};
```
---
### [2171. Removing Minimum Number of Magic Beans](https://leetcode.com/problems/removing-minimum-number-of-magic-beans/)
Runtime: 337 ms, faster than 71.43% of JavaScript online submissions for Removing Minimum Number of Magic Beans.
Memory Usage: 58.9 MB, less than 35.71% of JavaScript online submissions for Removing Minimum Number of Magic Beans.
```javascript=
var minimumRemoval = function(beans) {
beans.sort((a,b)=>a-b)
let total = beans.reduce((a,v)=>a+v)
let num = null
let min = Infinity
for( let i=0; i<beans.length; i++ ){
if ( num !== beans[i] ){
num = beans[i]
let numSum = num * ( beans.length - i )
min = Math.min( min, total - numSum )
}
}
return min
};
```
---
### [2170. Minimum Operations to Make the Array Alternating](https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/)
Runtime: 187 ms, faster than 99.44% of JavaScript online submissions for Minimum Operations to Make the Array Alternating.
Memory Usage: 78.5 MB, less than 61.80% of JavaScript online submissions for Minimum Operations to Make the Array Alternating.
```javascript=
var minimumOperations = function(nums) {
let odd = new Map()
let even = new Map()
for( let i=0; i<nums.length; i++ ){
let map = i % 2 === 0 ? even : odd
let cnt = map.get( nums[i] )
if ( cnt ){
map.set( nums[i], cnt+1 )
} else {
map.set( nums[i], 1 )
}
}
let oddMax = findMax('odd')
let evenMax = findMax('even')
if ( oddMax[0] === evenMax[0] ){
odd.delete( oddMax[0] )
even.delete( evenMax[0] )
let oddMax2 = findMax('odd')
let evenMax2 = findMax('even')
if ( oddMax2[1] + evenMax[1] > oddMax[1] + evenMax2[1] ){
return nums.length - ( oddMax2[1] + evenMax[1] )
} else {
return nums.length - ( oddMax[1] + evenMax2[1] )
}
} else {
return nums.length - ( oddMax[1] + evenMax[1] )
}
function findMax( oddEven ){
let map = oddEven === 'even' ? even : odd
let max = [0,0]
for ( let e of map ){
if ( e[1] > max[1] ){
max = e
}
}
return max
}
};
```
---
### [2166. Design Bitset](https://leetcode.com/problems/design-bitset/)
Runtime: 805 ms, faster than 82.35% of JavaScript online submissions for Design Bitset.
Memory Usage: 83.9 MB, less than 100.00% of JavaScript online submissions for Design Bitset.
```javascript=
class Bitset {
constructor( size ){
this.size = size
this.arr = Array(size).fill('0')
this.s0 = size
this.s1 = 0
this.flip1 = false
}
fix(idx){
if ( !this.flip1 ){
if ( this.arr[idx] === '0' ){
this.arr.splice( idx, 1, '1' )
this.s0 --
this.s1 ++
}
} else {
if ( this.arr[idx] === '1' ){
this.arr.splice( idx, 1, '0' )
this.s0 --
this.s1 ++
}
}
}
unfix(idx){
if ( !this.flip1 ){
if ( this.arr[idx] === '1' ){
this.arr.splice( idx, 1, '0' )
this.s0 ++
this.s1 --
}
} else {
if ( this.arr[idx] === '0' ){
this.arr.splice( idx, 1, '1' )
this.s0 ++
this.s1 --
}
}
}
flip(){
this.flip1 = !this.flip1
let tmp_s0 = this.s0
this.s0 = this.s1
this.s1 = tmp_s0
}
all(){
return this.s1 == this.size
}
one(){
return this.s1 > 0
}
count(){
return this.s1
}
toString(){
let Arr = this.arr
if ( this.flip1 ){
Arr = Arr.map( e => e === '1' ? '0' : '1' )
}
return Arr.join('')
}
}
```
---
### [2165. Smallest Value of the Rearranged Number](https://leetcode.com/problems/smallest-value-of-the-rearranged-number/)
Runtime: 58 ms, faster than 96.00% of JavaScript online submissions for Smallest Value of the Rearranged Number.
Memory Usage: 44 MB, less than 56.00% of JavaScript online submissions for Smallest Value of the Rearranged Number.
```javascript=
var smallestNumber = function(num) {
let negtive = false
if ( String(num).slice(0,1) === '-' ){
negtive = true
num = String(num).slice(1)
} else {
num = String(num)
}
if ( negtive ){
let arr = String(num).split('').sort((a,b)=>b-a)
return Number(arr.join('')) * -1
} else {
let arr = String(num).split('').sort((a,b)=>a-b)
let idx = arr.findIndex( e => e !== '0' )
if ( idx === -1 ){ // all 0
return 0
} else if ( idx === 0 ) { // no 0
return arr.join('')
} else {
let firstNum = arr[idx]
arr.splice(idx,1)
arr.unshift( firstNum )
return arr.join('')
}
}
};
```
---
### [2161. Partition Array According to Given Pivot](https://leetcode.com/problems/partition-array-according-to-given-pivot/)
Runtime: 366 ms, faster than 77.93% of JavaScript online submissions for Partition Array According to Given Pivot.
Memory Usage: 81.1 MB, less than 68.54% of JavaScript online submissions for Partition Array According to Given Pivot.
```javascript=
var pivotArray = function(nums, pivot) {
let left = []
let mid = []
let right = []
nums.forEach( e => {
if ( e < pivot ){
left.push( e )
} else if ( e > pivot ){
right.push( e )
} else {
mid.push( e )
}
})
return [ ...left, ...mid, ...right ]
};
```
---
### [2155. All Divisions With the Highest Score of a Binary Array](https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/)
Runtime: 351 ms, faster than 89.80% of JavaScript online submissions for All Divisions With the Highest Score of a Binary Array.
Memory Usage: 75.3 MB, less than 93.88% of JavaScript online submissions for All Divisions With the Highest Score of a Binary Array.
```javascript=
var maxScoreIndices = function(nums) {
let n0 = 0
let n1 = 0
nums.forEach( e => {
if ( e === 1 ){
n1 ++
}
})
let max = n1 // division at -0
let maxArr = [0]
for ( let i=0; i<nums.length; i++ ){
if ( nums[i] === 0 ){
n0 ++
} else {
n1 --
}
if ( n0 + n1 > max ){
max = n0 + n1
maxArr = [i+1]
} else if ( n0 + n1 === max ){
max = n0 + n1
maxArr.push( i+1 )
}
}
return maxArr
};
```
---
### [2150. Find All Lonely Numbers in the Array](https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/)
Runtime: 349 ms, faster than 93.26% of JavaScript online submissions for Find All Lonely Numbers in the Array.
Memory Usage: 70.5 MB, less than 97.75% of JavaScript online submissions for Find All Lonely Numbers in the Array.
```javascript=
var findLonely = function(nums) {
nums.sort((a,b)=>a-b)
let res = []
let prev = null
for( let i=0; i<nums.length; i++ ){
let prevLonely = true
let nextLonely = true
if ( i !== 0 ) { // match prev
if ( prev === nums[i] || prev === nums[i]-1 ){
prevLonely = false
}
}
if ( i !== nums.length-1 ){ // match next
if ( nums[i] === nums[i+1] || nums[i] === nums[i+1]-1 ){
nextLonely = false
}
}
if ( prevLonely && nextLonely ){
res.push( nums[i] )
}
prev = nums[i]
}
return res
};
```
---
### [2149. Rearrange Array Elements by Sign](https://leetcode.com/problems/rearrange-array-elements-by-sign/)
Runtime: 375 ms, faster than 85.51% of JavaScript online submissions for Rearrange Array Elements by Sign.
Memory Usage: 88.5 MB, less than 94.35% of JavaScript online submissions for Rearrange Array Elements by Sign.
```javascript=
var rearrangeArray = function(nums) {
let res = Array(nums.length)
let posCnt = 0
let negCnt = 1
nums.forEach( e => {
if ( e >= 0 ){
res[ posCnt ] = e
posCnt += 2
} else {
res[ negCnt ] = e
negCnt += 2
}
})
return res
};
```
---
### [2146. K Highest Ranked Items Within a Price Range](https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/)
Runtime: 1057 ms, faster than 66.67% of JavaScript online submissions for K Highest Ranked Items Within a Price Range.
Memory Usage: 158.3 MB, less than 40.00% of JavaScript online submissions for K Highest Ranked Items Within a Price Range.
```javascript=
var highestRankedKItems = function(grid, pricing, start, k) {
let startPrice = grid[start[0]][start[1]]
let dis = 0
let steps = k
let resArr = []
if ( startPrice >= pricing[0] && startPrice <= pricing[1] ){
resArr = [start]
steps -= 1
}
grid[start[0]][start[1]] = 0
let willMoveArr = [ start ]
while ( steps > 0 && willMoveArr.length > 0 ){
let newMoveArr = [] // [row, col]
let newResArr = [] // [row, col, price]
willMoveArr.forEach( rc => {
[[-1,0],[+1,0],[0,-1],[0,+1]].forEach( (d, i) => { // move 4 times [ up, down, left, right ]
let move = [ rc[0] + d[0], rc[1] + d[1] ]
if ( grid[move[0]] === undefined || grid[move[0]][move[1]] === undefined ) { return } // out of boundary
let price = grid[move[0]][move[1]]
if ( price === 0 ) { return } // wall
if ( price >= pricing[0] && price <= pricing[1] ){
steps -= 1
newResArr.push( [ ...move, price ] )
}
newMoveArr.push( move )
grid[move[0]][move[1]] = 0 // path will be a wall
})
})
if ( newResArr[0] ){
newResArr.sort( (a,b) => { return a[2] - b[2] || a[0] - b[0] || a[1] - b[1] })
newResArr.forEach( e => e.pop() )
resArr.push( ...newResArr )
}
dis ++
willMoveArr = newMoveArr
}
if ( steps < 0 ){
resArr.splice( resArr.length + steps, -steps )
}
return resArr
};
```
---
### [2140. Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/)
Runtime: 225 ms, faster than 79.41% of JavaScript online submissions for Solving Questions With Brainpower.
Memory Usage: 77.2 MB, less than 97.06% of JavaScript online submissions for Solving Questions With Brainpower.
```javascript=
var mostPoints = function(questions) {
let tmpPoint = Array(questions.length).fill(0)
for( let i=questions.length-1; i>=0; i--){
let point = questions[i][0]
let power = questions[i][1]
let skip = tmpPoint[i+1] || 0
let slove = point + (tmpPoint[ i + 1 + power] || 0)
tmpPoint[i] = Math.max( skip, slove )
}
return tmpPoint[0]
};
```
### [2139. Minimum Moves to Reach Target Score](https://leetcode.com/problems/minimum-moves-to-reach-target-score/)
Runtime: 66 ms, faster than 81.52% of JavaScript online submissions for Minimum Moves to Reach Target Score.
Memory Usage: 42.1 MB, less than 59.78% of JavaScript online submissions for Minimum Moves to Reach Target Score.
```javascript=
var minMoves = function(target, maxDoubles) {
let path = target
let cnt = 0
while( path !== 1 ){
if ( maxDoubles !== 0 ){
maxDoubles --
if ( path % 2 === 0 ){
path = path / 2
cnt += 1
} else {
path = (path - 1) / 2
cnt += 2
}
continue
} else {
cnt += path - 1
break
}
}
return cnt
};
```
---
### [2134. Minimum Swaps to Group All 1's Together II](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/)
Runtime: 112 ms, faster than 60.00% of JavaScript online submissions for Minimum Swaps to Group All 1's Together II.
Memory Usage: 50.9 MB, less than 48.57% of JavaScript online submissions for Minimum Swaps to Group All 1's Together II.
```javascript=
var minSwaps = function(nums) {
let min = Infinity
let num_1 = 0
for( let i=0; i<nums.length; i++ ){
if ( nums[i] === 1 ){ num_1++ }
}
let count0 = 0
for( let i=0; i<num_1; i++ ){ // 111110000
if ( nums[i] === 0 ){ count0 ++ }
}
min = Math.min(min,count0)
for( let i=1; i<=nums.length; i++ ){
if ( nums[i-1] === 0 ) count0 -= 1
let last = i + num_1 - 1
if ( nums[last] === undefined ) last -= nums.length
if ( nums[last] === 0 ) count0 += 1
min = Math.min(min,count0)
}
return min
};
```
---
### [2131. Longest Palindrome by Concatenating Two Letter Words](https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/)
Runtime: 176 ms, faster than 86.11% of JavaScript online submissions for Longest Palindrome by Concatenating Two Letter Words.
Memory Usage: 54.1 MB, less than 100.00% of JavaScript online submissions for Longest Palindrome by Concatenating Two Letter Words.
```javascript=
var longestPalindrome = function(words) {
let map = new Map()
words.forEach( val => {
if ( map.has(val) ){
map.set( val, map.get(val) + 1 )
} else {
map.set( val, 1 )
}
})
let sameCnt = 0
let sideCnt = 0
let noSide = true
let mid = true
for( let [str, cnt] of map ){
if ( cnt >= 2 ){ noSide = false }
if ( str[0] === str[1] ){
if ( cnt % 2 === 1 ){
if ( mid ){
mid = false
} else {
cnt -= 1
}
}
sameCnt += cnt * 2
} else {
noSide = false
let reStr = str.split('').reverse().join('')
if ( map.has(reStr) ){
sideCnt += Math.min( map.get(reStr), map.get(str) ) * 4
map.delete( reStr )
}
}
}
return ( noSide && sameCnt > 0 ) ? 2 : sideCnt + sameCnt
};
```