-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.cpp
More file actions
136 lines (109 loc) · 2.75 KB
/
Candy.cpp
File metadata and controls
136 lines (109 loc) · 2.75 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// class Solution {
// public:
// int candy(vector<int> &ratings) {
// int num = ratings.size();
// int m = 0;
// for (int i = 0; i < num; ++i) {
// if (ratings[i] < ratings[m]) {
// m = i;
// }
// }
// vector<int> candies(num, 1);
// int i = m;
// do {
// int p = (i - 1) % num;
// int n = (i + 1) % num;
// if (p < 0) {
// p = num - 1;
// }
// if ((i % num) != 0 && ratings[i % num] < ratings[p] && candies[i % num] >= candies[p]) {
// candies[p] = candies[i % num] + 1;
// }
// if ((i % num) != (num - 1) && ratings[i % num] < ratings[n] && candies[i % num] >= candies[n]) {
// candies[n] = candies[i % num] + 1;
// }
// ++i;
// } while ((i % num) != m);
// int result = 0;
// i = 0;
// while (i < (int)candies.size()) {
// result += candies[i];
// ++i;
// }
// return result;
// }
// };
//O(n) time and O(n) space
class Solution {
public:
int candy(vector<int> &ratings) {
int num = ratings.size();
vector<int> forward(num, 1);
for (int i = 1; i < num; ++i) {
if (ratings[i] > ratings[i - 1]) {
forward[i] = forward[i - 1] + 1;
}
}
vector<int> backward(num, 1);
for (int i = num - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
backward[i] = backward[i + 1] + 1;
}
}
int result = 0;
for (int i = 0; i < num; ++i) {
result += max(forward[i], backward[i]);
}
return result;
}
};
//O(n) time and O(1) space
class Solution {
public:
int candy(vector<int> &ratings) {
int num = ratings.size();
int result = 0;
int beforeAsce = 0;
int curDesc = 0;
int len = 0;
if (num > 0) {
result = 1;
}
for (int i = 1; i < num; ++i) {
if (ratings[i] > ratings[i - 1]) {
if (beforeAsce == 0) {
beforeAsce = 1;
}
++beforeAsce;
result += beforeAsce;
len = beforeAsce;
curDesc = 0;
}
else if (ratings[i] < ratings[i - 1]) {
if (curDesc == 0) {
curDesc = 1;
}
++curDesc;
if (len == 0) {
result += curDesc;
}
else {
if (curDesc <= len) {
result += curDesc - 1;
}
else {
result += curDesc;
}
}
beforeAsce = 0;
}
else {
++result;
beforeAsce = 0;
curDesc = 0;
len = 0;
}
}
return result;
}
};