Skip to main content

2 posts tagged with "greedy"

View All Tags

· One min read

https://leetcode.com/problems/longest-palindrome/submissions/

/**
* @param {string} s
* @return {number}
*/
var longestPalindrome = function (s) {
let longest = 0;
let keys = {};

for (const char of s) {
keys[char] = (keys[char] || 0) + 1;
if (keys[char] % 2 === 0) {
longest += 2;
}
}
return s.length > longest ? longest + 1 : longest;
};

Runtime: 106 ms, faster than 58.34% of JavaScript online submissions for Longest Palindrome.

Memory Usage: 43.5 MB, less than 73.08% of JavaScript online submissions for Longest Palindrome.

· One min read

https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/

Solution 1

/**
* @param {number} num
* @return {number}
*/
var minimumSum = function (num) {
const numToArr = num.toString().split('');

for (let i = 1; i < numToArr.length; i++) {
for (let j = 0; j < i; j++) {
if (numToArr[i] < numToArr[j]) {
const smallNum = numToArr[i];
numToArr[i] = numToArr[j];
numToArr[j] = smallNum;
}
}
}

const new1 = numToArr[0] + numToArr[2];
const new2 = numToArr[1] + numToArr[3];

return Number(new1) + Number(new2);
};