Created
June 18, 2024 18:45
-
-
Save AllanJeremy/9e0ce984ab52d5f3dca50b9960be0722 to your computer and use it in GitHub Desktop.
Leetcode [Hard] 1363. Largest Multiple of Three
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function largestMultipleOfThree(digits: number[]): string { | |
// Digits sorted in ascending order | |
const digitsAsc = [...digits].sort((a, b) => a - b); | |
// Sorting the digits in descending order 9,8,7... | |
const digitsDesc = [...digits].sort((a, b) => b - a); // [8,7,6,1,0] | |
let sum = digits.reduce((prev, curr) => prev + curr, 0); | |
let remainder = sum % 3; | |
let result = digitsDesc; | |
if (remainder === 0 && sum !== 0) return digitsDesc.join(""); | |
const REMAINDER_OF_1 = [1, 4, 7]; | |
const REMAINDER_OF_2 = [2, 5, 8]; | |
let indexToRemove: number; | |
function handleRemovalIfResultContains(arr: number[]) { | |
for (const d of arr) { | |
if (result.includes(d)) { | |
indexToRemove = result.indexOf(d); | |
sum -= d; | |
break; | |
} | |
} | |
} | |
const NUMS_REMAINDER_IS_1 = [2, 4, 7]; | |
const NUMS_REMAINDER_IS_2 = [1, 5, 8]; | |
for (let i = 0; i < digits.length; i++) { | |
const digit = digitsAsc[i]; | |
if (digit === 0) continue; | |
else if (remainder === 0) break; | |
if (result.includes(remainder)) { | |
indexToRemove = result.indexOf(remainder); | |
remainder = 0; | |
} else { | |
if (remainder === 1) { | |
handleRemovalIfResultContains(NUMS_REMAINDER_IS_1); | |
if (indexToRemove === undefined) { | |
handleRemovalIfResultContains(NUMS_REMAINDER_IS_2); | |
} | |
} else if (remainder === 2) { | |
handleRemovalIfResultContains(NUMS_REMAINDER_IS_2); | |
if (indexToRemove === undefined) { | |
handleRemovalIfResultContains(NUMS_REMAINDER_IS_1); | |
} | |
} | |
// Where we would get rid of the 8 | |
remainder = sum % 3; | |
} | |
result.splice(indexToRemove, 1); | |
} | |
const strResult = remainder === 0 ? result.join("") : ""; | |
return strResult.replace(/^0+(?=\d)/, ""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment