Tuesday, September 1, 2020

LeetCode Medium: Fruit Into Baskets

Y'day I solved LeetCode medium level problem: #904: Fruit Into Baskets ()

A quick heuristics-based solution with O(n) time-complexity in Java, which has been accepted by the LeetCode judge, is :

  
  class Solution {
    public int totalFruit(int[] tree) {
        Integer[] uniqueTreeTypesIdx = new Integer[2];
        uniqueTreeTypesIdx[0] = 0;
        
        int start = 0;
        int lastConsecutiveStretchStart = 0;
        int maxStretchLength = 1;
        int i = 1; //index counter
        for (i=1; i<tree.length; i++) {
            if (tree[i] != tree[uniqueTreeTypesIdx[0]]) {
                if (uniqueTreeTypesIdx[1] == null) {
                    uniqueTreeTypesIdx[1] = i;
                    lastConsecutiveStretchStart = i;
                } else if (tree[i] != tree[uniqueTreeTypesIdx[1]]) {
                    maxStretchLength = Math.max (maxStretchLength, i-1-start+1);
                    start = lastConsecutiveStretchStart;
                    uniqueTreeTypesIdx[0] = lastConsecutiveStretchStart;
                    uniqueTreeTypesIdx[1] = i;
                    lastConsecutiveStretchStart = i;
                } else { //tree[i] != tree[uniqueTreeTypesIdx[0]] && tree[i] == tree[uniqueTreeTypesIdx[1]] 
                    if (tree[i] == tree[lastConsecutiveStretchStart])
                        ;
                    else
                        lastConsecutiveStretchStart = i;
                }
            } else {
                if (tree[i] == tree[lastConsecutiveStretchStart])
                    ;
                else
                    lastConsecutiveStretchStart = i;
            }
        }
        maxStretchLength = Math.max (maxStretchLength, i-1-start+1);
        return maxStretchLength;
    }
}
  


I would like to re-visit it in near-times, to devise a more elegant and intuitive solution approach, but this is it for now!

Stay tuned for the next one!


No comments:

Post a Comment

Featured Post

interviewBit Medium: Palindrome Partitioning II

Problem Name:  Palindrome Partitioning II Problem Description : https://www.interviewbit.com/problems/palindrome-partitioning-ii/ Problem Ap...