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;
};
相关推荐
Navigator_Z15 分钟前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
zhensherlock21 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
Pniubi2 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3421~3440题目解析
java·leetcode
用户2972720767852 天前
从菜单树到运行时路由:途友后台权限管理系统设计复盘
typescript
LK_073 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi3 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路3 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode