LC 135 分发糖果 JavaScript ts

原创

思路有时间来填坑

处理好边界

前后俩值相等处,相当于一个分隔符

就可以从头开始处理

上升的话就一路往上升

下降的话就得数数一下

看看一股闹儿下降了多少了

7654321 这样

typescript 复制代码
function candy(ratings: number[]): number {
  let sum = 1;
  const len = ratings.length;
  if (len === 1) {
    return 1;
  }

  let current = 1;
  for (let i = 1; i < len; ++i) {
    // 当前的和前一个相等
    if (ratings[i - 1] === ratings[i]) {
      let j = i;
      for (; j < len; ++j) {
        sum++;
        if (j >= len - 1 || ratings[j] !== ratings[j + 1]) {
          break;
        }
      }
      i = j;
      current = 1;
    }
    // 当前比前一个大 每一个挨个直接加即可
    else if (ratings[i - 1] < ratings[i]) {
      let j = i;
      for (; j < len; ++j) {
        sum += ++current;
        if (j >= len - 1 || !(ratings[j] < ratings[j + 1])) {
          break;
        }
      }
      i = j;
    }
    // 当前比前一个小 得数数了
    else if (ratings[i - 1] > ratings[i]) {
      let j = i;
      for (; j < len; ++j) {
        if (j >= len - 1 || !(ratings[j] > ratings[j + 1])) {
          break;
        }
      }
      // 把左边处理过的减掉 这个节点需要特殊处理
      sum -= current;
      current = Math.max(current, j - i + 2);
      sum += (j - i + 1) * (2 + j - i) / 2 + current;
      i = j;
      current = 1;
    }
  }

  return sum;
};
相关推荐
小欣加油7 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
8Qi810 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
naildingding11 小时前
3-ts接口 Interface
前端·typescript
ZengLiangYi11 小时前
TypeScript 项目配置:tsconfig、ESM、路径别名
javascript·typescript·aigc
小欣加油14 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
怪兽学LLM16 小时前
LeetCode 438 找到字符串中所有字母异位词(Python 固定滑动窗口+字符计数解法)
python·算法·leetcode
Tisfy16 小时前
LeetCode 3689.最大子数组总值 I:What The Medium
算法·leetcode·题解·贪心·模拟·脑筋急转弯
moeyui70517 小时前
LeetCode 380:Insert Delete GetRandom O(1) 题解和一些延伸
算法·leetcode·职场和发展
圣保罗的大教堂17 小时前
leetcode 3689. 最大子数组总值 I 中等
leetcode
退休倒计时17 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript