forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete and Earn.java
28 lines (28 loc) · 942 Bytes
/
Delete and Earn.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Runtime: 19 ms (Top 27.32%) | Memory: 44.9 MB (Top 85.45%)
class Solution {
public int deleteAndEarn(int[] nums) {
Arrays.sort(nums);
int onePreviousAgo = 0;
int previous = 0;
for(int i = 0; i < nums.length; i++) {
int sum = 0;
// On hop there's no constraint to add the previous value
if(i > 0 && nums[i-1] < nums[i] - 1) {
onePreviousAgo = previous;
}
// Accumulate equal values
while(i < nums.length - 1 && nums[i] == nums[i+1]) {
sum += nums[i];
i++;
}
int currentPrevious = previous;
previous = Math.max(
onePreviousAgo + nums[i] + sum,
previous
);
onePreviousAgo = currentPrevious;
// System.out.println(nums[i] + ":" + previous);
}
return previous;
}
}