We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You have top solution!
I had same approach except one bug, and your comment inspired me to debug it instead of rewriting to left-right-left solution.
One improvement.
You can get rid of iterating forward when searching for descending sequence. For 4 descending elements you'll get 4,3,2,1 in S array, which are the same as 1,2,3,4. For descending order on each iteration add current len_of_desc_seq to total sum. And you don't need any arrays, just keep track of current descending sequesce length.
Time complexity O(N), space complexity O(1), single iteration over array.
longcandies(intn,vector<int>arr){unsignedintdescending_seq=0;unsignedlongsum=0;unsignedintprev_c=0;unsignedintprev_num_of_candies=0;for(intc:arr){if(c>=prev_c){if(descending_seq>0){// agjust local max value if descending sequence// was longer than ascendingif(descending_seq>=prev_num_of_candies){sum+=1+descending_seq-prev_num_of_candies;}// last of descending = local minimumprev_num_of_candies=1;descending_seq=0;}if(c>prev_c){++prev_num_of_candies;}else{// optimal if previous value is the sameprev_num_of_candies=1;}sum+=prev_num_of_candies;}else{++descending_seq;// For 3 descending numbers in a row this summing strategy// will increment like sum+=1+2+3 which is the same as// more usual and expected sum+=3+2+1sum+=descending_seq;}prev_c=c;}// If we finished on descending order, update last local maxif(descending_seq>=prev_num_of_candies){sum+=1+descending_seq-prev_num_of_candies;}returnsum;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Candies
You are viewing a single comment's thread. Return to all comments →
You have top solution! I had same approach except one bug, and your comment inspired me to debug it instead of rewriting to left-right-left solution.
One improvement. You can get rid of iterating forward when searching for descending sequence. For 4 descending elements you'll get 4,3,2,1 in S array, which are the same as 1,2,3,4. For descending order on each iteration add current len_of_desc_seq to total sum. And you don't need any arrays, just keep track of current descending sequesce length.
Time complexity O(N), space complexity O(1), single iteration over array.