This question is one of my favourites.
Suppose, the rating vectors are [4, 2, 3, 4, 1]
since, each child will at least get 1 candy. we can first initialize the vector all for 1.
if, the neighbour rating is larger than former, the child will at least have one more than the left one. --> from left to right
if, the neighbour rating is larger than the former, the child will at least have one more than the the right one ---> from right to left.
first start with [1, 1, 1, 1, 1]
after the first round (from left to right) ---> [1, 1, 2, 3, 1]
after the second round(from right to left) --> [2, 1, 2, 3, 1] ---> sum = 9
#include <vector>
#include <iostream>
using namespace std;
int candy(vector<int>& ratings) {
if(ratings.size() == 0) return 0;
int n = ratings.size();
vector<int> dp(n, 1);
for(int i = 1; i < n; ++i) {
if(ratings[i] > ratings[i - 1]) {
dp[i] = dp[i-1] + 1;
}
}
for(int i = n - 2; i >= 0; --i) {
if((ratings[i] > ratings[i + 1]) && (dp[i] <= dp[i+1])) {
dp[i] = dp[i+1] + 1;
}
}
int sum = 0;
for(int i = 0; i < n; ++i) {
sum += dp[i];
}
return sum;
}
int main(void) {
vector<int> nums{4, 2, 3, 4, 1};
cout << candy(nums) << endl;
}
Google Interview Question which is very similar to this one.
Input an array of integers, find the maximum (j-i) which A[j] > A[i], output the (i, j)
For example: [5, 2, 4, 5, 3, 8], the output is (0, 5) ; [3, 2, 1, 2, 3, 4], the output is (0, 5)
#include <iostream>
#include <vector>
using namespace std;
vector<int> maxDiffIndex(vector<int>& nums) {
int n = nums.size();
if(n < 2) return {};
vector<int> dp(n, 0);
vector<int> backward(n, 0);
for(int i = 1; i < nums.size(); ++i) {
dp[i] = (nums[i] > nums[dp[i-1]] ? dp[i-1] : i);
}
backward[n-1] = n - 1;
for(int i = n - 2; i >= 0; ++i) {
dp[i] = (nums[i] < nums[dp[i+1]] ? dp[i-1] : i);
}
int maxDiff = 0, start = 0, end = 0;
for(int i = 1; i < nums.size(); ++i) {
if(maxDiff < (dp[i] - backward[i])) {
maxDiff = abs(backward[i] - dp[i]);
start = dp[i];
end = backward[i];
}
}
if(maxDiff == 0) return {};
return {start, end};
}
本文介绍了一种糖果分配算法,确保评分较高的孩子获得更多的糖果,同时介绍了一个寻找整数数组中最大索引差的算法,该索引差满足后一个元素大于前一个元素的条件。
5万+

被折叠的 条评论
为什么被折叠?



