-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcandyDistribution.cpp
More file actions
65 lines (53 loc) · 1.88 KB
/
candyDistribution.cpp
File metadata and controls
65 lines (53 loc) · 1.88 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public:
int candy2P(vector<int>& ratings) {
int len = ratings.size();
if(!len) return 0;
if(len == 1) return 1;
vector<int> candyValues(len);
candyValues[0] =1;
for(int i =1; i< len; i++ ){
if(ratings[i]> ratings[i-1]){
candyValues[i] +=candyValues[i-1] + 1;
}
else{
candyValues[i] = 1;
}
}
int res = candyValues[len-1];
for(int i = len-2; i>=0; i--){
if(ratings[i] > ratings[i+1] && (candyValues[i] <= candyValues[i+1] )){
candyValues[i] = candyValues[i+1] + 1;
}
res += candyValues[i];
}
return res;
}
//In One Pass
int candy(vector<int>& ratings) {
int len = ratings.size();
if(len<=1) return len;
int prev =1, countDown =0;
int total = 1;
for(int i =1; i<len; i++){
if(ratings[i] >= ratings[i-1]){
if(countDown > 0){
total += countDown * (countDown+1) / 2; // total series sum while next is decreased ratings
if(countDown >= prev) total += countDown - prev + 1;
countDown =0;
prev = 1;
}
prev = ratings[i] == ratings[i-1]? 1 : prev+1;
total += prev;
}
else{
countDown++;
}
}
if(countDown >0){
total += countDown * (countDown+1) / 2; // total series sum while next is decreased ratings
if(countDown >= prev) total += countDown - prev + 1;
}
return total;
}
};