-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode135.cpp
60 lines (59 loc) · 1.58 KB
/
leetcode135.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
/*************************************************************************
> File Name: leetcode135.cpp
> Author:
> Mail:
> Created Time: Tue 16 Aug 2016 11:38:51 PM PDT
************************************************************************/
#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>
using namespace std;
/*
*初始化数组dp,数组成员均为1 ,每个孩子先分配一个糖果
从左向右遍历,如果第i个孩子比第i - 1孩子等级高,则dp[i] = dp[i - 1] + 1
从右向左遍历,如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少,则dp[i] = dp[i + 1] + 1
* */
int candy(vector<int>& ratings) {
int resultNum = 0;
vector<int> result;
for(int i = 0 ; i < ratings.size();i++)
{
result.push_back(1);
}
for(int i = 0 ; i < result.size(); i++)
{
if((i-1 >=0 )&& ratings[i] >ratings[i-1])
{
result[i] = result[i-1] +1;
}
}
for(int i = result.size()-1; i >=0;i--)
{
if((i+1<result.size())&& ratings[i]>ratings[i+1] && result[i] <= result[i+1])
{
result[i] = result[i+1] +1;
}
}
for(int i = 0 ; i < result.size(); i++)
{
// cout << result[i] << "\t";
resultNum+=result[i];
}
// cout <<endl;
return resultNum;
}
int main()
{
srand(time(0));
int count = 10;
vector<int> ratings;
for(int i = 0 ; i < count; i++)
{
int temp = rand()%10;
cout << temp << "\t";
ratings.push_back(temp);
}
cout << endl;
cout << candy(ratings) <<endl;
}