tygarian

arithmetic slices leetcode

Mar 2nd, 2022
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. class Solution {
  2. public:
  3. // Time Complexity:- O(N)
  4. // Space Complexity:- O(N)
  5. int numberOfArithmeticSlices(vector<int>& nums) {
  6. int n = nums.size();
  7.  
  8. // dp[i] = number of arithmetic subarrays ending at index i
  9. vector<int> dp(n+1);
  10.  
  11. for(int i=2;i<n;i++){
  12. // if the three element difference is same, extend the subarray
  13. if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){
  14. dp[i] = 1 + dp[i-1];
  15. }
  16. }
  17.  
  18. return accumulate(dp.begin(),dp.end(),0);
  19. }
  20. };
Add Comment
Please, Sign In to add comment