-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcandy.cpp
More file actions
56 lines (53 loc) · 1.13 KB
/
candy.cpp
File metadata and controls
56 lines (53 loc) · 1.13 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
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int length;
vector<int> candyForChild;
vector<int> ratings;
int candy(vector<int> &ratings) {
this -> ratings = ratings;
length = ratings.size();
for(int i = 0; i < length; i++)
{
candyForChild.push_back(0);
}
int sum = 0;
for(int i = 0; i < length; i++)
{
sum += getCandy(i);
}
return sum;
}
int getCandy(int i)
{
if(candyForChild[i])
return candyForChild[i];
int a = 1;
int b = 1;
if(i != 0)
{
if(ratings[i-1] < ratings[i])
{
a = getCandy(i-1) + 1;
}
}
if(i != length - 1)
{
if(ratings[i+1] < ratings[i])
{
b = getCandy(i+1) + 1;
}
}
candyForChild[i] = a > b ? a : b;
return candyForChild[i];
}
};
int main()
{
Solution s;
int v[] = {1,2,3,4,1,2,1,2,3};
vector<int> r(begin(v), end(v));
cout << s.candy(r) << endl;
}