aboutsummaryrefslogtreecommitdiff
path: root/other/candy.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/candy.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/candy.cpp')
-rw-r--r--other/candy.cpp37
1 files changed, 37 insertions, 0 deletions
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<int> &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<int> ratings = {};
+ cout << obj.candy(ratings);
+}