Tuesday, 15 June 2021

Finding the longest subarray that starts and ends on the same digit

 package com.poc.basic;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


public class Test {


public static void main(String[] args) {

List<Integer> input=Arrays.asList(1, 2, 3, 7, 6, 1, 9, 8, 6, 1, 9, 8,  9, 8, 3);

List<Integer> largest = new ArrayList<Integer>();

int largestSqnce = 0;

Map<Integer, Integer> map = new HashMap();

for(int i=0; i<input.size(); i++) {

if(!map.containsKey(input.get(i))) {

map.put(input.get(i), i);

}else {

if(i - map.get(input.get(i)) > largestSqnce) {

largestSqnce = (i - map.get(input.get(i)))+1;

largest = input.subList(map.get(input.get(i)), i+1);

}

}

}

System.out.println(largest);

}

}


No comments:

Post a Comment