package leetcode;

/**
 * https://leetcode.com/problems/fruit-into-baskets/
 */
public class Problem904 {
    public int totalFruit(int[] tree) {
        int answer = 0;
        TypeCount[] tc = new TypeCount[2];
        for (int i = 0; i < tree.length; i++) {
            if (tc[0] == null) {
                tc[0] = new TypeCount(tree[i]);
                tc[0].count++;
            } else if (tree[i] == tc[0].type) {
                tc[0].count++;
            } else if (tc[1] == null) {
                tc[1] = new TypeCount(tree[i]);
                tc[1].count++;
            } else if (tree[i] == tc[1].type) {
                tc[1].count++;
            } else {
                tc[0] = tc[1];
                tc[1] = new TypeCount(tree[i]);
                tc[1].count++;
            }
            answer = Math.max(answer, (tc[0] == null ? 0 : tc[0].count) +
                (tc[1] == null ? 0 : tc[1].count));
        }
        return answer;
    }

    private static class TypeCount {
        private final int type;
        private int count;

        public TypeCount(int num) {
            this.type = num;
        }
    }

    public static void main(String[] args) {
        Problem904 prob = new Problem904();
//        System.out.println(prob.totalFruit(new int[]{1, 2, 1})); // 3
//        System.out.println(prob.totalFruit(new int[]{0, 1, 2, 2})); // 3
//        System.out.println(prob.totalFruit(new int[]{1, 2, 3, 2, 2})); // 4
//        System.out.println(prob.totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4})); // 5
        System.out.println(prob.totalFruit(new int[]{1, 0, 1, 4, 1, 4, 1, 2, 3})); // 5
    }
}

@@ -684,21 +684,305 @@
     
-tc%5B0%5D = tc%5B1%5D
+int count = 0;%0A                int type = tree%5Bi - 1%5D;%0A                int j = i - 1;%0A                while (j %3E= 0 && tree%5Bj%5D == type) %7B%0A                    count++;%0A                    j--;%0A                %7D%0A                tc%5B0%5D = new TypeCount(tree%5Bi - 1%5D);%0A                tc%5B0%5D.count = count
 ;%0A  
@@ -1400,16 +1400,16 @@
  = num;%0A
+
         
@@ -1419,512 +1419,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem904 prob = new Problem904();%0A//        System.out.println(prob.totalFruit(new int%5B%5D%7B1, 2, 1%7D)); // 3%0A//        System.out.println(prob.totalFruit(new int%5B%5D%7B0, 1, 2, 2%7D)); // 3%0A//        System.out.println(prob.totalFruit(new int%5B%5D%7B1, 2, 3, 2, 2%7D)); // 4%0A//        System.out.println(prob.totalFruit(new int%5B%5D%7B3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4%7D)); // 5%0A        System.out.println(prob.totalFruit(new int%5B%5D%7B1, 0, 1, 4, 1, 4, 1, 2, 3%7D)); // 5%0A    %7D
 %0A%7D%0A

Solve problem 904