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;
};
相关推荐
夏鹏今天学习了吗8 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826528 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535209 小时前
力扣题目练习 换水问题
python·算法·leetcode
一匹电信狗9 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
liangshanbo12159 小时前
React + TypeScript 企业级编码规范指南
ubuntu·react.js·typescript
·白小白11 小时前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
仰泳的熊猫11 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode
水冗水孚11 小时前
双指针算法在实际开发中的具体应用之代码Review文章字符串的片段分割
算法·leetcode
Qiuner12 小时前
《掰开揉碎讲编程-长篇》重生之哈希表易如放掌
数据结构·算法·leetcode·力扣·哈希算法·哈希·一文读懂
缓风浪起14 小时前
【力扣】2011. 执行操作后的变量值
算法·leetcode·职场和发展