Easy Explanation | Tabulation | Commented Code
Code\n\nclass Solution {\npublic:\n\n    int mod = 1e9 + 7 ;\n\n    int countOfPairs(vector<int>& nums) {\n\n        // initialize n and 2D dp \n        // dp[i
# Code\n```\nclass Solution {\npublic:\n\n    int mod = 1e9 + 7 ;\n\n    int countOfPairs(vector<int>& nums) {\n\n        // initialize n and 2D dp \n        // dp[i][j] -> No of ways of generating array till index i having a[i] = j  \n        // answer will be summation of dp[n-1][j]  where  0 <= j <= 1000 \n        int n = nums.size() ;\n        int dp[n+1][1001], pref[n+1][1001] ;\n        memset(dp,0,sizeof(dp)) ;\n        memset(pref,0,sizeof(pref)) ;\n\n        // for the 0 index for every j <= nums[0] the dp[0][j] will be 1 as there is 1 way\n        for(int j = 0 ; j <= nums[0] ; j++ ){\n            dp[0][j] = 1 ;\n            pref[0][j] = dp[0][j] + ( j ? pref[0][j-1] : 0 ) ;\n        } \n        \n        /* now iterating over the index of array for every index, iterating over every possible\n        value of a that is  0 <= a <= nums[i], calculate b = nums[i] - a.\n        Now check for every possible value of prev_a. Two condition to be hold \n        1) 0 <= prev_a <= nums[i-1] \n        2) prev_a <= a\n\n        Intersection Of Both :  0 <= prev_a <= min( a, nums[i-1] ) ;\n        Now calculte prev_b = nums[i-1] - prev_a and check for conditon that prev_b >= b \n\n        as prev_a is increasing so prev_b will be decreasing  if at any moment prev_b < b then break \n        else add dp[i-1][prev_a] to ways \n\n        dp[i][prev_a] = ways ;\n\n        Mathametical computation :\n        -> prev_b < b \n        -> nums[i-1] - prev_a < nums[i] - a \n        -> prev_a >  a - ( nums[i] - nums[i-1] ) \n        -> 0 <= prev_a <= min(a, nums[i-1], a - ( nums[i] - nums[i-1] ) ) ;\n        Now we are adding for every prev_a from a to this so compute this earlier \n        */\n        \n        for(int i = 1 ; i < n ; i++ ){\n            for(int a = 0 ; a <= nums[i] ; a++ ){\n                int b = nums[i] - a ;\n                int ways = 0 ;\n\n                // for(int prev_a = 0 ; prev_a <= min(a, nums[i-1]) ; prev_a++ ){\n                //     int prev_b = nums[i-1] - prev_a ;\n                //     if(prev_b < b ) break ;\n                //     ways = (ways + dp[i-1][prev_a] ) % mod ;\n                // }\n\n                int prev_a = min( a, min( nums[i-1], a - ( nums[i] - nums[i-1] ))) ;\n\n                ways =  ( prev_a<0 ? 0 : pref[i-1][prev_a] ); \n                dp[i][a] = ways ; \n                pref[i][a] = ( dp[i][a] + ( a ? pref[i][a-1] : 0 ) ) % mod  ;\n            }\n        }\n\n        int res = 0 ; \n        for(int i = 0 ; i <= 1000 ; i++ ){\n            res = (res + dp[n-1][i] ) % mod ;\n        }\n        return res ;\n    }\n};\n```
['C++']