From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/candy.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 other/candy.cpp (limited to 'other/candy.cpp') diff --git a/other/candy.cpp b/other/candy.cpp new file mode 100644 index 0000000..83915b0 --- /dev/null +++ b/other/candy.cpp @@ -0,0 +1,37 @@ +#include "leetcode.h" + +class Solution { +public: + int candy(vector &ratings) { + if (ratings.size() <= 1) + return ratings.size(); + int ans = 0, up = 0, down = 0, oldSign = 0; + for (int i = 1; i < ratings.size(); i++) { + int newSign = ratings[i] > ratings[i - 1] ? 1 + : ratings[i] < ratings[i - 1] ? -1 + : 0; + if ((oldSign > 0 && newSign == 0) || (oldSign < 0 && newSign >= 0)) { + ans += helper(up) + helper(down) + max(up, down); + up = 0; + down = 0; + } + if (newSign > 0) + up++; + if (newSign < 0) + down++; + if (newSign == 0) + ans++; + oldSign = newSign; + } + ans += ramp(up) + ramp(down) + max(up, down) + 1; + } + +private: + int helper(int n) { return (n * (n + 1)) / 2; } +}; + +int main() { + Solution obj; + vector ratings = {}; + cout << obj.candy(ratings); +} -- cgit v1.2.3