最近面接を受けて、こんな質問をされました。質問を適切に説明しましょう。
数値 M (N 桁の整数) と K 個のスワップ操作 (スワップ操作は 2 桁をスワップできます) が与えられた場合、可能な最大整数を取得するアルゴリズムを考案しますか?
例:
M = 132 K = 1 出力 = 312
M = 132 K = 2 出力 = 321
M = 7899 k = 2 出力 = 9987
私の解決策(疑似コードのアルゴリズム)。max-heap を使用して、各 K 操作で N 桁から最大桁を取得し、適切に交換しました。
for(int i = 0; i<K; i++)
{
int max_digit_currently = GetMaxFromHeap();
// The above function GetMaxFromHeap() pops out the maximum currently and deletes it from heap
int index_to_swap_with = GetRightMostOccurenceOfTheDigitObtainedAbove();
// This returns me the index of the digit obtained in the previous function
// .e.g If I have 436659 and K=2 given,
// then after K=1 I'll have 936654 and after K=2, I should have 966354 and not 963654.
// Now, the swap part comes. Here the gotcha is, say with the same above example, I have K=3.
// If I do GetMaxFromHeap() I'll get 6 when K=3, but I should not swap it,
// rather I should continue for next iteration and
// get GetMaxFromHeap() to give me 5 and then get 966534 from 966354.
if (Value_at_index_to_swap == max_digit_currently)
continue;
else
DoSwap();
}
時間の複雑さ: O(K*( N + log_2(N) ))
// K 回 [ヒープから数をポップアウトするための log_2(N) & スワップする最も右のインデックスを取得するための N]
この例では、上記の戦略は失敗します:
M = 8799 および K = 2
私の戦略に従うと、K=1 の後に M = 9798 が得られ、K=2 の後に M = 9978 が得られます。ただし、取得できる最大値は、K = 2 の後で M = 9987 です。
私は何を取りこぼしたか?
また、問題を解決する他の方法と、ソリューションを最適化する方法を提案してください。