-
Notifications
You must be signed in to change notification settings - Fork 0
/
135.candy.44611407.ac.cpp
130 lines (116 loc) · 2.39 KB
/
135.candy.44611407.ac.cpp
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
/*
* [135] Candy
*
* https://leetcode.com/problems/candy
*
* Hard (24.52%)
* Total Accepted:
* Total Submissions:
* Testcase Example: '[0]'
*
*
* There are N children standing in a line. Each child is assigned a rating
* value.
*
*
* You are giving candies to these children subjected to the following
* requirements:
*
*
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
*
*
* What is the minimum candies you must give?
*
*/
#include<cmath>
class Solution {
public:
static inline int get_sum(int a1, int n)
{
return (n*(a1 + (a1 + n - 1))) / 2;
}
static inline int partial_process(vector<int>& ratings, int index, int& base, int& sum)
{
int inc = 0, dec = 0;
int max = 0;
if (index == ratings.size() - 1)
{
sum += base + 1;
return -1;
}
//连续相等情况[5,1,1,1],可以忽略base
if (index == 0 || ratings[index - 1] == ratings[index])
{
base = 0;
}
if (ratings[index + 1] == ratings[index])
{
sum += base + 1;
base = 0;
return index+1;
}
while(ratings[index + 1] > ratings[index])
{
inc++;
index++;
//最后的时候max是极大值
max = ++base;
sum += max;
//到达末尾了
if (index == ratings.size() - 1)
{
sum += base + 1;
break;
}
};
if (index == ratings.size() -1)
{
return -1;
}
//获得极大值
max = base + 1;
bool is_max_equal = false;
if (ratings[index] == ratings[index + 1])
{
is_max_equal = true;
}
//保证最少有一个dec
do
{
dec++;
index++;
}while(index < ratings.size() - 1 && ratings[index + 1] < ratings[index]);
if (dec >= max)
{
sum += get_sum(1, dec + 1);
}
else
{
sum += max;
sum += get_sum(1, dec);
}
//[7,8,8,7]的情况。max = 2,dec = 2,但是8 == 8,所以两个8的值可以相等,
if (dec == max && is_max_equal)
{
sum--;
}
base = 1;
if (index == ratings.size() -1)
{
return -1;
}
else
{
return index + 1;
}
}
int candy(vector<int>& ratings) {
int index = 0, base = 0, sum = 0;
while((index = partial_process(ratings, index, base, sum)) >= 0)
{
}
return sum;
}
};