DP + Prefix Sums
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires a beautiful prefix optimization to avoid calculating the sum again
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires a beautiful prefix optimization to avoid calculating the sum again and again. Otherwise it\'s same as simpler version!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N * M)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N * M)$$\n\n# Code\n```\nclass Solution {\npublic:\n    int countOfPairs(vector<int>& v) {\n        int n = v.size();\n\n        vector<vector<int>> dp(n, vector<int>(1001, 0));\n        for(int i = 0; i < 1001; i++) {\n            if(i > v[0]) break;\n            dp[0][i] = 1;\n        }\n\n        for(int i = 1; i < n; i++) {\n            // storing prefix to avoid re-calculations\n            vector<int> pref(1001, dp[i - 1][0]);\n            for(int k = 1; k < 1001; k++) {\n                pref[k] = pref[k - 1] + dp[i - 1][k];\n                pref[k] = pref[k] % (1000000007);\n            }\n            \n            for(int j = 0; j <= v[i]; j++) {\n                int t = v[i - 1] - v[i] + j;\n                if(min(t , j) < 0) continue;\n                dp[i][j] += pref[min(t , j)];\n                dp[i][j] = dp[i][j] % (1000000007);\n            }\n        }\n        \n        int ans = 0;\n        for(int i = 0; i < 1001; i++) {\n           ans += dp[n - 1][i];\n           ans = ans % (1000000007);\n        }\n        \n        return ans;\n        \n    }\n};\n```
['C++']