1. 程式人生 > >LeetCode135. Candy (貪心)

LeetCode135. Candy (貪心)

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

幾種情況觀察
輸入[2, 4, 6 ,8 ], 輸出序列為[1, 2, 3, 4]
輸入[8, 6, 4, 2], 輸出序列為[4, 3, 2, 1]
輸入[2, 4, 6, 8, 6, 4], 輸出序列為[1, 2, 3, 4, 2, 1]
輸入[2, 4, 6, 8, 6, 4, 2, 0], 輸出序列為[1, 2, 3, 5, 4, 3, 2, 1]
輸入[2,4, 6, 8, 8, 8, 6, 4,], 輸出序列為[1, 2, 3, 4, 1, 3, 2, 1]

特殊情況的考慮
如只有一個元素,返回1;
所有元素都一致,返回全1;

模擬上過程

class Solution
{ public: int candy(vector<int>& arr) { int n = arr.size(); if(n==0) return 0; if(n==1) return 1; vector<int> sum(n+1, 0); for(int i=0;i+1<n;) { if(arr[i+1]==arr[i]) { if(i==0) sum[0]=1; // 重點:否則過不了開始就連續相同元素的樣例 i++; sum[i]=1; continue; } int j,k; for(j=i;j+1<n&&arr[j+1]>arr[j];j++); for(k=i;k+1<n&&arr[k+1]<arr[k];k++); if(j!=i) { sum[i]=1; for(int t=i+1;t<=j;t++) sum[t]=sum[t-1]+1; i=j; } else if(i!=k) { int len = k-i+1; if(sum[i]<len) sum[i]=len; sum[i+1]=len-1; for(int t=i+2;t<=k;t++) sum[t]=sum[t-1]-1; i=k; } } int ans=0; for(int i=0;i<n;i++) ans+=sum[i]; return ans; } };