Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- // Time Complexity:- O(N)
- // Space Complexity:- O(N)
- int numberOfArithmeticSlices(vector<int>& nums) {
- int n = nums.size();
- // dp[i] = number of arithmetic subarrays ending at index i
- vector<int> dp(n+1);
- for(int i=2;i<n;i++){
- // if the three element difference is same, extend the subarray
- if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){
- dp[i] = 1 + dp[i-1];
- }
- }
- return accumulate(dp.begin(),dp.end(),0);
- }
- };
Add Comment
Please, Sign In to add comment