Skip to content

Commit

Permalink
Brute force solution to "Maximum Swap" problem
Browse files Browse the repository at this point in the history
  • Loading branch information
dkoval committed Oct 17, 2024
1 parent 630159b commit 92c01da
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.github.dkoval.leetcode.challenge;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* <a href="https://leetcode.com/problems/maximum-swap/">Maximum Swap</a>
* <p>
* You are given an integer num. You can swap two digits at most once to get the maximum valued number.
* <p>
* Return the maximum valued number you can get.
* <p>
* Constraints:
* <p>
* 0 <= num <= 10^8
*/
public interface MaximumSwap {

int maximumSwap(int num);

class MaximumSwapRev1 implements MaximumSwap {

@Override
public int maximumSwap(int num) {
// convert num to a list of digits
List<Integer> digits = new ArrayList<>();
int x = num;
while (x > 0) {
digits.add(x % 10);
x /= 10;
}

int n = digits.size();
Collections.reverse(digits);

// brute force
int best = num;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// swap digits at indices i and j
swap(digits, i, j);
best = Math.max(best, asNumber(digits));
// undo swap before considering a new pair of indices
swap(digits, i, j);
}
}
return best;
}

private void swap(List<Integer> digits, int i, int j) {
int tmp = digits.get(i);
digits.set(i, digits.get(j));
digits.set(j, tmp);
}

private int asNumber(List<Integer> digits) {
int x = 0;
for (int d : digits) {
x *= 10;
x += d;
}
return x;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.github.dkoval.leetcode.challenge

import com.github.dkoval.leetcode.challenge.MaximumSwap.MaximumSwapRev1
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
import java.util.stream.Stream

internal class MaximumSwapTest {

class InputArgumentsProvider : ArgumentsProvider {

override fun provideArguments(context: ExtensionContext): Stream<out Arguments> = Stream.of(
Arguments.of(2736, 7236),
Arguments.of(9973, 9973),
Arguments.of(1, 1)
)
}

@Nested
inner class MaximumSwapRev1Test {

@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `should return the maximum valued number you can get`(num: Int, expected: Int) {
MaximumSwapRev1().test(num, expected)
}
}
}

private fun MaximumSwap.test(num: Int, expected: Int) {
val actual = maximumSwap(num)
assertEquals(expected, actual)
}

0 comments on commit 92c01da

Please sign in to comment.