Saturday, February 16, 2013

Next Highest Number in Sequence


  Find the next highest number in the given sequence.  
  example:
  input : 54821
  output: 58412

 
   Solution: 

/*
 *
 *  1) Search for a non increasing number from right to left in the given sequence, suppose that number is x.
 *  2) Now find largest number < x from right, suppose that number is y.
 *  3) swap x and y.
 *
 *  Runtime: O(n).
 */
public class NextHighestNumberFromGivenSequence {

public int getNextHighestNumber(int[] currSeq) {

int nextNum = 0;
int x = -1;

for (int i = currSeq.length - 1; i > 0; i--) {
if (currSeq[i] > currSeq[i - 1]) {
x = i - 1;
break;
}
}

if (x != -1) {
for (int i = currSeq.length - 1; i > 0; i--) {
if (currSeq[i] > currSeq[x]) {
int temp = currSeq[x];
currSeq[x] = currSeq[i];
currSeq[i] = temp;
break;
}
}
}

for (int i = 0; i < currSeq.length; i++) {

if (i != 0)
nextNum = nextNum * 10;
nextNum = nextNum + currSeq[i];
}

return nextNum;
}


public static void main(String args[]) {

int[] arr = { 1, 2, 3, 4 };
System.out.println(new NextHighestNumberFromGivenSequence()
.getNextHighestNumber(arr));
}
}

No comments: