-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.cpp
More file actions
117 lines (109 loc) · 2.31 KB
/
Candy.cpp
File metadata and controls
117 lines (109 loc) · 2.31 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
// Source : https://oj.leetcode.com/problems/candy/
// Author : zheng yi xiong
// Date : 2014-12-04
/**********************************************************************************
*
* 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 "stdafx.h"
#include <vector>
using namespace std;
class CCandy {
public:
int candy(vector<int> &ratings) {
if (ratings.empty())
{
return 0;
}
int num = ratings.size();
if (1 == num)
{
return 1;
}
int candyNum = 0;
int increase_prev = 1; //递增的前一个糖果数
int decrease_count = 0; //递减的个数
int decrease_max = 0;
int equel_num = 0; //递增相等的个数
int max_equel_num = 0;
for (int i = 1; i < num; ++i)
{
if (ratings[i - 1] < ratings[i])
{
if (0 == decrease_count)
{
candyNum += increase_prev;
++increase_prev;
}
else
{
if (increase_prev > decrease_max)
{
candyNum += (increase_prev - decrease_max) * (1 - max_equel_num);
}
increase_prev = 2;
decrease_count = 0;
decrease_max = 0;
max_equel_num = 0;
}
equel_num = 0;
}
else if (ratings[i - 1] == ratings[i])
{
if (0 == decrease_count)
{
candyNum += increase_prev;
increase_prev = 1;
++equel_num;
}
else
{
candyNum += 1;
decrease_count = 1;
}
}
else
{
if (0 == decrease_count)
{
candyNum += 3;
decrease_count = 2;
decrease_max = 2;
max_equel_num = equel_num;
}
else
{
++decrease_count;
candyNum += decrease_count;
++decrease_max;
}
equel_num = 0;
}
}
if (0 == decrease_count)
{
if (ratings[num - 1] == ratings[num - 2])
{
candyNum += increase_prev;
candyNum -= equel_num * (increase_prev - 1);
}
else
{
candyNum += increase_prev;
}
}
else
{
if (increase_prev > decrease_max)
{
candyNum += (increase_prev - decrease_max) * (1 - max_equel_num);
}
}
return candyNum;
}
};