Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #include"SingleCoreSolution.h"
  2. namespace SingleCoreSolution {
  3. std::string Solution::TrickOrTreat(const std::vector<int>& pieces,
  4. const int homes, const int max) {
  5.  
  6. //calculate prefix sum;
  7. std::vector<int> prefixSum(homes + 1, 0);
  8. for (int i = 0; i < homes; ++i) {
  9. prefixSum[i + 1] = prefixSum[i] + pieces[i];
  10. }
  11.  
  12. //use two pointers
  13. int left = -1, right = 0;
  14. int maxLeftId = 0, maxRightId = 0;
  15. int maxCandy = -1;
  16.  
  17. while (right <= homes) {
  18. //shrink left
  19. do { left++; } while (left < right && prefixSum[right] - prefixSum[left] > max);
  20.  
  21. //expand right
  22. do { right++; } while (right <= homes && prefixSum[right] - prefixSum[left] <= max);
  23.  
  24. //calculate and update status
  25. int currCandy = prefixSum[right - 1] - prefixSum[left];
  26. if ((right - 1) != left && currCandy > maxCandy) {
  27. maxLeftId = left;
  28. maxRightId = right;
  29. maxCandy = currCandy;
  30. }
  31. }
  32. if (maxCandy == -1) {
  33. return "Don't go here\n";
  34. }
  35. else {
  36. return "Start at home " + std::to_string(maxLeftId + 1) +
  37. " and go to home " + std::to_string(maxRightId - 1) +
  38. " getting " + std::to_string(maxCandy) +
  39. " pieces of candy\n";
  40. }
  41. }
  42.  
  43. }//SingleCoreSolution
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement