Skip to content

feat: update Java solution to lc problem: No.135 #1617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions solution/0100-0199/0135.Candy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,36 @@ class Solution {
}
```

```java
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int up = 0;
int down = 0;
int peak = 0;
int candies = 1;
for (int i = 1; i < n; i++) {
if (ratings[i - 1] < ratings[i]) {
up++;
peak = up + 1;
down = 0;
candies += peak;
} else if (ratings[i] == ratings[i - 1]) {
peak = 0;
up = 0;
down = 0;
candies++;
} else {
down++;
up = 0;
candies += down + (peak > down ? 0 : 1);
}
}
return candies;
}
}
```

### **C++**

```cpp
Expand Down
30 changes: 30 additions & 0 deletions solution/0100-0199/0135.Candy/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,36 @@ class Solution {
}
```

```java
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int up = 0;
int down = 0;
int peak = 0;
int candies = 1;
for (int i = 1; i < n; i++) {
if (ratings[i - 1] < ratings[i]) {
up++;
peak = up + 1;
down = 0;
candies += peak;
} else if (ratings[i] == ratings[i - 1]) {
peak = 0;
up = 0;
down = 0;
candies++;
} else {
down++;
up = 0;
candies += down + (peak > down ? 0 : 1);
}
}
return candies;
}
}
```

### **C++**

```cpp
Expand Down
37 changes: 20 additions & 17 deletions solution/0100-0199/0135.Candy/Solution.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
int up = 0;
int down = 0;
int peak = 0;
int candies = 1;
for (int i = 1; i < n; i++) {
if (ratings[i - 1] < ratings[i]) {
up++;
peak = up + 1;
down = 0;
candies += peak;
} else if (ratings[i] == ratings[i - 1]) {
peak = 0;
up = 0;
down = 0;
candies++;
} else {
down++;
up = 0;
candies += down + (peak > down ? 0 : 1);
}
}
for (int i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.max(left[i], right[i]);
}
return ans;
return candies;
}
}