[InterviewBit] Distribute Candy

Distribute Candy

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>

int Solution::candy(vector<int> &A) {
int n = A.size();
vector<int> dp(n,1);
for(int i = 1; i < n; i++) {
if(A[i] > A[i-1]) dp[i] = max(dp[i], dp[i-1] + 1);
}
for(int i = n - 2; i >= 0; i--) {
if(A[i] > A[i+1]) dp[i] = max(dp[i], dp[i+1] + 1);
}

return accumulate(begin(dp), end(dp), 0);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/09/PS/interviewbit/distribute-candy/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.