C++ | 90% Faster | Easy and Clean | With Best explanation
Intuition\nWe can divide this problem into 3 sub parts, that is\n1) Incresing sequence\n2) Decresing sequence\n3) Sequence with same elements\n\nFor example:\nS
# Intuition\nWe can divide this problem into 3 sub parts, that is\n1) Incresing sequence\n2) Decresing sequence\n3) Sequence with same elements\n\nFor example:\nSequence A with ratings - [1, 5, 10, 15, 20]\nwe will assign candies optimisely as [1, 2, 3, 4, 5]\n\nSequence B with ratings - [10, 5, 3, 2, 1]\nAssign candies as [5, 4, 3, 2, 1]\n\nSequence C with ratings - [5, 5, 5, 5]\nAssign candies as [1, 1, 1, 1]\n\n# Code\n```\nclass Solution {\npublic:\n    int candy(vector<int>& ratings) {\n        vector<int> count(ratings.size(), 1);\n\n        int i=0, j=0;\n        while(j < ratings.size()-1){\n            if(ratings[j] < ratings[j+1]){\n                while(j < ratings.size()-1 && ratings[j] < ratings[j+1]){\n                    j++;\n                }\n\n                int num = 1;\n\n                for(int k=i; k<=j; k++){\n                    count[k] = max(count[k], num);\n                    num++;\n                }\n\n                i = j;\n            }\n            else if(ratings[j] > ratings[j+1]){\n                while(j < ratings.size()-1 && ratings[j] > ratings[j+1]){\n                    j++;\n                }\n\n                int num = 1;\n\n                for(int k=j; k>=i; k--){\n                    count[k] = max(count[k], num);\n                    num++;\n                }\n\n                i = j;\n            }\n            else{\n                while(j < ratings.size()-1 && ratings[j] == ratings[j+1]){\n                    j++;\n                }\n\n                i = j;\n            }\n        }\n        \n\n        int ans = 0;\n        for(auto i : count){\n            ans += i;\n        }\n\n        return ans;\n    }\n};\n```
['C++']