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;
};
相关推荐
Tisfy20 小时前
LeetCode 3498.字符串的反转度:一次遍历
leetcode·字符串·题解·遍历
a1879272183121 小时前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树··bfs·算法讲解·树遍历
Navigator_Z1 天前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
0+1111 天前
算法 --二分查找
c++·算法·leetcode
圣保罗的大教堂1 天前
leetcode 1674. 使数组互补的最少操作次数 中等
leetcode
kukubuzai1 天前
双指针系列二--末尾篇(3道题)
c++·算法·leetcode
圣保罗的大教堂2 天前
leetcode 835. 图像重叠 中等
leetcode
wabs6662 天前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin032 天前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
0+1112 天前
算法 --滑动窗口
c++·算法·leetcode