|
50 | 50 | public class FruitIntoBaskets { |
51 | 51 |
|
52 | 52 | // V0 |
| 53 | + // TODO: fix below |
53 | 54 | // public int totalFruit(int[] fruits) { |
54 | 55 | // |
| 56 | +// if(fruits.length==0){ |
| 57 | +// return 0; |
| 58 | +// } |
| 59 | +// |
| 60 | +// int res = 0; |
| 61 | +// // 2 pointers |
| 62 | +// /** |
| 63 | +// * |
| 64 | +// * * -> step 1) l = 0, r = 0 |
| 65 | +// * * -> step 2) move r, if set(l, r) <= 2, keep moving r (update res) |
| 66 | +// * * -> step 3) if set(l, r) > 2, MOVE l to r-1 (update res) |
| 67 | +// * * -> step 4) keep moving r, till meets the end |
| 68 | +// * |
| 69 | +// */ |
| 70 | +// int l = 0; |
| 71 | +// int r = 0; |
| 72 | +// //Set<Integer> set = new HashSet<>(); |
| 73 | +// Map<Integer, Integer> map = new HashMap<>(); |
| 74 | +// //int cur = 1; |
| 75 | +// while (r < fruits.length){ |
| 76 | +// |
| 77 | +// map.put(fruits[r], map.getOrDefault(fruits[r],0)+1); |
| 78 | +// |
| 79 | +// while (map.keySet().size() > 2) { |
| 80 | +// // update map |
| 81 | +// map.put(l, map.get(l)-1); |
| 82 | +// if (map.get(l) == 0){ |
| 83 | +// map.remove(l); |
| 84 | +// } |
| 85 | +// // move l |
| 86 | +// l += 1; |
| 87 | +// } |
| 88 | +// |
| 89 | +// r += 1; |
| 90 | +// res = Math.max(res, r-l+1); |
| 91 | +// } |
| 92 | +// |
| 93 | +// return res; |
55 | 94 | // } |
56 | 95 |
|
| 96 | + // V0-1 |
| 97 | + // IDEA: 2 POINTERS (gpt) |
| 98 | + public int totalFruit_0_1(int[] fruits) { |
| 99 | + if (fruits.length == 0) { |
| 100 | + return 0; |
| 101 | + } |
| 102 | + |
| 103 | + int res = 0; |
| 104 | + int l = 0; // left pointer |
| 105 | + Map<Integer, Integer> fruitCount = new HashMap<>(); |
| 106 | + |
| 107 | + // Iterate with the right pointer |
| 108 | + for (int r = 0; r < fruits.length; r++) { |
| 109 | + // Add current fruit to the map and increment its count |
| 110 | + fruitCount.put(fruits[r], fruitCount.getOrDefault(fruits[r], 0) + 1); |
| 111 | + |
| 112 | + // If we have more than 2 types of fruits, move the left pointer |
| 113 | + while (fruitCount.size() > 2) { |
| 114 | + fruitCount.put(fruits[l], fruitCount.get(fruits[l]) - 1); |
| 115 | + if (fruitCount.get(fruits[l]) == 0) { |
| 116 | + fruitCount.remove(fruits[l]); |
| 117 | + } |
| 118 | + l++; // Move the left pointer |
| 119 | + } |
| 120 | + |
| 121 | + // Update the result (window size) |
| 122 | + res = Math.max(res, r - l + 1); |
| 123 | + } |
| 124 | + |
| 125 | + return res; |
| 126 | + } |
| 127 | + |
| 128 | + |
57 | 129 | // V1 |
58 | 130 | // https://leetcode.com/problems/fruit-into-baskets/solutions/3153809/clean-codes-full-explanation-hashtable-c-dd57/ |
59 | 131 | public int totalFruit_1(int[] tree) { |
|
0 commit comments