Skip to content

Commit 841d51c

Browse files
committed
Add solution #2384
1 parent 1cfcf49 commit 841d51c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2162,6 +2162,7 @@
21622162
2381|[Shifting Letters II](./solutions/2381-shifting-letters-ii.js)|Medium|
21632163
2382|[Maximum Segment Sum After Removals](./solutions/2382-maximum-segment-sum-after-removals.js)|Hard|
21642164
2383|[Minimum Hours of Training to Win a Competition](./solutions/2383-minimum-hours-of-training-to-win-a-competition.js)|Easy|
2165+
2384|[Largest Palindromic Number](./solutions/2384-largest-palindromic-number.js)|Medium|
21652166
2385|[Amount of Time for Binary Tree to Be Infected](./solutions/2385-amount-of-time-for-binary-tree-to-be-infected.js)|Medium|
21662167
2387|[Median of a Row Wise Sorted Matrix](./solutions/2387-median-of-a-row-wise-sorted-matrix.js)|Medium|
21672168
2389|[Longest Subsequence With Limited Sum](./solutions/2389-longest-subsequence-with-limited-sum.js)|Easy|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 2384. Largest Palindromic Number
3+
* https://leetcode.com/problems/largest-palindromic-number/
4+
* Difficulty: Medium
5+
*
6+
* You are given a string num consisting of digits only.
7+
*
8+
* Return the largest palindromic integer (in the form of a string) that can be formed
9+
* using digits taken from num. It should not contain leading zeroes.
10+
*
11+
* Notes:
12+
* - You do not need to use all the digits of num, but you must use at least one digit.
13+
* - The digits can be reordered.
14+
*/
15+
16+
/**
17+
* @param {string} num
18+
* @return {string}
19+
*/
20+
var largestPalindromic = function(num) {
21+
const digitCount = new Array(10).fill(0);
22+
23+
for (const digit of num) {
24+
digitCount[parseInt(digit, 10)]++;
25+
}
26+
27+
let leftHalf = '';
28+
let middle = '';
29+
for (let digit = 9; digit >= 0; digit--) {
30+
const count = digitCount[digit];
31+
const pairs = Math.floor(count / 2);
32+
33+
if (digit === 0 && leftHalf === '') {
34+
continue;
35+
}
36+
37+
leftHalf += digit.toString().repeat(pairs);
38+
39+
if (count % 2 === 1 && middle === '') {
40+
middle = digit.toString();
41+
}
42+
}
43+
44+
if (leftHalf === '' && middle === '') {
45+
return '0';
46+
}
47+
48+
const rightHalf = leftHalf.split('').reverse().join('');
49+
return leftHalf + middle + rightHalf;
50+
};

0 commit comments

Comments
 (0)