Next Bigger Number
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
const {log} = console;
/*
n(abcde):
ไปฃ่กจไธไธๅๆฏ abcde ๅคง็ๆธๅญ (ไฝ้ๆฏๅช่ฝ็จ abcde ้ๅนพๅๆธๅญ)ใ
f(abcde):
1. ไปฃ่กจๅจ bcde ๅ
งๆพๅบใๆฏ a ๅคง็ๆธๅญๆๅฐ่
ใ๏ผ็ถๅพ่ท a ๅฐ่ชฟ๏ผ
ๅฆๆๆพไธๅฐ๏ผๅฐฑๅๅณ undefinedใ
2. ๅฐ่ชฟๅพ๏ผๅพ้ข็ๆธๅญใๅพๅฐๆๅฐๅคงใ๏ผ่ท็ฌฌไธๅๆธๅญๆฅ่ตทไพ๏ผ็ถๅพๅๅณใ
n(abcde) = abc+f(de) || ab+f(cde) || a+f(bcde) || f(abcde)
*/
// assume: `k` -> string of digits.
// suppose k = abcd, b = next bigger digit than `a`, then:
// f(abcd) = b + smallest(acd)
function f(k) {
// 1. find next bigger digit than leading digit
let arr = k.substring(1).split('').sort(); // sort is key
let i = arr.findIndex(c => +c > +k[0]);
// 2. if not found, return undefined.
if (i === -1) return undefined;
// if found, interchange them.
let b = arr[i]; arr[i] = k[0];
return b + arr.sort().join(''); // remember to sort again
}
// assume: `k` -> string of digits.
// next bigger number
function n(k) {
let next;
let left = k.length - 2;
while (!next && left >= 0) {
let found = f(k.substring(left));
if (found) next = k.substring(0, left) + found;
left -= 1;
}
return next;
}
// -------- log --------
// f(k)
[
3412, // 4123
4312, // undefined
]
.map(n => f(String(n)))
.forEach(x => log(x));
// n(k)
[
3412, // 3421
4312, // 4321
59884848459853, // 59884848483559
]
.map(k => n(String(k)))
.forEach(x => log(x));