Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7f348c2

Browse files
richie-rich algo. algo for highest value palindrome
1 parent 395e008 commit 7f348c2

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

‎richie-rich.js

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
5+
process.stdin.resume();
6+
process.stdin.setEncoding('utf-8');
7+
8+
let inputString = '';
9+
let currentLine = 0;
10+
11+
process.stdin.on('data', inputStdin => {
12+
inputString += inputStdin;
13+
});
14+
15+
process.stdin.on('end', _ => {
16+
inputString = inputString.replace(/\s*$/, '')
17+
.split('\n')
18+
.map(str => str.replace(/\s*$/, ''));
19+
20+
main();
21+
});
22+
23+
function readLine() {
24+
return inputString[currentLine++];
25+
}
26+
27+
// Complete the highestValuePalindrome function below.
28+
const isValidPalindrome = (s) => {
29+
let m = Math.ceil(s.length / 2);
30+
for (let i = 0, j = s.length - 1; i < m, j >= m; i++ , j--) {
31+
if (s[i] !== s[j]) { return false; }
32+
}
33+
return true;
34+
}
35+
function highestValuePalindrome(s, n, k) {
36+
let lives = k;
37+
let mod = new Array(n).fill(false);
38+
let temp = s.split('');
39+
for (let i = 0; i < n / 2; i++) {
40+
let j = n - i - 1;
41+
if (temp[i] != temp[j]) {
42+
mod[i] = true;
43+
lives--;
44+
}
45+
if (temp[i] < temp[j])
46+
temp[i] = temp[j];
47+
else if (temp[i] > temp[j])
48+
temp[j] = temp[i];
49+
if (lives < 0)
50+
return "-1";
51+
}
52+
let j = 0;
53+
while ((lives > 0) && (j < n / 2)) {
54+
if (temp[j] != '9') {
55+
if (mod[j])
56+
lives++;
57+
if (lives > 1) {
58+
temp[j] = '9';
59+
temp[n - j - 1] = '9';
60+
lives -= 2;
61+
}
62+
}
63+
j++;
64+
}
65+
if (n % 2 == 1) {
66+
if (lives > 0)
67+
temp[Math.floor(n / 2)] = '9';
68+
}
69+
return temp.join('');
70+
}
71+
72+
function main() {
73+
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
74+
75+
const nk = readLine().split(' ');
76+
77+
const n = parseInt(nk[0], 10);
78+
79+
const k = parseInt(nk[1], 10);
80+
81+
const s = readLine();
82+
83+
let result = highestValuePalindrome(s, n, k);
84+
85+
ws.write(result + "\n");
86+
87+
ws.end();
88+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /