[904] 水果成篮

993 阅读1分钟
**/*
 * @lc app=leetcode.cn id=904 lang=javascript
 *
 * [904] 水果成篮
 */

// @lc code=start
/**
 * @param {number[]} fruits
 * @return {number}
 */
var totalFruit = function(fruits) {
  let j=0
  const map=new Map()
  let max = 1
  for (let i = 0; i < fruits.length; i++) {
    // 定义一个map存两种水果的index,
    map.set(fruits[i],i)
    if(map.size>2){
      // 初始化最小值为数组的长度
      let minIndex=fruits.length-1
      for (const [fruit,index] of map) {
        // 判断map的index里面是不是超过minIndex,没有超过就更新minIndex
          if(index<minIndex){
            minIndex=index
          }
      }
      // 删除map里面的index小的那种水果
      map.delete(fruits[minIndex])
      // 将j指针移动到只有一种水果的最新位置
      j=minIndex+1
    }
    // 比较两种水果连续存在的最大值
    max= Math.max(max,i-j+1)
  }
  return max
};
// @lc code=end

**