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
| class Solution { public int totalFruit(int[] tree) { int n = tree.length; if (n == 0) { return 0; } List<Integer> list = new ArrayList<>(); HashSet<Integer> set = new HashSet<>(); int i = 0; int j = 0; int result = 0; while (i < n && j < n) { list.add(tree[j]); set.add(tree[j]); j++; while (i < n && set.size() > 2) { list.remove((Integer) tree[i]); i++; set = new HashSet<>(list); } result = Math.max(result, j - i); } return result; } }
|