nikunjsoni

1894

Jun 13th, 2021 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. O(n) solution
  2. class Solution {
  3. public:
  4.     int chalkReplacer(vector<int>& chalk, int k) {
  5.         k %= accumulate(begin(chalk), end(chalk), 0l);
  6.         for(int i = 0; i < chalk.size(); ++i)
  7.             if((k -= chalk[i]) < 0)
  8.                 return i;
  9.         return 0;
  10.     }
  11. };
  12.  
  13. -----------
  14. O(n) solution
  15.  
  16. class Solution {
  17. public:
  18.     int chalkReplacer(vector<int>& c, int k) {
  19.         long long n = c.size();
  20.         vector<long long> chalk(n);
  21.         chalk[0] = c[0];
  22.         for(int i=1; i<chalk.size(); i++)
  23.             chalk[i] = chalk[i-1]+c[i];
  24.         k = k%chalk[n-1];
  25.         if(k == 0) return 0;
  26.         int pos = upper_bound(chalk.begin(), chalk.end(), k)-chalk.begin();
  27.         return pos;
  28.     }
  29. };
Add Comment
Please, Sign In to add comment