Analysis
- My algorithm is greedy algorithm in O(nlogn) because sort is used. Better solution O(n)can be found here
- Sort the candy list in ascending order of rating
- Scan the candy list from the lowest node to highest node.
- If the node is the biggest one among it, left adjacent node and right adjacent node, then set it candy number is 1. Otherwise if either side node's rating is smaller then its, set its candy number as the number of that node's plus 1
Note
- Define comparison function in C++
- Self defined function cmp. Note compare function cannot be a class method otherwise sort cannot invoke it