友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

904. Fruit Into Baskets

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

  1. Add one piece of fruit from this tree to your baskets. If you cannot, stop.

  2. Move to the next tree to the right of the current tree. If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].

Example 2:

Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:

Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

  1. 1 <= tree.length <= 40000

  2. 0 <= tree[i] \< tree.length

思路分析

 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
28
29
30
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-27 15:33:58
 */
public int totalFruit(int[] fruits) {
  int result = 0;
  int head = 0, tail = 0;
  Map<Integer, Integer> fruitToCntMap = new HashMap<>();
  while (head < fruits.length) {
    int f1 = fruits[head];
    head++;
    Integer cnt = fruitToCntMap.getOrDefault(f1, 0);
    fruitToCntMap.put(f1, cnt + 1);
    if (fruitToCntMap.size() <= 2) {
      result = Math.max(result, head - tail);
    } else {
      while (tail < head && fruitToCntMap.size() > 2) {
        int f2 = fruits[tail];
        Integer c2 = fruitToCntMap.get(f2);
        if (c2 >1) {
          fruitToCntMap.put(f2, c2 - 1);
        }else {
          fruitToCntMap.remove(f2);
        }
        tail++;
      }
    }
  }
  return result;
}