-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathnextLargestNo.java
More file actions
56 lines (46 loc) · 1.25 KB
/
Copy pathnextLargestNo.java
File metadata and controls
56 lines (46 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//o(n) time complexity
import java.util.*;
public class nextLargestNo
{
public static void main(String args[])
{
String str;
Scanner sc=new Scanner(System.in);
str=sc.nextLine();
nextLargestNo1(str);
}
static void nextLargestNo1(String str)
{
int n=str.length();
StringBuilder s=new StringBuilder(str);
int i=n-1;
while(i>0 && s.charAt(i)<=s.charAt(i-1))
{
i--;
}
int j=i-1; //first candidate
System.out.println(s.charAt(j));
if(j>=0)
{
int secondCandidate=i;
i++;
while(i<n && s.charAt(i)>s.charAt(j))
{
if(s.charAt(i)<=s.charAt(secondCandidate))
{
secondCandidate=i;
}
i++;
}
System.out.println(s.charAt(secondCandidate));
swap(s,j,secondCandidate);
System.out.println(s.toString());
}
}
private static void swap(StringBuilder s,int i,int secondCandidate)
{
char temp=s.charAt(i);
s.setCharAt(i,s.charAt(secondCandidate));
s.setCharAt(secondCandidate,temp);
}
}