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 236ea6a

Browse files
awesome problem, largest-permutation
1 parent 392d437 commit 236ea6a

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

‎largest-permutation.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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+
function getMax(arr) {
27+
return Math.max.apply(Math, arr);
28+
}
29+
// Complete the largestPermutation function below.
30+
function largestPermutation(k, arr) {
31+
32+
let obj = {};
33+
arr.forEach((value, pos) => { obj[value] = pos });
34+
35+
let n = arr.length;
36+
for (let i = 0; i < k && i < n; i++) {
37+
let max = n-i;
38+
let maxIndex = obj[n-i];
39+
40+
// console.log(max, maxIndex);
41+
42+
if (max !== arr[i]) {
43+
let start = arr[i];
44+
arr[maxIndex] = start;
45+
arr[i] = max;
46+
47+
obj[start] = maxIndex;
48+
obj[max] = i;
49+
50+
} else {
51+
k++;
52+
}
53+
}
54+
// console.log(obj);
55+
return arr;
56+
}
57+
58+
function main() {
59+
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
60+
61+
const nk = readLine().split(' ');
62+
63+
const n = parseInt(nk[0], 10);
64+
65+
const k = parseInt(nk[1], 10);
66+
67+
const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));
68+
69+
let result = largestPermutation(k, arr);
70+
71+
ws.write(result.join(" ") + "\n");
72+
73+
ws.end();
74+
}

0 commit comments

Comments
(0)

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