How to find the subsequence of number in java in simplest way - java

I am using below program for printing all possible sub sequence
class Test {
static void printSubSeqRec(String str, int n, int index, String curr) {
if (index == n) {
return;
}
System.out.println(curr);
for (int i = index + 1; i < n; i++) {
curr += str.charAt(i);
printSubSeqRec(str, n, i, curr);
curr = curr.substring(0, curr.length() - 1);
}
}
static void printSubSeq(String str) {
int index = -1;
String curr = "";
printSubSeqRec(str, str.length(), index, curr);
}
public static void main(String[] args) {
String str = "24";
printSubSeq(str);
}
}
Output:
2
4
24
Is there any other way for getting the same result?

In solving this I figured I wanted to generate the following pairs of indices in the given order. The first element is the start of the substring and the second is the limit for a four character string.
[0,1], [1,2], [2,3], [3,4], [0,2], [1,3], [2,4], [0,3], [1,4], [0,4]
This is the simplest way I could come up with.
String numb = "1234";
for (int z = 1; z <= numb.length(); z++) {
for (int k = z; k <= numb.length(); k++) {
System.out.println(numb.substring(k - z, k));
}
}
If you want to do it recursively, here is one way.
String numb = "1234";
subseq(numb, 0, 1, 1);
public static void subseq(String v, int z, int k, int i) {
System.out.println(v.substring(z, k));
if (k < v.length()) {
subseq(v, z + 1, k + 1, i);
}
else if (z > 0) {
subseq(v, 0, 1 + i, i + 1);
}
}
The first recursive call to subseq is such that z and k are incremented by 1 each.
The i serves as the next amount to increment k
So the second call to subseq calls with z back to 0 and k to 1+i
In that second call, i is also increased by 1
This continues until k >= length of string and z = 0 which is the entire
String and the last string printed.
But I prefer the nested loops solution.

public class main {
public static void main(String[] args) {
String str= "243";
for(int i = 1; i<= str.length();i++){
int m = 0;
for(int j =0;j < str.length() && m+i <= str.length();j++){
System.out.println(str.substring(j,m+i));
m++;
}
}
}
}
result :
2 4 3 24 43 243

In case you prefer doing it without recursion:
static void printSubSeq(String str) {
for(int i = 1; i <= str.length(); i++) {
for(int j = 0; j <= str.length() - i; j++) {
int k = j + i - 1;
for(int l = j; l <= k; l++) System.out.print(str.charAt(l));
System.out.println();
}
}
}

Related

Letter printing until the whole word is finally displayed in the form of a triangle, Java

Output should look like this
Here is my code:
public static String repeat(String s, int n) {
String res = "";
for (int i = 0; i < n; i++) {
res += s;
}
return res;
}
public static void main(String[] args) {
String word = "mathematics";
int n = word.length()/2;
for (int i = 0; i <= n; i++) {
System.out.print(repeat(" ", n- i));
System.out.println(word.substring(n -1, n + i + 1)); //here is the problem I think
}
}
Or do you know some better solution? Thanks
The start index of your substring is n-1 which is constant, but it has to change, it has to be n-i to decrease to the start of the word
for (int i = 0; i <= n; i++) {
System.out.print(repeat(" ", n- i));
System.out.println(word.substring(n -i, n + i + 1));
}
m
ema
hemat
themati
athematic
mathematics

How to use LSD String Sort without having to enter a fixed length?

sorry for my bad english. I'm styding LSD String Sorts algorithm and I have a question related to it. Here my code. I want input W not fixed, for example:
String[] a = {"38A", "3TW723", "2IYEA938", "3CI34780720"};
public static void sort(String[] a, int w) { // Sort a[] on leading W characters.
int R = 256;
int N = a.length;
//For each of the character from right to left
for (int d = w - 1; d >= 0; d--) {
//1. count the frequencies
int[] count = new int[R + 1];
for (int i = 0; i < N; i++) {
count[a[i].charAt(d) + 1]++;
}
//2. Transform counts to indices
for (int r = 0; r < R; r++) {
count[r + 1] += count[r];
}
//3. Distribute
String aux[] = new String[N];
for (int i = 0; i < N; i++) {
aux[count[a[i].charAt(d)]] = a[i];
count[a[i].charAt(d)]++;
}
//4. Copyback
System.arraycopy(aux, 0, a, 0, N);
}
}
To develop an implementation of LSD string sort that works for variable-length strings, we need to do many works on the base of your code. We need to find the longest length of string in string[] a, so when d >= a[i].length(), we return 0, which means we add extra 0 to make every string in the same length. This is my code.
// Develop an implementation of LSD string sort
// that works for variable-length strings.
public class LSDForVariableLengthStrings {
// do not instantiate
private LSDForVariableLengthStrings() { }
// find longest length string in string[] a.
public static int findLongestLength(String[] a) {
int longest = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i].length() > longest) {
longest = a[i].length();
}
}
return longest;
}
// if d >= 0 && d < a[i].length(), return a[i].charAt(d);
// else , return 0, which means least value to sort.
public static int findCharAtInString(int i, int d, String[] a) {
if (d < 0 || d >= a[i].length()) {
return 0;
}
return a[i].charAt(d);
}
// Rearranges the array of variable-length strings.
public static void sort(String[] a) {
int n = a.length;
int R = 256; // extended ASCII alphabet size.
String[] aux = new String[n];
int w = findLongestLength(a); // w is the length of longest string in a.
for (int d = w - 1; d >= 0; d--) {
// sort by key-indexed counting on dth character
// compute frequency counts
int[] count = new int[R + 1];
for (int i = 0; i < n; ++i) {
int c = findCharAtInString(i, d, a);
count[c + 1]++;
}
// compute cumulates
for (int r = 0; r < R; ++r) {
count[r + 1] += count[r];
}
// move data
for (int i = 0; i < n; ++i) {
int c = findCharAtInString(i, d, a);
aux[count[c]++] = a[i];
}
// copy back
for (int i = 0; i < n; ++i) {
a[i] = aux[i];
}
}
}
public static void main(String[] args) {
String[] a = {"38A", "3TW723", "2IYEA938", "3CI34780720"};
int n = a.length;
// sort the strings
sort(a);
// prints results
for (int i = 0; i < n; ++i) {
System.out.println(a[i]);
}
}
}
LSD sorts only fixed-length strings. Use MSD instead

How can I modify the first for loop in this java method into a recursive call?

This is a problem for an Algorithms course I'm taking that I can't figure out.
// modify the array x to generate the next k-combination from x.
// In general, the first k-combination of n elements is { 1, 2, ..., k }
// and the last k-combination is { n-k+1, n-k+2, ..., n }.
public static boolean nextCombination (int x[], int k, int n) {
for (int j = k-1; j >= 0; j--)
if (x[j] <= (n - k + j)) {
x[j]++;
for (int i = 1; i < k - j; i++)
x[i+j] = x[j]+i;
return true;
}
return false;
}
It gets called by this method:
// print all k-combinations of n elements.
public static void enumerateCombinations (int k, int n) {
int x[] = new int[100]; // k <= 100
System.out.println("All " + k + "-combinations of " + n + " numbers:");
for (int j = 0; j < k; j++)
x[j] = j+1;
while (true) {
printArray(x, k);
if (nextCombination(x, k, n) == false)
break;
}
}
Any help would be appreciated.
With this code you transform the nextCombination method into a recursive one.
public static boolean nextCombinationRecursive (int j, int x[], int k, int n) {
if (j < 0 || j > k) return false;
if (x[j] <= (n - k + j)) {
x[j]++;
for (int i = 1; i < k - j; i++)
x[i+j] = x[j]+i;
return true;
}
return nextCombinationRecursive(j - 1, x, k, n);
}
And you call it from enumerateCombinations like this:
if (nextCombinationRecursive(k - 1, x, k, n) == false)

Compute Prefix Function in String Matching

What am i doing wrong here?
Java code for computing prefix function. Two input are right but the last one is wrong.
Here's the pseudocode:
Java code:
class Main {
// compute prefix function
public static void main(String[] args) {
String p = "422213422153342";
String x = "ababbabbabbababbabb";
String y = "ababaca";
printOutput(p);
printOutput(y);
System.out.println();System.out.println();
System.out.println("the prefix func below is wrong. I am not sure why.");
System.out.print("answer should be: 0 0 1 2 0 1 2 0 1 2 0 1 2 3 4 5 6 7 8");
printOutput(x);
}
static void printOutput(String P){
System.out.println();System.out.println();
System.out.print("p[i]: ");
for(int i = 0; i < P.length(); i++)System.out.print(P.charAt(i) + " ");
System.out.println();
System.out.print("Pi[i]: ");
compute_prefix_func(P);
}
public static void compute_prefix_func(String P){
int m = P.length();
int pi[] = new int[m];
for(int i = 0; i < pi.length; i++){
pi[i] = 0;
}
pi[0] = 0;
int k = 0;
for(int q = 2; q < m; q++){
while(k > 0 && ( ((P.charAt(k) + "").equals(P.charAt(q) + "")) == false)){
k = pi[k];
}
if ((P.charAt(k) + "").equals(P.charAt(q) + "")){
k = k + 1;
}
pi[q] = k;
}
for(int i = 0; i < pi.length; i++){
System.out.print(pi[i] + " ");
}
}
}
Okay, let's start off by making the code much easier to read. This:
if ((P.charAt(k) + "").equals(P.charAt(q) + ""))
can be simplified to:
if (P.charAt(k) == P.charAt(q))
... and you've done that in multiple places.
Likewise here:
int pi[] = new int[m];
for(int i = 0; i < pi.length; i++){
pi[i] = 0;
}
pi[0] = 0;
... you don't need the explicit initialization. Variables are 0-initialized by default. (It's unclear why you're then setting pi[0] again, although I note that if P.length() is 0, this will throw an exception.)
Next is to remove the explicit comparison with false, instead just using ! so we have:
while(k > 0 && P.charAt(k) != P.charAt(q))
Finally, let's restructure the code a bit to make it easier to follow, use more conventional names, and change int pi[] to the more idiomatic int[] pi:
class Main {
public static void main(String[] args) {
String x = "ababbabbabbababbabb";
int[] prefix = computePrefix(x);
System.out.println("Prefix series for " + x);
for (int p : prefix) {
System.out.print(p + " ");
}
System.out.println();
}
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for(int q = 2; q < input.length(); q++) {
while (k > 0 && input.charAt(k) != input.charAt(q)) {
k = pi[k];
}
if (input.charAt(k) == input.charAt(q)) {
k = k + 1;
}
pi[q] = k;
}
return pi;
}
}
That's now much easier to follow, IMO.
We can now look back to the pseudocode and see that it appears to be using 1-based indexing for both arrays and strings. That makes life slightly tricky. We could mimic that throughout the code, changing every array access and charAt call to just subtract 1.
(I've extracted the common subexpression of P[q] to a variable target within the loop.)
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for (int q = 2; q <= input.length(); q++) {
char target = input.charAt(q - 1);
while (k > 0 && input.charAt(k + 1 - 1) != target) {
k = pi[k - 1];
}
if (input.charAt(k + 1 - 1) == target) {
k++;
}
pi[q - 1] = k;
}
return pi;
}
That now gives your desired results, but it's really ugly. We can shift q very easily, and remove the + 1 - 1 parts:
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
int k = 0;
for (int q = 1; q < input.length(); q++) {
char target = input.charAt(q);
while (k > 0 && input.charAt(k) != target) {
k = pi[k - 1];
}
if (input.charAt(k) == target) {
k++;
}
pi[q] = k;
}
return pi;
}
It's still not entirely pleasant, but I think it's what you want. Make sure you understand why I had to make the changes I did.
public static int[] computePrefix(String input) {
int[] pi = new int[input.length()];
pi[0] = -1;
int k = -1;
for (int q = 1; q < input.length(); q++) {
char target = input.charAt(q);
while (k > 0 && input.charAt(k + 1) != target) {
k = pi[k];
}
if (input.charAt(k + 1) == target) {
k++;
}
pi[q] = k;
}
return pi;
}

Find the largest span between the same number in an array

Merry Christmas and hope you are in great Spirits,I have a Question in Java-Arrays as shown below.Im stuck up with this struggling to get it rite.
Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Write a **Java Function** that returns the largest span found in the given array.
**Example:
maxSpan({1, 2, 1, 1, 3}) → 4,answer is 4 coz MaxSpan between 1 to 1 is 4
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6,answer is 6 coz MaxSpan between 4 to 4 is 6
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6,answer is 6 coz Maxspan between 4 to 4 is 6 which is greater than MaxSpan between 1 and 1 which is 4,Hence 6>4 answer is 6.
I have the code which is not working,it includes all the Spans for a given element,im unable to find the MaxSpan for a given element.
Please help me out.
Results of the above Program are as shown below
Expected This Run
maxSpan({1, 2, 1, 1, 3}) → 4 5 X
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6 8 X
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6 9 X
maxSpan({3, 3, 3}) → 3 5 X
maxSpan({3, 9, 3}) → 3 3 OK
maxSpan({3, 9, 9}) → 2 3 X
maxSpan({3, 9}) → 1 1 OK
maxSpan({3, 3}) → 2 3 X
maxSpan({}) → 0 1 X
maxSpan({1}) → 1 1 OK
::Code::
public int maxSpan(int[] nums) {
int count=1;//keep an intial count of maxspan=1
int maxspan=0;//initialize maxspan=0
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i] == nums[j]){
//check to see if "i" index contents == "j" index contents
count++; //increment count
maxspan=count; //make maxspan as your final count
int number = nums[i]; //number=actual number for maxspan
}
}
}
return maxspan+1; //return maxspan
}
Since a solution has been given, here is a more efficient solution which uses one pass.
public static void main(String... args) {
int maxspan = maxspan(3, 3, 3, 2, 1, 4, 3, 5, 3, 1, 1, 1, 1, 1);
System.out.println(maxspan);
}
private static int maxspan(int... ints) {
Map<Integer, Integer> first = new LinkedHashMap<Integer, Integer>(); // use TIntIntHashMap for efficiency.
int maxspan = 0; // max span so far.
for (int i = 0; i < ints.length; i++) {
int num = ints[i];
if (first.containsKey(num)) { // have we seen this number before?
int span = i - first.get(num) + 1; // num has been found so what is the span
if (span > maxspan) maxspan = span; // if the span is greater, update the maximum.
} else {
first.put(num, i); // first occurrence of number num at location i.
}
}
return maxspan;
}
I see the following problems with your attempt:
Your count is completely wrong. You can instead calculate count from i and j: j - i + 1
You're overriding maxcount as soon as you get any span, so you're going to end up with the last span, not the maximum span. Fix it by going maxspan = Math.max(maxspan, count);.
You can remove the line int number = nums[i]; as you never use number.
Remove the +1 in the returnmaxspan+1;` if you follow my tips above.
Initial maxspan should be 1 if there are any values in the array, but 0 if the array is empty.
That should help you get it working. Note that you can do this in a single pass of the array, but that's probably stretching it too far for you. Concentrate on getting your code to work before considering efficiency.
Here is the solution of this problem:
public int maxSpan(int[] nums) {
int maxSpan=0;
int tempSpan=0;
if(nums.length==0){
return 0;
}
for(int i=0;i<nums.length;i++){
for(int j=nums.length-1;j>i;j--){
if(nums[i]==nums[j]){
tempSpan=j-i;
break;
}
}
if(tempSpan>maxSpan){
maxSpan=tempSpan;
}
}
return maxSpan+1;
}
I did it with a List. Easier way to do it.
The only problem is if the Array is too big, maybe it's gonna take a while..
import java.util.ArrayList;
import java.util.List;
public class StackOverflow {
public static void main(String[] args) {
List<Integer> listNumbers = new ArrayList<Integer>();
listNumbers.add(3);
listNumbers.add(3);
listNumbers.add(3);
listNumbers.add(2);
listNumbers.add(1);
listNumbers.add(4);
listNumbers.add(3);
listNumbers.add(5);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(3);
int result = 0;
Integer key = null;
for(Integer i : listNumbers){
int resultDistance = returnDistance(listNumbers, i);
if (resultDistance > result){
result = resultDistance;
key = i;
}
}
System.out.println("MaxSpan of key " + key + " is: " + result);
}
private static int returnDistance(List<Integer> listNumbers, Integer term){
Integer startPosition = null;
Integer endPosition = null;
boolean bolStartPosition = false;
boolean bolResult = false;
int count = 1;
int result = 0;
for (Integer i : listNumbers){
if (i == term && !bolStartPosition){
startPosition = count;
bolStartPosition = true;
continue;
}
if (i == term && bolStartPosition){
endPosition = count;
}
count++;
}
if (endPosition != null){
// because it's inclusive from both sides
result = endPosition - startPosition + 2;
bolResult = true;
}
return (bolResult?result:-1);
}
}
public int maxSpan(int[] nums) {
int b = 0;
if (nums.length > 0) {
for (int i = 0; i < nums.length; i++) {
int a = nums[0];
if (nums[i] != a) {
b = nums.length - 1;
} else {
b = nums.length;
}
}
} else {
b = 0;
}
return b;
}
One brute force solution may like this, take one item from the array, and find the first occurance of item from the left most, and calculate the span, and then compare with the previous result.
public int maxSpan(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++) {
int item = nums[i];
int span = 0;
for(int j = 0; j<= i; j++) {//find first occurance of item from the left
if(nums[j]==item) {
span = i -j+1;
break;
}
}
if(span>result) {
result = span;
}
}
return result;
}
Here is the solution -
public int maxSpan(int[] nums) {
int span = 0;
for (int i = 0; i < nums.length; i++) {
for(int j = i; j < nums.length; j++) {
if(nums[i] == nums[j]) {
if(span < (j - i + 1)) {
span = j -i + 1;
}
}
}
}
return span;
}
public int maxSpan(int[] nums) {
int span = 0;
//Given the values at position i 0..length-1
//find the rightmost position of that value nums[i]
for (int i = 0; i < nums.length; i++) {
// find the rightmost of nums[i]
int j =nums.length -1;
while(nums[i]!=nums[j])
j--;
// j is at the rightmost posititon of nums[i]
span = Math.max(span,j-i+1);
}
return span;
}
public int maxSpan(int[] nums) {
//convert the numnber to a string
String numbers = "";
if (nums.length == 0)
return 0;
for(int ndx = 0; ndx < nums.length;ndx++){
numbers += nums[ndx];
}
//check beginning and end of string
int first = numbers.indexOf(numbers.charAt(0));
int last = numbers.lastIndexOf(numbers.charAt(0));
int max = last - first + 1;
int efirst = numbers.indexOf(numbers.charAt(numbers.length()-1));
int elast = numbers.lastIndexOf(numbers.charAt(numbers.length()-1));
int emax = elast - efirst + 1;
//return the max span.
return (max > emax)?max:emax;
}
public int maxSpan(int[] nums) {
int current = 0;
int currentcompare = 0;
int counter = 0;
int internalcounter = 0;
if(nums.length == 0)
return 0;
for(int i = 0; i < nums.length; i++) {
internalcounter = 0;
current = nums[i];
for(int x = i; x < nums.length; x++) {
currentcompare = nums[x];
if(current == currentcompare) {
internalcounter = x - i;
}
if(internalcounter > counter) {
counter = internalcounter;
}
}
}
return counter + 1;
}
public int maxSpan(int[] nums) {
if(nums.length<1){
return 0;
}
int compare=1;
for (int i=0; i<nums.length; i++){
for (int l=1; l<nums.length; l++){
if((nums[l]==nums[i])&&(Math.abs(l)-Math.abs(i))>=compare){
compare = Math.abs(l)-Math.abs(i)+1;
}
}
}
return compare;
}
public static int MaxSpan(int[] input1, int key)
{
int Span = 0;
int length = input1.length;
int i,j,k = 0;
int start = 0, end = 0 ;
k = key;
for (int l = 0; l < length; l++) {
if(input1[l] == k) { start = l;
System.out.println("\nStart = " + start);
break;
}
}
if(start == 0) { Span = 0; System.out.println("Key not found"); return Span;}
for (j = length-1; j> start; j--) {
if(input1[j] == k) { end = j;
System.out.println("\nEnd = " + end);
break;
}
}
Span = end - start;
System.out.println("\nStart = " + start + "End = " + end + "Span = " + Span);
return Span;
}
public int maxSpan(int[] nums) {
int length = nums.length;
if(length <= 0)
return 0;
int left = nums[0];
int rigth = nums[length - 1];
int value = 1;
//If these values are the same, then the max span is length
if(left == rigth)
return length;
// the last match is the largest span for any value
for(int x = 1; x < length - 1; x++)
{
if(nums[x] == left || nums[x] == rigth)
value = x + 1;
}
return value;
}
public int maxSpan(int[] nums) {
int count, largest=0;
for (int x=0; x< nums.length; x++)
{
for (int y=0; y< nums.length; y++)
{
if (nums[x]==nums[y])
{
count= y-x+1;
if (count > largest)
{
largest= count;
}
}
}
}
return largest;
}
import java.io.*;
public class maxspan {
public static void main(String args[])throws java.io.IOException{
int A[],span=0,pos=0;
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the number of elements");
A=new int[Integer.parseInt(in.readLine())];
int i,j;
for(i=0;i<A.length;i++)
{
A[i]=Integer.parseInt(in.readLine());
}
for(i=0;i<A.length;i++)
{
for(j=A.length-1;j>=0;j--)
if(A[i]==A[j]&&(j-i)>span){span=j-i;pos=i;}
}
System.out.println("maximum span => "+(span+1)+" that is of "+A[pos]);
}
}
public static int maxSpan(int[] nums) {
int left = 0;
int right = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[0] == nums[nums.length - 1 - i]) {
left = nums.length - i;
break;
} else if (nums[nums.length - 1] == nums[i]) {
right = nums.length - i;
break;
}
}
return Math.max(left, right);
}
The above solutions are great, if your goal is to avoid using Arrays.asList and indexOf and LastIndexOf, the code below does the job as lazy as possible, while still being clear and concise.
public int maxSpan(int[] nums) {
if(nums.length < 2){ //weed out length 0 and 1 cases
return nums.length;
}
int maxSpan = 1; //start out as 1
for(int a = 0; a < nums.length; a++){
for(int b = nums.length - 1; b > a; b--){
if(nums[a] == nums[b]){
maxSpan = Math.max(maxSpan, (b + 1 - a));
//A little tricky getting those indices together.
break; //there's no reason to continue,
//at least for this single loop execution inside another loop
}
}
}
return maxSpan; //the maxSpan is here!
}
The Math.max method returns the larger of 2 values, one of them if they are equal.
This is how I did it:
public int maxSpan(int[] nums) {
for (int span=nums.length; span>0; span--) {
for (int i=0; i<nums.length-span+1; i++) {
if (nums[i] == nums[i+span-1]) return span;
}
}
return 0;
}
I am not sure, if I have to use 2 for-loops... or any loop at all?
If not, this version functions without any loop.
At first you check, if the length of the array is > 0. If not, you simply return the length of the array, which will correspond to the correct answer.
If it is longer than 0, you check if the first and last position in the array have the same value.
If yes, you return the length of the array as the maxSpan.
If not, you substract a 1, since the value appears twice in the array.
Done.
public int maxSpan(int[] nums) {
if(nums.length > 0){
if(nums[0] == nums[nums.length - 1]){
return nums.length;
}
else{
return nums.length - 1;
}
}
return nums.length;
}
public int maxSpan(int[] nums) {
Stack stack = new Stack();
int count = 1;
int value = 0;
int temp = 0;
if(nums.length < 1) {
return value;
}
for(int i = 0; i < nums.length; i++) {
for(int j = nums.length - 1; j >= i; j--) {
if(nums[i] == nums[j]) {
count = (j - i) + 1;
stack.push(count);
count = 1;
break;
}
}
}
if(stack.peek() != null) {
while(stack.size() != 0) {
temp = (Integer) stack.pop();
if(value <= temp) {
value = temp;
} else {
value = value;
}
}
}
return value;
}
public int maxSpan(int[] nums) {
int totalspan=0;
int span=0;
for(int i=0;i<nums.length;i++)
{
for (int j=nums.length-1;j>i-1;j--)
{
if(nums[i]==nums[j])
{
span=j-i+1;
if (span>totalspan)
totalspan=span;
break;
}
}
}
return totalspan;
}
public int maxSpan(int[] nums) {
int max_span=0, j;
for (int i=0; i<nums.length; i++){
j=nums.length-1;
while(nums[i]!=nums[j]) j--;
if (j-i+1>max_span) max_span=j-i+1;
}
return max_span;
}
Linear solution with a Map storing the first occurrence, and calculating the distance from it for the next occurrences:
public int maxSpan(int[] nums) {
int span = 0;
Map<Integer, Integer> first = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (!first.containsKey(nums[i]))
first.put(nums[i], i);
span = Math.max(span, (i - first.get(nums[i])) + 1);
}
return span;
}

Categories

Resources