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;
};
相关推荐
光明西道45号13 分钟前
Leetcode 15. 三数之和
数据结构·算法·leetcode
还不秃顶的计科生26 分钟前
LeetCode 热题 100第一题:两数之和python版本
python·算法·leetcode
Swift社区30 分钟前
LeetCode 462 - 最小操作次数使数组元素相等 II
算法·leetcode·职场和发展
wen__xvn1 小时前
代码随想录算法训练营DAY1第一章 数组part01
数据结构·算法·leetcode
在风中的意志1 小时前
[数据库SQL] [leetcode-175] 175. 组合两个表
数据库·sql·leetcode
圣保罗的大教堂1 小时前
leetcode 1970. 你能穿过矩阵的最后一天 困难
leetcode
造夢先森2 小时前
常见数据结构及算法
数据结构·算法·leetcode·贪心算法·动态规划
iAkuya2 小时前
(leetcode)力扣100 29删除链表的倒数第 N 个结点(双指针)
算法·leetcode·链表
没事多睡觉6662 小时前
零基础React + TypeScript 教程
前端·react.js·typescript
Binky6782 小时前
力扣--贪心(2)+动规(1)
算法·leetcode·职场和发展