[LeetCode] 904. Fruit Into Baskets

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.

Given the integer array fruits, return the maximum number of fruits you can pick.

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

Constraints:

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length

水果成篮。

你正在探访一家农场,农场从左到右种植了一排果树。这些树用一个整数数组 fruits 表示,其中 fruits[i] 是第 i 棵树上的水果 种类 。

你想要尽可能多地收集水果。然而,农场的主人设定了一些严格的规矩,你必须按照要求采摘水果:

你只有 两个 篮子,并且每个篮子只能装 单一类型 的水果。每个篮子能够装的水果总量没有限制。
你可以选择任意一棵树开始采摘,你必须从 每棵 树(包括开始采摘的树)上 恰好摘一个水果 。采摘的水果应当符合篮子中的水果类型。每采摘一次,你将会向右移动到下一棵树,并继续采摘。
一旦你走到某棵树前,但水果不符合篮子的水果类型,那么就必须停止采摘。
给你一个整数数组 fruits ,返回你可以收集的水果的 最大 数目。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/fruit-into-baskets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目的糖衣写的很模糊,讲的直白一点,这个题是给你一个数组,数组代表一排树,每个坐标上的值 tree[i] 代表树的类型,而不是树上果子的数量。只允许你收集两种树上的果子,每棵树上你只能拿一个果子,请问你最多能收集多少果子。所以实际问的是只能收集两种果子的情况下(只能有两种不同元素的情况下爱),如何能使你收集的这个子数组最长。返回的是能收集的最长的长度。因为这个数组的长度越长,能收集到的果子越多。比如例子三,[1,2,3,2,2],收集的是 2 和 3 两种果子,组成的最长子串的长度是 4。

思路是滑动窗口,基本可以套用 76 题的模板。这个题基本跟159题没有区别。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int totalFruit(int[] fruits) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         int left = 0;
 5         int right = 0;
 6         int res = 0;
 7         while (right < fruits.length) {
 8             map.put(fruits[right], map.getOrDefault(fruits[right], 0) + 1);
 9             right++;
10             while (map.size() > 2) {
11                 map.put(fruits[left], map.get(fruits[left]) - 1);
12                 if (map.get(fruits[left]) == 0) {
13                     map.remove(fruits[left]);
14                 }
15                 left++;
16             }
17             res = Math.max(res, right - left);
18         }
19         return res;
20     }
21 }

 

sliding window相关题目

LeetCode 题目总结

posted @ 2020-07-18 03:01  CNoodle  阅读(144)  评论(0编辑  收藏  举报