question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-total-damage-with-spell-casting | Neat comprehensible efficient solution | neat-comprehensible-efficient-solution-b-d164 | IntuitionApproachComplexity
Time complexity: O(n log n)
Space complexity: O(n)
Code | shmirrakhimov | NORMAL | 2025-03-23T17:01:58.084387+00:00 | 2025-03-23T17:01:58.084387+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n log n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} power
* @return {number}
*/
var maximumTotalDamage = function(power) {
power.sort((a, b) => a - b);
let setSum = {};
let set = [];
for(let num of power) setSum[num] = (setSum[num] || 0) + num;
for(let num of power) if(!set.length || set[set.length - 1] != num) set.push(num);
let maximum = 0;
for(let i = 0; i < set.length; i++){
let max = 0;
let j = i - 1;
while(j > -1 && set[j] + 2 >= set[i]) j--;
if(set[j]) { max = Math.max(max, setSum[set[j]]); j--; }
if(set[j]) { max = Math.max(max, setSum[set[j]]); j--; }
if(set[j]) { max = Math.max(max, setSum[set[j]]); j--; }
setSum[set[i]] += max;
if(setSum[set[i]] > maximum) maximum = setSum[set[i]];
}
return maximum;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
maximum-total-damage-with-spell-casting | O(Nlog(N)) sort and traverse | onlogn-sort-and-traverse-by-awuxiaoqi-4iz2 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | labao | NORMAL | 2025-03-06T16:40:52.587752+00:00 | 2025-03-06T16:40:52.587752+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public long maximumTotalDamage(int[] power) {
Arrays.sort(power);
return helper(power, 0, new Long[power.length]);
}
public long helper(int[] power, int index, Long[] memo) {
if (index >= power.length || index == -1) {
return 0;
}
if (memo[index] != null) return memo[index];
long res = 0;
int nextIndex = -1;
int nextDifferentIndex = -1;
long currPow = power[index];
for (int i = index + 1; i < power.length; ++i) {
if (power[i] == power[index]) {
currPow += (long)power[i];
} else {
if (nextDifferentIndex == -1){
nextDifferentIndex = i;
}
if (power[i] > power[index] + 2) {
nextIndex = i;
break;
}
}
}
res = currPow + helper(power, nextIndex, memo);
if (nextDifferentIndex != nextIndex) {
res = Math.max(res, helper(power, nextDifferentIndex, memo));
}
memo[index] = res;
return res;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | Maximum Total Damage with Spell Casting | maximum-total-damage-with-spell-casting-s82js | Code | _jyoti_geek | NORMAL | 2025-02-17T06:35:33.402610+00:00 | 2025-02-17T06:35:33.402610+00:00 | 8 | false | # Code
```java []
class Solution {
public long maximumTotalDamage(int[] arr) {
Arrays.sort(arr);
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
long[] dp = new long[arr.length];
Arrays.fill(dp, -1);
return helper(arr, 0, map, dp);
}
public long helper(int[] arr, int idx, HashMap<Integer, Integer> map, long[] dp) {
if (idx >= arr.length) {
return 0;
}
if(dp[idx]!=-1){
return dp[idx];
}
long c1 = (long)arr[idx] * map.get(arr[idx]);
int i = idx + map.get(arr[idx]);
long c2 = helper(arr, i, map, dp);
if (map.containsKey(arr[idx] + 2)) {
i += map.get(arr[idx] + 2);
}
if (map.containsKey(arr[idx] + 1)) {
i += map.get(arr[idx] + 1);
}
c1 += helper(arr, i, map, dp);
return dp[idx] = Math.max(c1, c2);
}
}
``` | 0 | 0 | ['Array', 'Hash Table', 'Two Pointers', 'Dynamic Programming', 'Sorting', 'Java'] | 0 |
maximum-total-damage-with-spell-casting | Easy to understand DP java | easy-to-understand-dp-java-by-zpw1337-spyo | IntuitionSort the input list into key value pairs, where key is the spell power, and value is its occurences.let dp[k] denote most power casting only from first | zpw1337 | NORMAL | 2025-02-13T00:45:39.706654+00:00 | 2025-02-13T00:45:39.706654+00:00 | 5 | false | # Intuition
Sort the input list into key value pairs, where key is the spell power, and value is its occurences.
let dp[k] denote most power casting only from first k spells with unique power.
Then we build dp from 0 to n-1.
At each step, we can choose current spell or not.
If we don't, we try to find the best answer from dp[k-1], dp[k-2], dp[k-3]. Anything beyond k-3 will not be more optimal
If we do pick the current spell, we need find from k-1, k-2, and k-3, for the spell that is more than 2 power under current, in that order
The code doesn't necessearrily check for k-2 and k-3, because if k-1 is more than 2 under, k-2 and k-3 will be less or equally optimal.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(nlogn)
- Space complexity:
O(n)
# Code
```java []
class Solution {
public long maximumTotalDamage(int[] power) {
Map<Integer, Integer> map = new TreeMap<>();
for (int p: power)
map.put(p, map.getOrDefault(p, 0) + 1);
int n = map.size();
long dp[] = new long[n];
Integer[] keys = map.keySet().toArray(Integer[]::new);
Integer[] values = map.values().toArray(Integer[]::new);
for (int i = 0; i < n; i++) {
long val = (long)keys[i]*values[i];
dp[i] = val;
if (i > 0) {
if (keys[i] - keys[i-1] > 2) {
dp[i] = val + dp[i-1];
continue;
}
dp[i] = Math.max(dp[i-1], dp[i]);
}
if (i > 1) {
if (keys[i] - keys[i-2] > 2) {
dp[i] = Math.max(val + dp[i-2], dp[i]);
continue;
}
dp[i] = Math.max(dp[i-2], dp[i]);
}
if (i > 2) {
dp[i] = Math.max(dp[i], val + dp[i-3]);
}
}
// System.out.println(Arrays.toString(power));
// System.out.println(Arrays.toString(keys));
// System.out.println(Arrays.toString(values));
// System.out.println(Arrays.toString(dp));
return dp[n-1];
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | 79 ms Beats 93.56% DP | 79-ms-beats-9356-dp-by-dinhson-nguyen-9cv4 | IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
Code | sondinh1701_ | NORMAL | 2025-02-10T08:44:54.481911+00:00 | 2025-02-10T08:44:54.481911+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long maximumTotalDamage(vector<int>& power) {
int n = power.size();
sort(power.begin(),power.end());
int p = 0;
int l = 1;
vector<long long> dp(n+1,0);
dp[0] = power[0];
if ( p < n-1 && power[p+1] <= power[0] + 2 ) {
while ( p < n-1 && power[p+1] <= power[0] + 2) {
if (power[p+1] == power[p]) {
l++;
dp[p+1] = max(dp[max(p+2-l,0)],1LL * l * power[p]);
} else {
dp[p+1] = max(dp[p], 0LL + power[p+1]);
l = 1;
}
p++;
}
}
int j = 0;
int t = 1;
for(int i = p+1; i < n; i++) {
if (power[j] < power[i]-2 ) {
while ( power[j] < power[i]-2 ) j++;
j--;
}
if (power[i] == power[i-1]) {
t++;
dp[i] = max(1LL *t*power[i-1] + dp[j], dp[i-1]);
}
else {
dp[i] = max(0LL + power[i] + dp[j],dp[i-1]);
t = 1;
}
}
return dp[n-1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Sorting + 2 Pointers | sorting-2-pointers-by-yelleti-18-08av | IntuitionApproachComplexity
Time complexity:O(n∗logn)
Space complexity:O(n)
Code | yelleti-18 | NORMAL | 2025-01-29T13:24:28.270357+00:00 | 2025-01-29T13:24:28.270357+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:$$O(n*logn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
using ll = long long;
using pii = pair<int,int>;
long long maximumTotalDamage(vector<int>& pw) {
map<int,int> mp;
for(auto i: pw)
mp[i]++;
vector<pii> ve(mp.begin(),mp.end());
int n=ve.size();
vector<ll> dp(n,0);
int s=-1,e=0;
ll mxs=0;
while(e<n){
while(s+1<e && ve[s+1].first<ve[e].first-2){
s++;
mxs=max(mxs,dp[s]);
}
dp[e]=((ll)ve[e].second*ve[e].first)+mxs;
//if(s>=0) dp[e]+=dp[s];
e++;
}
// for(auto i: dp) cout<<i<<" ";
return *max_element(dp.begin(),dp.end());
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | scala greedy oneliner | scala-greedy-oneliner-by-vititov-p0fc | null | vititov | NORMAL | 2025-01-28T00:59:40.532534+00:00 | 2025-01-28T00:59:40.532534+00:00 | 5 | false | ```scala []
object Solution {
import scala.util.chaining._
def maximumTotalDamage(power: Array[Int]): Long =
power.groupMapReduce(_.toLong)(_ => 1L)(_ + _).to(List).sorted.iterator
.foldLeft(Map(-3L -> 0L)){ case (aMap,(p,cnt)) =>
aMap.iterator.filter{case (k,_) => k+2<p}.maxBy(_._2)
.pipe{case mx@(_,v3) => aMap.filter{case (k,_) => k+2>=p} ++ Iterator(mx, (p, v3+p*cnt))}
}.values.maxOption.getOrElse(0L)
}
``` | 0 | 0 | ['Hash Table', 'Greedy', 'Sorting', 'Scala'] | 0 |
maximum-total-damage-with-spell-casting | Simple Solution O(NlogN) | simple-solution-onlogn-by-kush-sahu-ud3a | IntuitionApproachComplexity
Time complexity:O(NlogN)
Space complexity:O(N)
Code | kush-sahu | NORMAL | 2025-01-19T21:31:21.975046+00:00 | 2025-01-19T21:31:21.975046+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(NlogN)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public long maximumTotalDamage(int[] power) {
HashMap<Integer,Long>hm=new HashMap<>();
List<Integer>list=new ArrayList<>();
for(int i=0;i<power.length;i++){
if(hm.containsKey(power[i])==false){
list.add(power[i]);
}
hm.put(power[i],hm.getOrDefault(power[i],0l)+1);
}
Collections.sort(list);
long dp[]=new long[list.size()];
dp[0]=list.get(0)*hm.get(list.get(0));
for(int i=1;i<list.size();i++){
int current=list.get(i);
dp[i]=dp[i-1];
int j=i-1;
while(j>=0 && list.get(j)>=current-2)j--;
if(j>=0){
dp[i]=Math.max(dp[i],dp[j]+current*hm.get(current));
}else{
dp[i]=Math.max(dp[i],current*hm.get(current));
}
}
return dp[dp.length-1];
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | Best Solution Ever || Think Bottom-Up || Easiest Explanation || Easiest Implementation || | best-solution-ever-think-bottom-up-easie-82c6 | IntuitionCode | krishna_6431 | NORMAL | 2025-01-18T18:55:06.663780+00:00 | 2025-01-18T18:55:06.663780+00:00 | 3 | false | # Intuition
https://youtu.be/z14TI29ATQ0
# Code
```cpp []
using ll = long long;
class Solution {
public:
long long maximumTotalDamage(vector<int>& nums) {
map<ll,ll>dp;
map<ll,ll>mp;
for(auto x : nums){
mp[x]++;
}
// for(auto y : mp){
// cout << y.first << " " << y.second << endl;
// }
ll ans = 0;
for(auto [x,y] : mp){
dp[x] = x * y;
auto itr = dp.upper_bound(x - 3);
if(itr != dp.begin()){
dp[x] = max(dp[x], prev(itr)->second + x*y);
}
itr = dp.find(x);
if(itr != dp.begin()){
dp[x] = max(dp[x],prev(itr)->second);
}
ans = max(ans, dp[x]);
}
// cout << "***" << endl;
// for(auto x : dp){
// cout << x.first << " " << x.second << endl;
// }
return ans;
}
};
``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Dynamic Programming and Binary Search | dynamic-programming-and-binary-search-by-qz1q | IntuitionApproachBinary Search and Dynamic ProgrammingComplexity
Time complexity: O(nlogn)
Space complexity: O(n)
Code | Akash-96 | NORMAL | 2024-12-30T07:05:24.857715+00:00 | 2024-12-30T07:05:24.857715+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
Binary Search and Dynamic Programming
# Complexity
- Time complexity: O(nlogn)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int upperBound(vector<int> &arr, int x, int n) {
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] > x) {
ans = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}
return ans;
}
long long solve(vector<int> &arr, int i, vector<long long>& dp)
{
if(i >= arr.size())
{
return 0;
}
if(dp[i]!=-1)
return dp[i];
long long currValue = arr[i];
long long currSum = 0;
int c=upperBound(arr, currValue, arr.size());
currSum=(long long)(arr[i]*(long long)(c-i));
int up=upperBound(arr, currValue+2, arr.size());
return dp[i]=max(currSum + solve(arr, up, dp), solve(arr, i+1, dp));
}
long long maximumTotalDamage(vector<int>& arr) {
int n = arr.size();
vector<long long> dp(arr.size()+1,-1);
sort(arr.begin(), arr.end());
return solve(arr, 0, dp);
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Easy C++ Solution | Must SEE | Hash Table | easy-c-solution-must-see-hash-table-by-n-o3wb | Code | NehaGupta_09 | NORMAL | 2024-12-15T10:56:10.707876+00:00 | 2024-12-15T10:56:10.707876+00:00 | 3 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n unordered_map<int,vector<int>>mp;\n vector<long long>dp;\n long long maximumTotalDamage(vector<int>& power) {\n dp.resize(power.size(),-1);\n sort(power.begin(),power.end());\n int i=0;\n while(i<power.size()){\n int ele=power[i];\n int start=i;\n int end;\n while(i<power.size() and power[i]==ele){\n end=i;\n i++;\n }\n mp[ele]={start,end};\n }\n return fun(power,0);\n }\n long long fun(vector<int>&arr,int idx){\n if(idx>=arr.size()){\n return 0;\n }\n if(dp[idx]!=-1){\n return dp[idx];\n }\n long long c1=0;\n long long c2=0;\n //take choice\n c1=(arr[idx]*1LL*(mp[arr[idx]][1]-mp[arr[idx]][0]+1))+fun(arr,get_idx(arr[idx]));\n c2=fun(arr,idx+1);\n return dp[idx]=max(c1,c2);\n }\n int get_idx(int power){\n if(mp.find(power+2)!=mp.end()){\n return mp[power+2][1]+1;\n }\n else if(mp.find(power+1)!=mp.end()){\n return mp[power+1][1]+1;\n }\n return mp[power][1]+1;\n }\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'Dynamic Programming', 'Sorting', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Use priority_queue(max heap) after sorting | use-priority_queuemax-heap-after-sorting-kq5q | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst sort the array then use a max heap [sum, -biggest number];\nIn each iteration fir | zsnwd | NORMAL | 2024-12-06T06:58:26.817461+00:00 | 2024-12-06T06:58:26.817503+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst sort the array then use a max heap [sum, -biggest number];\nIn each iteration first pop the potentially invalid nodes;\nThen get the max sum for the current number(deduplicatoin included).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n# Code\n```cpp []\nstruct Comp {\n bool operator()(const vector<long long>& a, const vector<long long>& b) {\n return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; // Maxheap\n }\n};\n\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(), power.end()); // necessary?\n priority_queue<vector<long long>, vector<vector<long long>>, Comp> q;\n int i = 0;\n int n = power.size();\n vector<vector<long long>> b; // backup\n long long a = 0;\n while (i < n) {\n int j = i;\n while (i + 1 < n and power[i + 1] == power[i]) i++;\n int cnt = i - j + 1; // count the num in case of any duplicate numbers\n\n while (!q.empty() && (-q.top()[1] == power[i] - 1 || -q.top()[1] == power[i] - 2)) {\n // cant have -1 and -2 according to the rule\n b.push_back(q.top());\n q.pop();\n // b.push_back(q.pop()); can\'t do this?! why??\n }\n\n long long newMax = 1LL * cnt * power[i]; // 100000 * 1000000000\n newMax += q.empty() ? 0 : q.top()[0]; \n\n q.push({newMax, -power[i]});\n a = max(a, newMax);\n\n while (!b.empty()) {\n // push back the invlid elements\n q.push(b.back());\n b.pop_back();\n }\n\n i++;\n }\n return a;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Two Intuitive DP Approaches, beats 90% | two-intuitive-dp-approaches-beats-90-by-e221n | Approach 1: Overkill DP -> Memory Limit Exceeded\nPerform dynamic programming over all possible power caps p_cap in the range $[0, \max(\text{powers})]$; this i | PeterFavero | NORMAL | 2024-12-03T01:27:09.694157+00:00 | 2024-12-03T01:27:09.694179+00:00 | 11 | false | # Approach 1: Overkill DP -> Memory Limit Exceeded\nPerform dynamic programming over all possible power caps `p_cap` in the range $[0, \\max(\\text{powers})]$; this is innefficient and exceeds memory limitations because the only power caps that matter are the unique spell powers in the `powers`.\n\nTime Complexity: $O(N\\log(N) + \\max(\\text{powers}))$\nSpace Complexity: $O(\\max(\\text{powers}))$\n\n```python3 []\nclass Solution:\n def maximumTotalDamage(self, powers: List[int]) -> int:\n\n # Linear DP approach: Memory Limit Exceeded exception\n\n i_powers = 0\n n_powers = len(powers)\n \n powers.sort()\n MAX_P = powers[-1]\n\n dp = [-1] * (MAX_P+1)\n dp[0] = 0\n\n # print(powers)\n # print()\n # print(0, dp)\n\n for p_cap in range(1,MAX_P+1):\n\n dp[p_cap] = dp[p_cap-1]\n\n if p_cap == powers[i_powers]:\n total = dp[max(p_cap-3,0)]\n while i_powers < n_powers and powers[i_powers] == p_cap:\n total += p_cap\n i_powers += 1\n \n dp[p_cap] = max(total, dp[p_cap])\n\n # print(p_cap, dp)\n\n return dp[-1] \n```\n\n# Approach 2: Optimal DP -> Beats 90%\nPerform dynamic programming over all unique spell power values in the `powers` array as the power cap `p_cap`. This is efficient as we iterate only over the elements where the wizard has a choice point, and thus avoid needless computation.\n\nTime Complexity: $O(N\\log(N))$\nSpace Complexity: $O(N)$\n\n```python3 []\nclass Solution:\n def maximumTotalDamage(self, powers: List[int]) -> int:\n\n # Minimalistic DP\n \n powers.sort()\n\n # dp[i] is (ith p_cap, maximum damage under ith p_cap), \n dp = [(-2,0), (-1,0), (0,0)] # extra values added to avoid going out of bounds\n\n # print(powers)\n # print()\n # print(0, dp)\n\n run_len = 1\n run_p = powers[0]\n i_powers = 1\n n_powers = len(powers)\n while i_powers < n_powers:\n \n if run_p == powers[i_powers]:\n # continue current run\n run_len += 1\n else:\n # completec current run\n p_cap = run_p\n dmg_use = run_p*run_len + (dp[-1][1] if dp[-1][0] < p_cap-2 else dp[-2][1] if dp[-2][0] < p_cap-2 else dp[-3][1])\n dmg_skip = dp[-1][1]\n dmg_max = max(dmg_use, dmg_skip)\n dp.append((p_cap, dmg_max))\n # print(p_cap, dp)\n\n # start next run\n run_p = powers[i_powers]\n run_len = 1\n\n i_powers += 1 # advance to next iteration\n\n # complete last run\n p_cap = run_p\n dmg_use = run_p*run_len + (dp[-1][1] if dp[-1][0] < p_cap-2 else dp[-2][1] if dp[-2][0] < p_cap-2 else dp[-3][1])\n dmg_skip = dp[-1][1]\n dmg_max = max(dmg_use, dmg_skip)\n dp.append((p_cap, dmg_max))\n # print(p_cap, dp)\n\n return dp[-1][1] \n``` | 0 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | 1D DP | 1d-dp-by-mohith_jain-76yc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | mohith_jain | NORMAL | 2024-11-21T13:16:18.420711+00:00 | 2024-11-21T13:16:18.420745+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n long sum = 0;\n Arrays.sort(power);\n long[] ans = new long[power.length+1];\n //int[] right = new int[power.length];\n ans[0] = power[0];\n for (int i=0; i<power.length; i++) {\n int temp = i-1;\n if (temp >= 0 && power[i] == power[temp]) {\n ans[i+1] = ans[i];\n continue;\n }\n while (temp >= 0 && power[temp] != power[i] && power[temp] >= power[i]-2) {\n temp--;\n }\n int temp2 = i+1;\n long count=1;\n while (temp2 < power.length && power[temp2] == power[i]) {\n count++;\n temp2++;\n }\n //if (temp > 0)\n //System.out.println("Temp is " + power[temp] + " for i" + power[i]);\n long prev = temp < 0 ? 0 : ans[temp+1];\n ans[i+1] = Math.max(ans[i], power[i]*count + prev);\n }\n // for (int i=0; i<power.length; i++) {\n // System.out.print(ans[i] + " ");\n // }\n return ans[power.length];\n\n\n\n }\n\n\n\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | Sort and DP | sort-and-dp-by-lambdacode-dev-dcyn | Intuition\n- Sort and then consider each spell with increasing power. \n- Of all choice history (with combinatorial count) made so far, the effective states are | lambdacode-dev | NORMAL | 2024-11-11T16:19:34.856407+00:00 | 2024-11-11T16:19:34.856468+00:00 | 2 | false | # Intuition\n- Sort and then consider each spell with increasing power. \n- Of all choice history (with combinatorial count) made so far, the effective states are polynomial, because only the largest power spell matter for future choices.\n- Only maixmum 3 such states are needed due to the specific constraints.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n map<int,int> freq;\n for(auto p : power) freq[p]++;\n\n struct State {int p; long long d; }; // damage d if the largest spell has power p so far\n State dp[] = { {-4,0LL}, {-3, 0LL}, {-2, 0LL} };\n for(auto [p,f] : freq) {\n long long d = 0;\n for(int i = 0; i < 3; ++i)\n if(abs(dp[i].p - p) > 2) \n d = max(d, dp[i].d + static_cast<long long>(p)*f);\n\n dp[0] = dp[1];\n dp[1] = dp[2];\n if(d > dp[2].d)\n dp[2] = {p, d};\n }\n return max(max(dp[0].d, dp[1].d), dp[2].d);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | 100% easy code | 100-easy-code-by-alokpratapsing_cs22-5he6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | alokpratapsing_cs22 | NORMAL | 2024-11-08T18:02:30.507821+00:00 | 2024-11-08T18:02:30.507858+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maximumTotalDamage(int[] A) {\n int n=A.length;\n long[] dp=new long[n];\n Arrays.sort(A);\n Map<Integer,Integer> map=new HashMap<>();\n long res=0l;\n \n for(int i=0;i<n;i++){\n long score= 0l;\n int left=Math.min(map.getOrDefault(A[i]-1,i) , map.getOrDefault(A[i]-2,i));\n left=Math.min(left, map.getOrDefault(A[i],i));\n score=((long)(i- map.getOrDefault(A[i],i) + 1))*A[i];\n \n score+=left>0 ? dp[left-1]:0;\n dp[i]=Math.max(i>0 ? dp[i-1]:0 , score);\n\n map.putIfAbsent(A[i],i);\n }\n return dp[n-1];\n }\n \n \n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | C++ sort process then iterate with deque | c-sort-process-then-iterate-with-deque-b-061z | cpp []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n vector<pair<long long, long long>> p;\n sort(power.beg | user5976fh | NORMAL | 2024-11-05T07:29:52.557639+00:00 | 2024-11-05T07:29:52.557666+00:00 | 4 | false | ```cpp []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n vector<pair<long long, long long>> p;\n sort(power.begin(), power.end());\n long long n = power[0], f = 0;\n for (auto& num : power) {\n if (num == n) ++f;\n else {\n p.push_back({n, f * n});\n n = num;\n f = 1;\n }\n }\n p.push_back({n, f * n});\n deque<long long> sums, level;\n long long largest = 0, ans = 0;\n for (int i = 0; i < p.size(); ++i){\n auto [f, s] = p[i];\n while (!level.empty() && level.front() + 2 < f){\n largest = max(largest, sums.front());\n sums.pop_front();\n level.pop_front();\n }\n long long next = s + largest;\n ans = max(ans, next);\n sums.push_back(next);\n level.push_back(f);\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | DP | Similar to House Robber | dp-similar-to-house-robber-by-yimang-z23p | Intuition\nSimilar to https://leetcode.com/problems/house-robber/\n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(n)\n Add your space co | yimang | NORMAL | 2024-10-26T06:27:54.345279+00:00 | 2024-10-26T06:32:22.563542+00:00 | 8 | false | # Intuition\nSimilar to https://leetcode.com/problems/house-robber/\n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n count = Counter(power)\n damage = list(count.keys())\n damage.sort()\n\n damage = [0, 0, 0] + damage\n dp = [0] * len(damage)\n\n for i in range(3, len(damage)):\n j = i - 1\n # Example: [1, 2, 3]\n if (damage[i-1] == damage[i] - 1) and (damage[i-2] == damage[i] - 2):\n j = i - 3\n # Example: [1, 3] OR [2, 3]\n elif (damage[i-1] >= damage[i] - 2):\n j = i - 2\n \n dp[i] = max(damage[i] * count[damage[i]] + dp[j], dp[i-1])\n\n return dp[-1]\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | Python Solution, Beats 99.47%, Bottom-up DP | python-solution-beats-9947-bottom-up-dp-ozb39 | This solution uses a bottom up dynamic programming approach and beats 99.47% of other approaches runtime wise and 71.01% in memory use.\n\n## Idea\nTo solve thi | fayyazbasil | NORMAL | 2024-10-24T22:06:40.621834+00:00 | 2024-10-24T22:06:40.621856+00:00 | 4 | false | This solution uses a bottom up dynamic programming approach and beats 99.47% of other approaches runtime wise and 71.01% in memory use.\n\n## Idea\nTo solve this we will first get a count of all powers with the same damage (as multiple powers can have the same damage) and then sort all the unqiue damages of the powers.\nThis is done as if multiple spells have the same damage we can use all of these spells.\n\nWe will go through all the unique damages in order and set the current damage to the max of:\n- Using this power (current spell damage * count of spells with this damage) + max damage whilst using first power which is more than 2 difference in damage\n\t- To find the first damage which is more than 2 difference in damage from current damage we will check the previous 3 damages, and use the first damage that is outside of the blocked range. We check previous 3 as damages could either be consecutive and we will have to use 3rd [1,2,3,4] or non consecutive and we can use the damage right before [1,4,7,10,14]. Additionaly the max damage for the 3 previous damages must be stored.\n- Not Using this power and using previously determined max damage upto previous damage\n\nAfter going through all powers with this method we will have the maximum damage we can output whilst not violating the rules.\n>It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.\n## Solution\n```Python\ndef maximumTotalDamage(self, power: List[int]) -> int:\n\tcounts = Counter(power)\n\tpower = sorted(counts.keys())\n\t\n\t# store current damage and last 3 powers\n\tcur = p1 = p2 = p3 = 0\n\n\tfor i, spell in enumerate(power):\n\t\tcur = (counts[spell] * spell)\n\n\t\t# Add previous powers to current damages if they do not violate\n\t\tif i > 0 and spell - power[i - 1] > 2:\n\t\t\tcur += p1\n\t\telif i > 1 and spell - power[i - 2] > 2:\n\t\t\tcur += p2\n\t\telif i > 2:\n\t\t\tcur += p3\n\n\t\t# Choose current damage or previous damage score\n\t\tif p1 > cur:\n\t\t\tcur = p1\n\n\t\t# Shift over previous powers\n\t\tp3 = p2\n\t\tp2 = p1\n\t\tp1 = cur\n\n\treturn cur\n```\n## Complexity Analysis\n### Runtime Analysis\n- Initially filling the dictionary of count (damage: powers count) for powers will take O(n) where n is the total number of powers (non -unique damage)\n- Sorting all the unique damages will take O(d log d) where d is the |unique damages|\n- Then the algo goes through each unique damage and for each damage figuring out the max damage upto that point takes O(1) time making overall for loop runtime O(d)\n\nOverall runtime is **O(n + d log d)** which can be **less tightly bounded by O(n log n)** as d <= n.\n### Space complexity\n- Generating the counter to store the counts of powers with a particular damage will take overall O(d) space (d = |unique damage|).\n- Other than that 4 variabes are made and no other auxiliary space is required\nOverall memory complexity is **O(d)** which again can be **less tightly bounded by O(n)** as d <= n.\n\nP.S.\nThis is one of my first few solutions so any feedback would be appreciated. | 0 | 0 | ['Dynamic Programming', 'Python'] | 0 |
maximum-total-damage-with-spell-casting | Beats 100% of solutions. Python DP | beats-100-of-solutions-python-dp-by-ohud-ywjc | Intuition\n Describe your first thoughts on how to solve this problem. \nDynamic Programming\n\n# Approach\n Describe your approach to solving the problem. \n1. | ohudson | NORMAL | 2024-10-19T17:31:21.408806+00:00 | 2024-10-19T17:31:21.408827+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamic Programming\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Store frequency of powers in hashmap\n2. Remove duplicates from power array\n3. Sort power array\n4. 1-D DP where dp[i] represents maximum power at index i of sorted powers\n5. Answer is dp[len(power - 1)]\n\n# Complexity\n- Time complexity: O(nlog(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n\n #create map of power : power frequency\n #sort array by power\n\n #create dp array damange[i] - max damage up to spell i in sorted array\n # transitions step: for next index, max power is max of next index * frequency - prior two * each frequency if they are on and within range or previous max\n \n power_frequency = {}\n for power_value in power:\n power_frequency[power_value] = power_frequency.get(power_value, 0) + 1\n\n power = list(set(power))\n power.sort()\n\n maximum_damage = [0] * len(power)\n maximum_damage[0] = power_frequency[power[0]] * power[0]\n\n for i, power_level in enumerate(power):\n p = i - 1\n while p >= 0 and power[p] >= power_level - 2:\n p -= 1\n if p < 0:\n maximum_prior_damage = 0\n else:\n maximum_prior_damage = maximum_damage[p]\n \n damage_with_curr_power = maximum_prior_damage + power_frequency[power_level] * power_level\n damage_without_curr_power = maximum_damage[i - 1]\n\n maximum_damage_at_curr = max(damage_with_curr_power, damage_without_curr_power)\n maximum_damage[i] = maximum_damage_at_curr\n\n return maximum_damage[len(power) - 1]\n \n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | Beats 100% as of 10/19/24 | beats-100-as-of-101924-by-ohudson-no4v | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ohudson | NORMAL | 2024-10-19T17:22:32.160610+00:00 | 2024-10-19T17:22:32.160633+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n\n #create map of power : power frequency\n #sort array by power\n\n #create dp array damange[i] - max damage up to spell i in sorted array\n # transitions step: for next index, max power is max of next index * frequency - prior two * each frequency if they are on and within range or previous max\n \n power_frequency = {}\n for power_value in power:\n power_frequency[power_value] = power_frequency.get(power_value, 0) + 1\n\n power = list(set(power))\n power.sort()\n\n maximum_damage = [0] * len(power)\n maximum_damage[0] = power_frequency[power[0]] * power[0]\n\n for i, power_level in enumerate(power):\n p = i - 1\n while p >= 0 and power[p] >= power_level - 2:\n p -= 1\n if p < 0:\n maximum_prior_damage = 0\n else:\n maximum_prior_damage = maximum_damage[p]\n \n damage_with_curr_power = maximum_prior_damage + power_frequency[power_level] * power_level\n damage_without_curr_power = maximum_damage[i - 1]\n\n maximum_damage_at_curr = max(damage_with_curr_power, damage_without_curr_power)\n maximum_damage[i] = maximum_damage_at_curr\n\n return maximum_damage[len(power) - 1]\n \n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | short code with deep understanding | short-code-with-deep-understanding-by-ra-jg5q | Pre-requisite\nSolve this problem: https://leetcode.com/problems/house-robber/description/\n\n\n# Approach\nif the product of frequency of power and power were | rajat8020 | NORMAL | 2024-10-17T23:27:51.202147+00:00 | 2024-10-17T23:27:51.202174+00:00 | 1 | false | # Pre-requisite\nSolve this problem: https://leetcode.com/problems/house-robber/description/\n\n\n# Approach\nif the product of frequency of power and power were $$<=$$ $$10^6$$ then this problem would be converted to the problem mentioned in pre-requisute. But give the constraints we won\'t be able to take an array of size $$>= 10^9$$. Hence we create a map and extend the approach using $$upper_bound$$. The code should be self explanatory. \n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n map<int, int> M;\n for(auto x : power) {\n M[x]++;\n }\n map<long long, long long> dp;\n long long ans = 0;\n for(auto e : M) {\n long long key = e.first;\n dp[key] = (long long)e.first * (long long)e.second;\n auto it = dp.upper_bound(key-3);\n if(it != dp.end() && it != dp.begin()) {\n --it;\n dp[key] += it->second;\n }\n it = dp.find(key);\n if(it != dp.begin()) {\n it--;\n dp[key] = max(dp[key], it->second);\n }\n ans = max(ans, dp[key]);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Memoization & Recursion | memoization-recursion-by-roy_b-1pc7 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis could be done with a hashmap to make it look cleaner but were memoizaing it so it | roy_b | NORMAL | 2024-10-11T18:01:31.616748+00:00 | 2024-10-11T18:01:31.616790+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis could be done with a hashmap to make it look cleaner but were memoizaing it so it doesn\'t make any difference.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI avoided running loops and including prev and just went staright with the knapsack alike approach but with constraints.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N LogN)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n# Code\n```java []\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n Arrays.sort(power);\n Long[] dp = new Long[power.length];\n return f(power,0,dp);\n }\n public long f(int[] power,int index,Long[] dp){\n if(index >= power.length){\n return 0;\n }\n if(dp[index] != null){\n return dp[index];\n }\n int next = index+1;\n long dup_sum = power[index];\n while(next < power.length && power[next] == power[next-1]){\n dup_sum += power[next];\n next++;\n }\n long nottake = f(power,next,dp);\n next = binarySearch(power,next,power[index] + 2);\n long take = dup_sum;\n if(next != -1){\n take += f(power,next,dp);\n }\n return dp[index] = Math.max(take,nottake);\n }\n public int binarySearch(int[] power,int index,int target){\n int left = index;\n int right = power.length-1;\n while(left < right){\n int mid = (left+right) / 2;\n if(power[mid] > target){\n right = mid;\n }\n else{\n left = left+1;\n }\n }\n if(power[right] > target){\n return right;\n }\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | Java Solution || TC SC O(N) || Sorting | java-solution-tc-sc-on-sorting-by-harsha-pdij | \n\n# Code\njava []\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n\n Arrays.sort(power);\n long[] dp = new long[power.leng | harshal_yallewar | NORMAL | 2024-10-09T10:30:20.877842+00:00 | 2024-10-09T10:30:20.877869+00:00 | 4 | false | \n\n# Code\n```java []\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n\n Arrays.sort(power);\n long[] dp = new long[power.length];\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for(int num: power){\n map.put(num, map.getOrDefault(num,0)+1);\n }\n\n Arrays.fill(dp, -1);\n\n return f(power, 0, dp, map);\n }\n\n public long f(int[] power, int ind, long[] dp, HashMap<Integer, Integer> map){\n if(ind>=power.length) return 0;\n\n if(dp[ind]!=-1) return dp[ind];\n\n long take = (long)power[ind] * map.get(power[ind]);\n\n int i = ind + map.get(power[ind]);\n\n long notTake = f(power, i, dp, map);\n if(i<power.length){\n if(map.containsKey(power[ind]+2)){\n i += map.get(power[ind]+2);\n } \n if(map.containsKey(power[ind]+1)){\n i += map.get(power[ind]+1);\n }\n \n }\n\n take += f(power, i, dp, map);\n\n return dp[ind] = Math.max(take, notTake);\n }\n}\n``` | 0 | 0 | ['Array', 'Hash Table', 'Dynamic Programming', 'Sorting', 'Java'] | 0 |
find-the-count-of-monotonic-pairs-i | Easy Video Solution 🔥 || How to 🤔 in Interview || 3D DP || O(50*50*N) | easy-video-solution-how-to-in-interview-topbf | If you like the solution Please Upvote and subscribe to my youtube channel\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nDry Run | ayushnemmaniwar12 | NORMAL | 2024-08-11T05:23:52.559061+00:00 | 2024-08-11T09:52:56.104239+00:00 | 2,089 | false | ***If you like the solution Please Upvote and subscribe to my youtube channel***\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDry Run few examples and observe how you can build the logic\n\n\n\n***Easy Video Explanation***\n \nhttps://youtu.be/W9Job3hNmvA\n\n# Code\n\n\n```C++ []\nclass Solution {\npublic:\n int mod=1e9+7;\n int dp[2001][52][52];\n int solve(int i,int n,vector<int>&v,int prev1,int prev2) {\n if(i==n)\n return 1;\n if(dp[i][prev1][prev2]!=-1)\n return dp[i][prev1][prev2];\n int ans=0;\n for(int j=prev1;j<=v[i];j++) {\n int x1=j;\n int x2=v[i]-j;\n if(x1>=prev1 && x2<=prev2) {\n ans=(ans+solve(i+1,n,v,x1,x2))%mod;\n } \n }\n return dp[i][prev1][prev2]=ans;\n }\n int countOfPairs(vector<int>& v) {\n int n=v.size();\n memset(dp,-1,sizeof(dp));\n int ans=solve(0,n,v,0,50);\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def __init__(self):\n self.mod = 1000000007\n self.dp = None\n\n def solve(self, i, n, v, prev1, prev2):\n if i == n:\n return 1\n if self.dp[i][prev1][prev2] != -1:\n return self.dp[i][prev1][prev2]\n \n ans = 0\n for j in range(prev1, v[i] + 1):\n x1 = j\n x2 = v[i] - j\n if x1 >= prev1 and x2 <= prev2:\n ans = (ans + self.solve(i + 1, n, v, x1, x2)) % self.mod\n \n self.dp[i][prev1][prev2] = ans\n return ans\n\n def countOfPairs(self, v):\n n = len(v)\n self.dp = [[[-1] * 52 for _ in range(52)] for _ in range(n)]\n return self.solve(0, n, v, 0, 50)\n\n# Example usage:\nsolution = Solution()\nv = [1, 2, 3]\nresult = solution.countOfPairs(v)\nprint(f"Result: {result}") # Replace with actual test case\n\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n private static final int MOD = 1000000007;\n private int[][][] dp;\n\n private int solve(int i, int n, List<Integer> v, int prev1, int prev2) {\n if (i == n) {\n return 1;\n }\n if (dp[i][prev1][prev2] != -1) {\n return dp[i][prev1][prev2];\n }\n \n int ans = 0;\n for (int j = prev1; j <= v.get(i); j++) {\n int x1 = j;\n int x2 = v.get(i) - j;\n if (x1 >= prev1 && x2 <= prev2) {\n ans = (ans + solve(i + 1, n, v, x1, x2)) % MOD;\n }\n }\n \n dp[i][prev1][prev2] = ans;\n return ans;\n }\n\n public int countOfPairs(List<Integer> v) {\n int n = v.size();\n dp = new int[n][52][52];\n for (int[][] row : dp) {\n for (int[] col : row) {\n Arrays.fill(col, -1);\n }\n }\n \n return solve(0, n, v, 0, 50);\n }\n\n public static void main(String[] args) {\n Solution solution = new Solution();\n List<Integer> v = Arrays.asList(1, 2, 3);\n int result = solution.countOfPairs(v);\n System.out.println("Result: " + result); // Replace with actual test case\n }\n}\n\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(50*50*N)\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(50*50*N)\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n*Thank you* \uD83D\uDE00 | 26 | 3 | ['Dynamic Programming', 'Combinatorics', 'C++'] | 3 |
find-the-count-of-monotonic-pairs-i | [Java/C++/Python] 1D DP, O(n) Space | javacpython-1d-dp-on-space-by-lee215-n5jj | [Java/C++/Python] DP, O(n) Solution\n----------------------------------------------\n\n# Explanation\ndp[i][j] means the count of first i + 1 pairs and arr1[i] | lee215 | NORMAL | 2024-08-11T04:01:40.155237+00:00 | 2024-08-18T13:24:06.145913+00:00 | 2,645 | false | [Java/C++/Python] DP, O(n) Solution\n----------------------------------------------\n\n# **Explanation**\n`dp[i][j]` means the count of first `i + 1` pairs and `arr1[i] = j`.\n\nSince arr1[0] can be any value that `0 <= arr1[0] <= A[0]`,\nwe initilize `d[0][j] = 1`\n\nFrom the problem we have\n`A[i - 1] - arr1[i - 1] >= A[i] - arr1[i]`\n\nThat is:\n`arr1[i - 1] + A[i] - A[i - 1] <= arr1[i]`\n\nSo we can have\n`arr1[i - 1] + d <= arr1[i]`,\nwhere `d = max(0, A[i] - A[i - 1])`,\n\nThus we can have the dp equation:\n`dp[i][j] = dp[i][j - 1] + dp[i - 1][j - d]`\n\nFinally we return `sum(dp[n - 1])`\n\nBecause `dp[i]` only depends on `dp[i - 1]`,\nwe can optimize it to 1 dimention dp with `O(n)` space\n<br>\n\n# **Complexity**\nTime `O(nm)`, where `m = max(A) + 1`\nSpace `O(m)`\n<br>\n\n**Java**\n```java\n public int countOfPairs(int[] A) {\n int n = A.length, m = 1001, mod = 1000000007, dp[] = new int[m];\n Arrays.fill(dp, 1);\n\n for (int i = 1; i < n; ++i) {\n int d = Math.max(0, A[i] - A[i - 1]), dp2[] = new int[m];\n for (int j = d; j < A[i] + 1; ++j) {\n dp2[j] = ((j > 0 ? dp2[j - 1] : 0) + dp[j - d]) % mod;\n }\n dp = dp2;\n }\n\n int res = 0;\n for (int j = 0; j <= A[n - 1]; ++j)\n res = (res + dp[j]) % mod;\n return res;\n }\n```\n\n**C++**\n```cpp\n int countOfPairs(vector<int>& A) {\n int n = A.size(), m = 1001, mod = 1e9 + 7;\n vector<int> dp(m, 1);\n\n for (int i = 1; i < n; ++i) {\n int d = max(0, A[i] - A[i - 1]);\n vector<int> dp2(m, 0);\n for (int j = d; j < A[i] + 1; ++j) {\n dp2[j] = ((j > 0 ? dp2[j - 1] : 0) + dp[j - d]) % mod;\n }\n swap(dp, dp2);\n }\n\n int res = 0;\n for (int j = 0; j <= A[n - 1]; ++j)\n res = (res + dp[j]) % mod;\n return res;\n }\n```\n\n**Python**\n```py\n def countOfPairs(self, A: List[int]) -> int:\n mod = 10 ** 9 + 7\n n, m = len(A), max(A) + 1\n dp, dp2 = [1] * m, [0] * m\n for i in range(1, n):\n d = max(0, A[i] - A[i - 1])\n for j in range(d, A[i] + 1):\n dp2[j] = (dp2[j - 1] + dp[j - d]) % mod\n dp, dp2 = dp2, [0] * m\n return sum(dp) % mod\n```\n\n**Short Python**\n```py\n def countOfPairs(self, A: List[int]) -> int:\n dp = [1] * (A[0] + 1)\n for a,b in pairwise(A):\n dp = list(accumulate([0] * (b - a) + dp))[:b + 1]\n return sum(dp) % (10 ** 9 + 7)\n```\n<br>\n\n\n# **Solution 2: Combinations**\nSolution 0 is a 2D dp.\nSolution 1 is a simplified 1D dp.\n\nwe notice the result is a `n`-times accumulated number,\nwhich is also a combination number.\n\nFrom the latest python solution,\nwe can see the final length of list is `A[n - 1]`,\nWe only need to calculate the prefix zeros,\nwhich is the sum of increases.\n\nFrom the understanding of math,\nit\'s same as the number of increasing sequence `a` that\n`a1 <= a2 <= .... <= an <= v`\n\nTime `O(n + m)` for `comb` in Python, need extra `logmod` for general calculation.\nSpace `O(1)`\n\n**Python**\n```py\n def countOfPairs(self, A: List[int]) -> int:\n v = A[-1] - sum(max(b - a, 0) for a,b in pairwise(A))\n return comb(len(A) + v, v) % (10 ** 9 + 7) if v > 0 else 0\n```\n | 22 | 3 | ['C', 'Python', 'Java'] | 7 |
find-the-count-of-monotonic-pairs-i | Short | Simple | 3D DP | C++| Video Solution | O(50*50*N) | short-simple-3d-dp-c-video-solution-o505-juv0 | Intuition\n Describe your first thoughts on how to solve this problem. \nwe will go recursively and check for every possible pair of numbers.\nwe have x and y r | gavnish_kumar | NORMAL | 2024-08-11T04:08:49.990876+00:00 | 2024-08-11T07:34:50.567591+00:00 | 833 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe will go recursively and check for every possible pair of numbers.\nwe have x and y representing arr1 current index value and similarly y of arr2.\nnow for 0th index we can have range ```0<=x<=nums[0]``` and ```0<=y<=nums[0]``` so just because we can only increase x and decrease y we start with ```x=0``` and ```y=nums[0]```\nnow we will similarly call this function for upcoming indexes, range of x for next index will we lie in ```x<=j<=nums[i]```, where x is = ```arr1[i-1]``` and calculate y using formula ``y=nums[i]-x``\nbecause of repeated subproblems we have to use dp for 3 variable parameter,i.e ``i``,``x``and ``y``.\n\n<!-- Describe your approach to solving the problem. -->\n# Contest Video Solutions\nhttps://www.youtube.com/watch?v=kEGE9hDFIqc\n# Complexity \n- Time complexity:O(Nx50x50)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(Nx50x50)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nint mod=1e9+7;\nint solve(vector<int>&nums,int i,int x,int y,vector<vector<vector<int>>>&dp){\n if(i>=nums.size()) return 1;\n if(dp[i][x][y]!=-1) return dp[i][x][y];\n int ans=0;\n for(int j=x;j<=nums[i];j++){ // checking increase x up to last limit and calculate y such that x+y==nums[i];\n if((nums[i]-j)<=y)\n ans = (ans+solve(nums,i+1,j,nums[i]-j,dp))%mod; // call for next index\n }\n return dp[i][x][y]=ans;\n}\n int countOfPairs(vector<int>& nums) {\n int ans=0;\n int n=nums.size();\n vector<vector<vector<int>>>dp(n,vector<vector<int>>(51,vector<int>(51,-1)));// dp of size n*51*51\n ans= (ans+ solve(nums,0,0,nums[0],dp))%mod; // call for root with x started from 0 and y started from nums[0] because we can increase x and decrease y so we take starting of arr1[0] =0 and ending of arr2[0]=nums[i]\n \n return ans;\n }\n};\n``` | 14 | 0 | ['C++'] | 4 |
find-the-count-of-monotonic-pairs-i | Intuition + Approach || Using Memoization + Pair Sum Algorithm | intuition-approach-using-memoization-pai-z2jq | Intuition and Approach\n\n\nFor example:\n\n nums = [2,3,2]\n Conditions for good monotonic pairs:\n 1. equal to size n\n 2. arr1 increasing\n 3. | langesicht | NORMAL | 2024-08-11T04:50:13.035429+00:00 | 2024-08-11T09:32:42.843270+00:00 | 1,902 | false | # Intuition and Approach\n\n\nFor example:\n\n nums = [2,3,2]\n Conditions for good monotonic pairs:\n 1. equal to size n\n 2. arr1 increasing\n 3. arr2 decreasing\n 4. arr1[i]+arr2[i]=nums[i]\n\n\nSuppose :\n\n arr1 = [ _ , _ , _ ],\n arr2 = [ _ , _ , _ ]\n\n We have to fill these positions to create monotonic pairs.\n \n For position i=0, we have to find values for arr[i] and arr2[i] such that (arr[i]+ arr2[i]) = nums[i]\n\n\n\n\n## Observations: for nums[0]\n 1. Range of arr1[0] is : \n a. Least number which we can select as value of arr1[0] is (s1 = 0). \n b. Max number wich we can use as value of arr1[0] is (e1 = nums[i] ) because if we select value greater than nums[0] , (arr1[0] + arr2[0] >0 ]). But we want (arr1[0]+arr2[0] = nums[0])\n 2. Range of arr2[0] is :\n a. Least value which we can take as value of arr2[0] is (s2 = 0).\n b. Max value which we can select as value of arr2[0] is (e2 = nums[i]) because if we select value greater than nums[0] , (arr1[0] + arr2[0] > nums[0])\n\n## Note:\n Max value of arr1[0] and arr2[0] is nums[0] because if we select value greater than nums[0] , (arr1[0] + arr2[0] >0 ]). But we want (arr1[0]+arr2[0] = nums[0])\n\n\n## Conclusion\n- Number arr1[0] and arr2[0] are both in range [s1,e2] . We can use Pair sum Algorithm to find all pairs in this range having sum as nums[0].\n\nUse memoization + recursion and calculate pairs using pair Sum Algorithm for each value of nums[i].\n\n\n### In generalized code , for each nums[i] :\n- s1 will be prev selected value of arr1[i-1] .\n- e2 will be min of( prev selected value of arr2[i-1] and nums[i]).\n- Refer to code for better understanding and give it a dry run.\n\n\n\n# Complexity\n- Time complexity : O(n * 50 * 100) \n- Space complexity: O(n * 50 * 50)\n\n# Code\n\n```java []\nclass Solution {\n HashMap<String,Long> memo = new HashMap<>();\n public long helper(int i,int nums[],int s,int e){\n if(i==nums.length){\n return 1;\n }\n String key = s+"-"+e+"-"+i;\n if(memo.containsKey(key)){\n return memo.get(key);\n }\n long ans = 0;\n int j= s;\n int k = Math.min(e,nums[i]);\n while(j<=nums[i] && k>=0){\n int sum = j+k;\n if(sum==nums[i]){\n ans = (ans + helper(i+1,nums,j,k))%1000000007;\n j++;\n k--;\n } else if(sum<nums[i]){\n j++;\n }else {\n k--;\n }\n }\n memo.put(key,ans);\n return ans;\n }\n public int countOfPairs(int[] nums) {\n long ans = helper(0,nums,0,50);\n return (int)ans;\n }\n}\n```\n```python []\n def countOfPairs(self, nums):\n def helper(i, nums, s, e,memo):\n if i == len(nums):\n return 1\n key = "{}-{}-{}".format(s, e, i)\n if key in memo:\n return memo[key]\n ans = 0\n j = s\n k = min(e, nums[i])\n while j <= nums[i] and k >= 0:\n sum_value = j + k\n if sum_value == nums[i]:\n ans = (ans + helper(i + 1, nums, j, k,memo)) % 1000000007\n j += 1\n k -= 1\n elif sum_value < nums[i]:\n j += 1\n else:\n k -= 1\n memo[key] = ans\n return ans\n\n memo = {}\n ans = helper(0, nums, 0, 50,memo)\n return int(ans)\n```\n```c++ []\nint dp[2001][51][51];\nlong helper(int i, vector<int>& nums, int s, int e) {\n if (i == nums.size()) {\n return 1;\n }\n\n if(dp[i][s][e]!=-1){\n\n return dp[i][s][e];\n }\n \n long ans = 0;\n int j = s;\n int k = min(e, nums[i]);\n while (j <= 50 && k >= 0) {\n int sum = j + k;\n if (sum == nums[i]) {\n ans = (ans + helper(i + 1, nums, j, k)) % 1000000007;\n j++;\n k--;\n } else if (sum < nums[i]) {\n j++;\n } else {\n k--;\n }\n }\n\n\n dp[i][s][e]= ans;\n return ans;\n}\nint countOfPairs(vector<int>& nums) {\n\n for(int i=0; i<=nums.size(); i++){\n for(int j=0; j<=50; j++){\n for(int k=0; k<=50; k++){\n dp[i][j][k]=-1;\n }\n }\n }\n\n long ans = helper(0, nums, 0, 50);\n return (int) (ans);\n}\n```\n.\n.\n.\n# PLEASE UPVOTE. THANKS!\n... | 13 | 1 | ['Python', 'C++', 'Java'] | 2 |
find-the-count-of-monotonic-pairs-i | Super simple solution using combinatorics | super-simple-solution-using-combinatoric-7bvc | Key Insights\n\nThe problem can be viewed as a way of distributing the values in nums between two arrays while maintaining their monotonic properties.\nThe mini | Mudit-B | NORMAL | 2024-08-11T04:15:49.344067+00:00 | 2024-08-11T04:15:49.344090+00:00 | 913 | false | # Key Insights\n\nThe problem can be viewed as a way of distributing the values in nums between two arrays while maintaining their monotonic properties.\nThe minimum possible value for arr2 at any position constrains the possible distributions.\nOnce we find the minimum possible value for arr2, the problem transforms into a combinatorial question.\n\n# Approach\n\nFirst, we iterate through nums to find the minimum possible value for arr2 (min_arr2).\n\nWe maintain two variables, a and b, representing the current values in arr1 and arr2 respectively.\nWe update these values ensuring arr1 is non-decreasing and arr2 is non-increasing.\n\nIf min_arr2 is negative, it\'s impossible to create valid monotonic pairs, so we return 0.\nIf min_arr2 is non-negative, we can view this as a stars and bars problem:\n\nWe need to distribute min_arr2 "stars" into len(nums) + 1 "bars" (including the space before the first element and after the last).\nThis is equivalent to choosing len(nums) positions out of (min_arr2 + len(nums)) total positions.\n\n\nWe use the combination formula to calculate this: C(min_arr2 + len(nums), len(nums)).\nFinally, we return the result modulo $10^9 + 7$ as required by the problem.\n\nTime and Space Complexity\n\nTime Complexity: O(n), where n is the length of nums. We iterate through nums once.\nSpace Complexity: O(1), as we only use a constant amount of extra space.\n\n# Code\n```py\nfrom math import comb\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n a, b = 0, nums[0]\n arr1 = [a]\n arr2 = [b]\n for i in nums[1:]:\n # min a possible\n a = max(a, i - b)\n b = i - a\n arr1.append(a)\n arr2.append(b)\n # probablity question\n # bars and stars\n # we have to convert 5, 5, 5, 5 to 0, 0, 0, 0 in the end\n # xi can be {0, 1, 2, 3, 4, 5}\n # to find the number of times xi appears is the problem\n # x0 + x1 + x2 + x3 + x4 + x5 = 4\n \n # number of bars = 5\n # number of stars = 4\n # 9 choose 4 \n arr_2_min = min(arr2)\n if arr_2_min < 0:\n return 0\n res = comb(arr_2_min + len(arr2), len(arr2))\n \n return res % MOD\n``` | 10 | 0 | ['Python3'] | 5 |
find-the-count-of-monotonic-pairs-i | DP Based Solution | Memorization | Tabulation | dp-based-solution-memorization-tabulatio-ry2i | Intuition\nIf we observe carefully observe we don\'t really need to form arrays we just need to play with the conditions. Look at the arr1 it should be non-decr | tanishq0_0 | NORMAL | 2024-08-11T04:04:45.331427+00:00 | 2024-08-11T04:04:45.331448+00:00 | 1,020 | false | # Intuition\nIf we observe carefully observe we don\'t really need to form arrays we just need to play with the conditions. Look at the arr1 it should be non-decreasing means current element should be ATLEAST previous, (that\'s our first condition for finding the pairs for arr1). Now similarly we can check condition for second array, Since arr1[i] + arr2[i] = nums[i] this gives\narr2[i] = nums[i] - arr1[i] \nThis Gives us previous value for array2 , Now array 2 is non-increasing , So current value is ATMOST prev value of array 2\nwhich is\n arr2[i-1] = nums[i-1] - arr1[i-1]\n\nBased on these condition we can count number of pairs and FOR BASE CASE if we traverse the whole nums we return 1\n\nWe use DP to memorize this\n\n# Memorization\n\n```\nclass Solution {\n const int mod = 1e9 + 7;\n\npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n\n vector<vector<int>> dp(n, vector<int>(1001, - 1));\n\n return f(0, 0, nums, dp);\n \n }\n\n int f(int i, int prev, vector<int> &nums, vector<vector<int>> &dp){\n if(i >= nums.size())\n return 1;\n \n if(dp[i][prev] != -1)\n return dp[i][prev];\n \n int c = 0;\n\n for(int val = prev; val <= nums[i]; val++){\n int k = nums[i] - val;\n\n if(i == 0 || k <= nums[i -1] - prev){\n c = (c + f(i + 1, val, nums,dp)) % mod;\n }\n\n \n }\n\n return dp[i][prev] = c;\n }\n};\n```\n\n# Tabulation\n```\n#define ll long long\nclass Solution {\n const int mod = 1e9 + 7;\n\npublic:\n int countOfPairs(vector<int>& nums) {\n \n int n = nums.size();\n ll cnt = 0;\n\n int dp[n][1001];\n memset(dp, 0, sizeof(dp));\n\n for(int i = 0; i<= nums[0]; i++){\n dp[0][i] = 1;\n }\n\n for(int i = 1; i<n; i++){\n for(int prev = 0; prev <= nums[i-1]; prev++){\n for(int k = prev; k <= nums[i]; k++){\n int val = nums[i] - k;\n\n if(val <= nums[i-1] - prev)\n dp[i][k] = (dp[i][k] + dp[i-1][prev]) % mod;\n }\n }\n }\n\n for(int i = 0; i<= nums[n-1]; i++){\n cnt = (cnt + dp[n-1][i]) % mod;\n }\n\n return cnt;\n \n }\n \n};\n``` | 10 | 1 | ['Dynamic Programming', 'C++'] | 3 |
find-the-count-of-monotonic-pairs-i | Python 3 || 9 lines, no arrays || T/S: 99% / 89% | python-3-9-lines-no-arrays-ts-99-89-by-s-w4z6 | \n\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n\n n, mn = len(nums), nums.pop(0)\n num1, num2 = 0, mn\n \n fo | Spaulding_ | NORMAL | 2024-08-11T20:12:52.443516+00:00 | 2024-10-16T22:12:44.934175+00:00 | 152 | false | \n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n\n n, mn = len(nums), nums.pop(0)\n num1, num2 = 0, mn\n \n for num in nums:\n if num < num1: return 0\n\n if num > num1 + num2: \n num1 = num - num2 \n\n num2 = num - num1\n\n if num2 < mn: mn = num2\n \n return comb(n + mn, mn) % 1_000_000_007\n```\n[https://leetcode.com/problems/find-the-count-of-monotonic-pairs-ii/submissions/1352454766/](https://leetcode.com/problems/find-the-count-of-monotonic-pairs-ii/submissions/1352454766/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`. | 9 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Video Explanation - Recursion Journey from O(N*X*X*X) --> O(N*X*X) --> O(N*X) | video-explanation-recursion-journey-from-y7rw | Explanation\n\nClick here for the video\n\n# Code\n\nconst int N = 2001;\nconst int M = 1e9+7;\n\nclass Solution {\npublic:\n int countOfPairs(vector<int>& n | codingmohan | NORMAL | 2024-08-11T06:32:04.569625+00:00 | 2024-08-11T06:32:04.569652+00:00 | 280 | false | # Explanation\n\n[Click here for the video](https://youtu.be/37S9Debk8Bg)\n\n# Code\n```\nconst int N = 2001;\nconst int M = 1e9+7;\n\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<int> dp(N, 1); // dp[i+1]\n \n for (int i = n-1; i >= 0; i --) {\n vector<int> new_dp (N, 0);\n \n vector<int> prefix (N, 0);\n prefix[0] = dp[0];\n for (int j = 1; j < N; j ++) prefix[j] = (prefix[j-1] + dp[j]) % M;\n \n for (int prv1 = 0; prv1 <= 2000; prv1 ++) {\n int prv2 = (i > 0)? nums[i-1]-prv1 : 1e9;\n if (prv2 < 0) break;\n \n int l = max(prv1, nums[i] - prv2);\n int r = nums[i];\n \n if (l <= r) new_dp[prv1] = (prefix[r] - (l > 0? prefix[l-1] : 0) + M) % M;\n }\n dp = new_dp;\n } \n return dp[0];\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Simple JAVA Memo || Traditional DP (Striver) || ✅ | simple-java-memo-traditional-dp-striver-qpr2x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Harshsharma08 | NORMAL | 2024-08-11T04:09:21.955872+00:00 | 2024-08-11T04:09:21.955912+00:00 | 419 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n int dp[][][];\n int count(int nums[], int i, int prev1, int prev2){\n if(i>=nums.length) return 1;\n\n if(dp[i][prev1][prev2]!=-1) return dp[i][prev1][prev2];\n\n int ans=0;\n for(int j=0;j<=nums[i];j++){\n int x = j; int y = nums[i]-j;\n if (x>=prev1 && y<=prev2) \n ans =(ans + count(nums,i+1,x,y))%1000000007;\n }\n\n dp[i][prev1][prev2] = ans;\n return ans;\n }\n\n public int countOfPairs(int[] nums) {\n int n = nums.length;\n dp = new int[n][51][51];\n for(int i=0;i<n;i++){\n for(int j=0;j<51;j++) Arrays.fill(dp[i][j],-1);\n }\n return count(nums,0,0,50);\n }\n}\n``` | 6 | 0 | ['Array', 'Dynamic Programming', 'Memoization', 'Java'] | 3 |
find-the-count-of-monotonic-pairs-i | Simple short Top Down solution. 50*N, 2D Beats 90% | simple-short-top-down-solution-50n-2d-be-ubfs | Code\n\nclass Solution {\npublic:\n\n int n;\n int mod=1e9+7;\n int dp[2000][51];\n int dfs(vector<int>& nums,int indx,int previous)\n {\n | Michael_Teng6 | NORMAL | 2024-08-18T17:39:09.121153+00:00 | 2024-09-14T16:22:06.105709+00:00 | 133 | false | # Code\n```\nclass Solution {\npublic:\n\n int n;\n int mod=1e9+7;\n int dp[2000][51];\n int dfs(vector<int>& nums,int indx,int previous)\n {\n if(indx==n) return 1;\n if(dp[indx][previous]!=-1) return dp[indx][previous];\n long long ans=0;\n for(int i=previous;i<=nums[indx];i++)\n {\n if(indx==0||(nums[indx-1]-previous)>=nums[indx]-i)\n {\n ans+=dfs(nums,1+indx,i);\n ans%=mod;\n }\n }\n return dp[indx][previous]=ans;\n }\n\n int countOfPairs(vector<int>& nums) \n {\n memset(dp,-1,sizeof(dp));\n n=nums.size();\n return dfs(nums,0,0);\n }\n};\n``` | 5 | 0 | ['Recursion', 'Memoization', 'C++'] | 1 |
find-the-count-of-monotonic-pairs-i | C++ solution using dp | c-solution-using-dp-by-sachin_kumar_shar-443h | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Sachin_Kumar_Sharma | NORMAL | 2024-08-11T05:20:43.993688+00:00 | 2024-08-11T05:20:43.993725+00:00 | 107 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*50)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N*50)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nconst int mod=1e9+7;\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<int>> memo(n,vector<int>(1001,-1));\n return solve(0,0,nums,memo);\n }\n int solve(int ind,int prev,vector<int> &nums,vector<vector<int>> &memo){\n if(ind>=nums.size()) return 1;\n\n if(memo[ind][prev]!=-1) return memo[ind][prev];\n\n int cnt=0;\n for(int val1=prev;val1<=nums[ind];val1++){\n int val2=nums[ind]-val1;\n\n if(ind==0 || val2<=nums[ind-1]-prev){\n cnt=(cnt+solve(ind+1,val1,nums,memo))%mod;\n }\n }\n\n return memo[ind][prev]=cnt;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Mastering 3D Dynamic Programming: Efficient Pair Counting in Arrays | mastering-3d-dynamic-programming-efficie-4srf | Intuition\nThe problem at hand is about counting valid pairs from an array of integers under specific constraints. The first thought is that this problem can be | Saurabh_1602 | NORMAL | 2024-08-11T05:05:16.123526+00:00 | 2024-08-11T05:05:16.123555+00:00 | 524 | false | # Intuition\nThe problem at hand is about counting valid pairs from an array of integers under specific constraints. The first thought is that this problem can be approached using dynamic programming, as it involves breaking down the problem into smaller overlapping subproblems. By keeping track of the minimum and maximum values in pairs as we progress through the array, we can efficiently calculate the total number of valid pairs without recalculating results for the same subproblems.\n\n# Approach\n\nThe core idea is to use dynamic programming to keep track of subproblems, where each subproblem is defined by an index in the array and a pair of minimum and maximum values. We start by initializing a 3D memoization table, where memo[ind][mn][mx] stores the number of valid pairs for a given index ind, and pair values mn (minimum) and mx (maximum).\n\nSteps:\nInitialization: Start by defining a solve function that recursively computes the number of valid pairs starting from a given index.\nBase Case: If the index ind exceeds the size of the array, return 1, as we\'ve successfully formed a valid sequence.\nMemoization: Before computing the result for a given state, check if it\'s already computed and stored in the memo table.\nRecursion: Iterate over possible values for the current element, updating the minimum and maximum values for the next step. Recursively solve for the next index and accumulate the results.\nFinal Computation: Start the recursion from the first element, iterating through all possible initial pairs.\n# Complexity\n- Time complexity:\nThe time complexity is \nO(n\xD751\xD751),O(n\xD751\xD751), where \n\uD835\uDC5B\nn is the length of the array, and 51 is the range of possible values for mn and mx. This is efficient given that the size of the array and the range of values are limited.\n\n- Space complexity:\nThe space complexity is \n\uD835\uDC42(\uD835\uDC5B\xD751\xD751)\nO(n\xD751\xD751) due to the 3D memoization table used to store the results of subproblems.\n\n\n# Code\n```\nclass Solution {\npublic:\n const long long MOD = 1e9 + 7;\n vector<vector<vector<long long>>> memo;\n\n long long solve(int ind, long long mn, long long mx, vector<int>& nums) {\n if (ind >= nums.size()) {\n return 1; }\n \n \n if (memo[ind][mn][mx] != -1) {\n return memo[ind][mn][mx];\n }\n\n long long ans = 0;\n int a = nums[ind];\n\n for (long long i = mn; i <= a; i++) {\n long long b = a - i;\n if (b <= mx) {\n ans = (ans + solve(ind + 1, i, b, nums)) % MOD;\n }\n }\n\n memo[ind][mn][mx] = ans;\n return ans;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n \n memo.resize(n, vector<vector<long long>>(51, vector<long long>(51, -1)));\n \n long long ct = 0;\n for (int i = 0; i <= nums[0]; i++) {\n ct = (ct + solve(1, i, nums[0] - i, nums)) % MOD;\n }\n return ct;\n }\n};\n\n``` | 5 | 0 | ['Dynamic Programming', 'C++'] | 1 |
find-the-count-of-monotonic-pairs-i | C++ Top down dp with memoization | c-top-down-dp-with-memoization-by-ss_sks-x0p9 | \n# Code\n\nclass Solution {\npublic:\n int n;\n int memo[2000][51];\n long long mod = 1e9+7;\n int recursion(vector<int>& nums,int idx,int prev1){\ | ss_sks_4851 | NORMAL | 2024-08-11T04:05:11.318680+00:00 | 2024-08-11T04:27:59.737646+00:00 | 236 | false | \n# Code\n```\nclass Solution {\npublic:\n int n;\n int memo[2000][51];\n long long mod = 1e9+7;\n int recursion(vector<int>& nums,int idx,int prev1){\n if(idx>=n) return 1;\n if(memo[idx][prev1]!=-1) return memo[idx][prev1];\n long long ans = 0;\n int prev2=51;\n if(idx>0){\n prev2 = nums[idx-1]-prev1;\n }\n for(int i=nums[idx];i>=prev1;i--){\n if(nums[idx]-i>prev2) break;\n if(idx+1<n && memo[idx+1][i]!=-1) ans+=memo[idx+1][i];\n else ans += recursion(nums,idx+1,i);\n ans %= mod;\n }\n return memo[idx][prev1] = ans;\n }\n int countOfPairs(vector<int>& nums) {\n n = nums.size();\n memset(memo,-1,sizeof(memo));\n return recursion(nums,0,0);\n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | 🔥 |🔥 | You will understand it, I guarantee.🔥 |🔥 | | you-will-understand-it-i-guarantee-by-pr-39op | Intuition\n Describe your first thoughts on how to solve this problem. \nTo tackle the problem of counting monotonic pairs (arr1, arr2), we need to construct tw | prajwal_nimbalkar | NORMAL | 2024-08-13T17:24:16.840918+00:00 | 2024-08-13T17:24:16.840944+00:00 | 144 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo tackle the problem of counting monotonic pairs (arr1, arr2), we need to construct two arrays:\n\n* arr1 which is monotonically non-decreasing.\n* arr2 which is monotonically non-increasing.\nThe sum of corresponding elements from arr1 and arr2 should be equal to the elements of the given array nums.\nGiven the constraints, a brute-force approach would be inefficient. Instead, we use dynamic programming to count the valid pairs efficiently.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Dynamic Programming Table: Use a DP table memo where memo[ind][prev] stores the number of valid ways to form the arrays starting from index ind with the last value of arr1 being prev.\n\n* Recursive Function: Define a recursive function solve(ind, prev, nums, memo):\n\nBase Case: If ind is equal to or greater than the size of nums, return 1 as it signifies that all indices have been processed.\n\nMemoization Check: If memo[ind][prev] has a computed value, return it to avoid redundant calculations.\n\nCount Valid Pairs: Iterate over possible values for arr1[ind] from prev to nums[ind]. Compute the corresponding value for arr2[ind] as nums[ind] - arr1[ind]. Check if this value satisfies the monotonic constraints for arr2 and recursively count the number of valid pairs for subsequent indices.\n\n* Result Calculation: Start the recursion from index 0 with an initial previous value of 0 and return the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nconst int mod=1e9+7;\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<int>> memo(n,vector<int>(1001,-1));\n return solve(0,0,nums,memo);\n }\n int solve(int ind,int prev,vector<int> &nums,vector<vector<int>> &memo){\n if(ind>=nums.size()) return 1;\n\n if(memo[ind][prev]!=-1) return memo[ind][prev];\n\n int cnt=0;\n for(int val1=prev;val1<=nums[ind];val1++){\n int val2=nums[ind]-val1;\n\n if(ind==0 || val2<=nums[ind-1]-prev){\n cnt=(cnt+solve(ind+1,val1,nums,memo))%mod;\n }\n }\n\n return memo[ind][prev]=cnt;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Beginner friendly solution || Memoization || C++ | beginner-friendly-solution-memoization-c-1ba4 | Approach\nValue of elements in nums array ranges from 0 to 50.\n\narr1[i] + arr2[i] = nums[i]\n\n\nwe know the value of nums[i].If we fix the value of arr1[i] t | naman65 | NORMAL | 2024-08-11T13:45:10.919839+00:00 | 2024-08-11T13:45:10.919870+00:00 | 123 | false | # Approach\nValue of elements in nums array ranges from 0 to 50.\n```\narr1[i] + arr2[i] = nums[i]\n\n```\nwe know the value of nums[i].If we fix the value of arr1[i] then we can easly find the value of arr2[i].\n```\narr2[i] = nums[i] - arr1[i];\n\n```\nSo we take all possible values of arr1[i] and the possible value ranges from 0 to 50.\n\n```\nconst int MOD = 1000000007;\nclass Solution {\npublic:\n int solve(int idx,int prev1,int prev2,vector<int> &nums,vector<vector<vector<int>>> &dp){\n if(idx>=nums.size()) return 1;\n if(dp[idx][prev1+1][prev2+1] != -1) return dp[idx][prev1+1][prev2+1];\n int ans = 0;\n for(int i=0;i<51;i++){\n int a1 = i;\n int a2 = nums[idx]-i;\n if(a2<0) break;\n if((a1>=prev1 && a2<=prev2) || (prev1 == -1 && prev2 == -1)){\n ans = (ans+solve(idx+1,a1,a2,nums,dp))%MOD;\n }\n }\n return dp[idx][prev1+1][prev2+1]=ans%MOD;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<vector<int>>> dp(n+1,vector<vector<int>>(52,vector<int>(52,-1)));\n return solve(0,-1,-1,nums,dp);\n }\n};\n``` | 3 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C++'] | 1 |
find-the-count-of-monotonic-pairs-i | 3D-dp easy to understand solution !! | 3d-dp-easy-to-understand-solution-by-suj-k6dl | \n\n# Approach\nUse previous values to check if curr value of i and j can be inserted in the arrays or not. (there is no need to make 2 arrays we just need to | sujal-08 | NORMAL | 2024-08-15T13:47:52.055869+00:00 | 2024-08-15T13:47:52.055904+00:00 | 56 | false | \n\n# Approach\nUse previous values to check if curr value of i and j can be inserted in the arrays or not. (there is no need to make 2 arrays we just need to keep track of prev value of both arraays)\n\n\n# Code\n```\nclass Solution {\npublic:\n\n int MOD = 1e9 + 7;\n int solve(vector<int>& nums, int ind, int prev1, int prev2, vector<vector<vector<int>>>& dp) {\n if (ind == nums.size()) return 1;\n if (dp[ind][prev1][prev2] != -1) return dp[ind][prev1][prev2];\n \n int ans = 0;\n for (int i = 0; i <= nums[ind]; i++) {\n int j = nums[ind] - i;\n if (i >= prev1 && j <= prev2) {\n ans = (ans + solve(nums, ind + 1, i, j, dp)) % MOD;\n }\n }\n \n return dp[ind][prev1][prev2] = ans;\n }\n \n int countOfPairs(vector<int>& nums) {\n vector<vector<vector<int>>> dp(nums.size(), vector<vector<int>>(51, vector<int>(51, -1)));\n return solve(nums, 0, 0, 50, dp);\n }\n};\n\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 1 |
find-the-count-of-monotonic-pairs-i | Python3 - Combinatorics Explanation O(n) | python3-combinatorics-explanation-on-by-ye3ow | Intuition\nI originally solved this question using 2D DP. I saw the other combinatorics solutions and found them very interesting. It took me a bit to understan | b4aprogrammer123 | NORMAL | 2024-08-14T05:43:47.450155+00:00 | 2024-08-14T05:43:47.450177+00:00 | 60 | false | # Intuition\nI originally solved this question using 2D DP. I saw the other combinatorics solutions and found them very interesting. It took me a bit to understand the intuition behind the counting, so thought I would share my attempt at an explanation for anyone else trying to understand the solution.\n\n# Approach\n## Pt. 1 - Finding minimal and maximal arrays\nFirst, note that we can easily find the minimal monotonically increasing array: that is, the array with each element being the smallest possible value it could be out of all the valid arrays.\n\nFor `[2,3,2]`, the minimal array is `[0,1,1]`. For each element xi, you can\'t find another solution with a smaller xi. To find the minimal array:\n```\nminimal_array = [0] # The first element is always 0\nfor i in range(1, len(nums)):\n if nums[i] > nums[i-1]:\n """\n If the current number is greater than the previous number, then the next element needs to be the previous element plus the difference\n between the current and previous numbers. If we don\'t make up this difference, the other array cannot be monotonically decreasing.\n """\n minimal_array.append(minimal_array[-1] + nums[i] - nums[i-1])\n else:\n # Otherwise, just append the previous element. We can\'t go any lower since this array must be monotonically increasing.\n if minimal_array[-1] > nums[i]:\n # If the minimal possible element at this point is greater than the current number, there is no possible solution so return 0.\n return 0\n minimal_array.append(minimal_array[-1])\n\n```\nThe maximal monotonically decreasing array is just the `nums - minimal_array` where the subtraction is element-wise. In this case, the corresponding maximal array is `[2,2,1]`\n\n## Pt. 2 - Counting valid increments\nGiven the maximal array `[2,2,1]`, note that we can decrement the last element to a minimum of 0, and it would still be valid, e.g. `[2,2,0] + [0,1,2]` is a valid solution.\n\nWe can decrement element at any position so long as we can apply the same decrement to all elements to the right of that position while still keeping every element greater than or equal to 0. E.g. we can apply the same decrement to `maximal_array[1], maximal_array[2]...maximal_array[n-1]`. In this case, we would end up with `[2,1,0] + [0,2,2]`.\n\nRemember that the maximal array corresponds specifically to the minimal array, so the decrement has to be applied as described above so that there is a corresponding increment on the minimal array. The minimal array is already the minimum, so if you don\'t apply the increment as described above, you would break the monotonic attribute of the array, e.g. `[2,1,1] would correspond to [0,2,1]` which is invalid.\n\nSince the maximal array is monotonically decreasing, the minimum value in the array has to be equal to the last element. Since we can decrement until an element goes to 0, that means we can decrement a maximum of `maximal_array[-1]` times.\n\nGiven that we can decrement a maximum of `maximal_array[-1]` times plus an additional option of not applying the decrement at all, the question becomes, how many ways can we arrange the start of each decrement. E.g. for the example above, we have one decrement to place. We can start decrementing at the 0th element, first element, second element, or apply no decrement at all. There are therefore 4 solutions.\n\nIn combinatorics terms, it\'s stars and bars, where we have `len(nums)` positions where we can apply each decrement, and `maximal_array[-1] + 1` number of decrements (add one to include scenario of not applying a decrement), so \n```\n(len(nums) + (maximal_array[-1] + 1) - 1) choose ((maximal_array[-1] + 1) - 1)\n= (len(nums) + maximal_array[-1]) choose (maximal_array[-1])\n```\n\n## Pt. 3 - Space Optimization\nWe don\'t need to actually generate the minimal and maximal arrays. We just need the last element of the maximal array, and to do that, we only need to keep track of the previous elements of the minimal and maximal arrays as we iterate through the nums array. This is what is used below.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n mi, mx = 0, nums[0]\n for num in nums:\n if num - mi < 0:\n return 0\n \n if num >= mi + mx:\n mi = num - mx # Really just = mi + num - (mi + mx)\n \n mx = num - mi\n """\n Every digit within either array can vary from its max to min by a maximum of (mx + 1).\n E.g. for decreasing array, the last digit can be [0, mx], length = mx + 1\n Therefore, every pair is just each of the (mx+1) increments taking place at different\n positions within the array. Equivalent ways to split array into (mx+1) == putting len(nums) into (mx+1) buckets.\n (len(nums) + (mx+1) - 1) choose len(nums)\n """\n return math.comb(len(nums)+mx, mx) % (10**9 + 7)\n``` | 2 | 0 | ['Python3'] | 1 |
find-the-count-of-monotonic-pairs-i | Easy to Understand C++ Solution || Very Intuitive DP(Memomization) | easy-to-understand-c-solution-very-intui-ipmz | Intuition\n Describe your first thoughts on how to solve this problem. \nWhen approaching this problem, think about how to count valid sequences where each elem | jitenagarwal20 | NORMAL | 2024-08-12T07:19:37.222894+00:00 | 2024-08-12T07:19:37.222915+00:00 | 213 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen approaching this problem, think about how to count valid sequences where each element in the sequence must satisfy certain constraints relative to the previous elements. \nThe key idea is to use dynamic programming to explore all possible sequences efficiently. Start by considering the constraints on consecutive elements, then build the solution by breaking down the problem into smaller subproblems, storing intermediate results to avoid redundant calculations. This way, you can efficiently count all valid sequences that can be formed from the array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1.Dynamic Programming (DP) Setup:**\n\nThe solution uses dynamic programming to avoid recalculating results for the same subproblems.\nA 2D DP table dp[i][s] is maintained where i represents the current index in the array arr, and s represents the last selected value for the sequence.\n\n**2.Recursive Function recursion(i, s, n):**\n\nThe function recursion(i, s, n) is the core of the solution. It returns the number of valid sequences starting from the index i with the last value s.\nBase Case: If i == n, it means the end of the array is reached, so a valid sequence is found, and 1 is returned.\nMemoization: If the result for dp[i][s] is already computed (dp[i][s] != -1), it is returned directly to save computation time.\n\n**3.Transition/Recurrence Relation:**\n\nThe core idea is to explore all possible values for the current element nums[i] in the sequence starting from s to nums[i].\nThe solution iterates over all possible values j from s to nums[i].\nIf i-1 >= 0, the condition (nums[i] - j) <= (nums[i-1] - s) ensures that the sequence\'s difference constraint is respected. If true, the function recursively calculates the number of valid sequences starting from i+1 with the last value j.\nIf i-1 < 0, it means it\'s the first element, so there are no previous constraints, and the function directly calculates the number of valid sequences.\n\n**4.Modular Arithmetic:**\n\nThe problem uses large numbers, so results are computed modulo 1e9 + 7 to prevent overflow and ensure results fit within standard data types.\n\n**5.Function countOfPairs:**\n\nThis function initializes the DP table and kicks off the recursion from the first index (0) with the starting value (0).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n const int mod = 1e9+7;\n vector<int> nums;\n vector<vector<int>> dp;\n int recursion(int i,int s,int n){\n if(i==n)\n return 1;\n else if(dp[i][s]!=-1)\n return dp[i][s];\n else{\n int temp = 0;\n for(int j=s;j<=nums[i];j++){\n if(i-1>=0 && (nums[i]-j) <= (nums[i-1]-s))\n temp=(temp +recursion(i+1,j,n))%mod;\n else if(i-1<0)\n temp=(temp +recursion(i+1,j,n))%mod;\n }\n return dp[i][s] = temp%mod;\n }\n }\n int countOfPairs(vector<int>& arr) {\n nums=arr;\n int maxi = *max_element(nums.begin(),nums.end());\n int n = nums.size();\n dp.resize(n,vector<int>(maxi+1,-1));\n\n return recursion(0,0,n);\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | 92%Beats in C++|| Easy understandable DP Tabulation solution for absolute Beginners 💯✅ | 92beats-in-c-easy-understandable-dp-tabu-oxmz | \n\n# Approach\n Describe your approach to solving the problem. \nFirst we need to define the state dp[i][j] :\nThe State dp[i][j] means if we want number of po | srimukheshsuru | NORMAL | 2024-08-11T18:28:03.692044+00:00 | 2024-08-11T19:17:54.861467+00:00 | 122 | false | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we need to define the state **```dp[i][j]```** :\nThe State dp[i][j] means if we want number of possible pairs of arr1 and arr2 till ith index and the number in the ith index in the arr1 is j. \n\nNow we want to set the base case for the dp, if we are looking number of pairs for the 0th index then we will have nums[0]+1 possibilities, here in this dp array based on the state definition the value of dp[0][i] where i is from 0 to nums[0] is 1.Then we start filling the dp array, first we will vary the i from 1 to n, and then for the current number we have possiabilities from 0 to nums[i], then for calculating dp[i][cur] we need to know the prev number , \ncur>=prev and nums[i]-cur <=nums[i-1]-prev\n\nRead the above condition of both of them satisfy we can add dp[i-1][prev] to our current value dp[i][cur] and we need to check for all possible {prev , cur} pairs and then fill the dp.\nNow our answer will be the sum of all elements in the last row of the dp.\n\nThis code is less efficient with more nested loops for better solution refer to : [Link](https://leetcode.com/problems/find-the-count-of-monotonic-pairs-ii/solutions/5623413/80-beats-in-c-easy-understandable-dp-tabulation-solution-for-absolute-beginners)\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9+7;\n int countOfPairs(vector<int>& nums) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int n = nums.size();\n vector<vector<int>>dp(n,vector<int>(51,0));\n for(int i=0;i<=nums[0];i++){\n dp[0][i]=1;\n }\n for(int i=1;i<n;i++){\n for(int cur = 0;cur<=nums[i];cur++){\n int ways = 0;\n for(int prev = 0;prev<=50;prev++){\n if(cur>=prev and nums[i]-cur <=nums[i-1]-prev){\n ways=(ways + dp[i-1][prev])%mod;\n } \n }\n dp[i][cur] = ways;\n }\n }\n\n int ans =0;\n for(int i=0;i<51;i++){\n ans= (ans+dp[n-1][i])%mod;\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Dynamic Programming 2D array (Python) | dynamic-programming-2d-array-python-by-r-epzk | 2d array Dynamic Programming\n\n## Problem Statement\n\nWe are given an array of positive integers nums of length n. The goal is to find the number of monotonic | ragharao2001 | NORMAL | 2024-08-11T04:04:56.520564+00:00 | 2024-08-11T04:18:00.278665+00:00 | 106 | false | # 2d array Dynamic Programming\n\n## Problem Statement\n\nWe are given an array of positive integers `nums` of length `n`. The goal is to find the number of monotonic pairs \\((arr1, arr2)\\) such that:\n\n- `arr1` is monotonically non-decreasing: `arr1[0] <= arr1[1] <= ... <= arr1[n-1]`.\n- `arr2` is monotonically non-increasing: `arr2[0] >= arr2[1] >= ... >= arr2[n-1]`.\n- For each index `i, arr1[i] + arr2[i] = nums[i]`.\n\nThe solution must return the count of such pairs modulo `10^9 + 7`.\n\n## Code Explanation\n\nThe code uses dynamic programming to solve the problem. Here\'s a breakdown of each part of the code:\n\n```python\nclass Solution(object):\n def countOfPairs(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n MOD = 10**9 + 7\n n = len(nums)\n\n # Create a 2D dp array with size (n) x (max(nums) + 1)\n max_num = max(nums)\n dp = [[0] * (max_num + 1) for _ in range(n)]\n\n # Initialize dp[0][j]\n for j in range(nums[0] + 1):\n dp[0][j] = 1\n```\n\n- **Initialization**:\n - `MOD` is set to `10^9 + 7`to handle large numbers and avoid overflow.\n - `n` is the length of the input array `nums`.\n - `max_num` is the maximum value in `nums`, used to determine the size of the DP table.\n - `dp` is a 2D list where `dp[i][j]` represents the number of ways to form valid arrays up to index `i` with `arr1[i] = j`.\n - The first row of the DP table is initialized such that `dp[0][j] = 1` for all \\(j\\) from `0` to `nums[0]`, indicating that there\'s one way to choose `arr1[0] = j` and `arr2[0] = nums[0] - j`.\n\n```python\n # Fill the dp table\n for i in range(1, n):\n prefix_sum = 0\n diff = nums[i] - nums[i-1]\n\n for j in range(max_num + 1):\n # We accumulate the prefix sum to use in the next row\n if j <= nums[i] and j >= diff:\n prefix_sum += dp[i - 1][min(j - diff, j)]\n prefix_sum %= MOD\n dp[i][j] = prefix_sum\n```\n\n- **Filling the DP Table**:\n - The `for` loop iterates over each element `i` from `1` to `n-1`.\n - `prefix_sum` is used to accumulate the number of ways to form valid arrays up to the previous index.\n - `diff` is calculated as `nums[i] - nums[i-1]` to ensure the monotonic property of `arr2` holds (explained later).\n - The inner loop iterates over each possible value of `j`, representing `arr1[i]`.\n - The condition `j >= diff` ensures that `arr1[i]` is at least as large as `arr1[i-1] + (nums[i] - nums[i-1])`. This is necessary to satisfy \\(arr2[i] \\geq arr2[i-1] \\)\n - `prefix_sum` is updated by adding the number of ways to form valid arrays up to the previous index (`i-1`) where `arr1[i-1]` can be between `0` and `min(j - diff, j)`.\n - The result is taken modulo `MOD` to avoid overflow.\n\n```python\n # The result is the sum of the last row in dp\n result = sum(dp[n - 1][j] for j in range(nums[n - 1] + 1)) % MOD\n return result\n```\n\n- **Result Calculation**:\n - The final result is the sum of all entries in the last row of the DP table, `dp[n-1][j]`, for all `j` from `0` to `nums[n-1]`.\n - The sum is taken modulo `MOD` to get the final result.\n\n## Key Insights\n\n- The code ensures that `arr1` is monotonically non-decreasing by comparing the current value `j` with the allowed minimum based on the previous index (`i-1`).\n- By accumulating the prefix sum up to the minimum allowed value, the code efficiently counts all valid configurations.\n- The use of dynamic programming allows the solution to handle large inputs efficiently by breaking down the problem into smaller subproblems and building up the solution incrementally.\n\nThis solution ensures that all conditions for monotonicity and sum are met while efficiently counting the number of valid pairs. | 2 | 0 | ['Python'] | 1 |
find-the-count-of-monotonic-pairs-i | Java Clean DP + Memoization Solution | java-clean-dp-memoization-solution-by-sh-s4p8 | Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \n\n# Code\n\nclas | Shree_Govind_Jee | NORMAL | 2024-08-11T04:04:40.574515+00:00 | 2024-08-11T04:04:40.574539+00:00 | 265 | false | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n \n int MOD = 1_000_000_007;\n \n private long solveMemo(int[] nums, int idx1, int idx2, int num, long[][][] dp){\n// edge\n if(idx1 >= nums.length){\n return 1;\n }\n \n// step-2: already cal\n if(dp[idx1][idx2][num]!=-1){\n return dp[idx1][idx2][num];\n }\n \n// step-3: if not cal\n long res=0;\n for(int i=idx2; i<=nums[idx1]; i++){\n for(int j=num; j>=0; j--){\n if(i+j == nums[idx1]){\n res+=solveMemo(nums, idx1+1, i, j, dp);\n res %= MOD;\n }\n }\n }\n return dp[idx1][idx2][num]=res;\n }\n \n public int countOfPairs(int[] nums) {\n int n = nums.length;\n \n long[][][] dp = new long[n][51][51];\n for(int i=0; i<n; i++){\n for(int j=0; j<51; j++){\n Arrays.fill(dp[i][j], -1);\n }\n }\n \n return (int) solveMemo(nums, 0,0,nums[0], dp);\n }\n}\n``` | 2 | 1 | ['Array', 'Math', 'Dynamic Programming', 'Recursion', 'Memoization', 'Java'] | 1 |
find-the-count-of-monotonic-pairs-i | [Python3] dp | python3-dp-by-ye15-1w44 | \nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [[0]*51 for _ in range(n+1)]\n dp[n] = [1]*51 | ye15 | NORMAL | 2024-08-11T04:01:37.917060+00:00 | 2024-08-14T18:38:27.423107+00:00 | 334 | false | ```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n n = len(nums)\n dp = [[0]*51 for _ in range(n+1)]\n dp[n] = [1]*51\n for i in range(n-1, -1, -1): \n diff = 0 \n if i: diff = max(0, nums[i] - nums[i-1])\n for j in range(50, -1, -1): \n if j+1 <= 50: dp[i][j] = dp[i][j+1]\n if j+diff <= nums[i]: \n dp[i][j] = (dp[i][j] + dp[i+1][j+diff]) % 1_000_000_007\n return dp[0][0]\n``` | 2 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | 2D DP Solution | Clean solution | c-2d-dp-solution-clean-solution-by-kena7-py3h | Code | kenA7 | NORMAL | 2025-04-11T11:28:19.841068+00:00 | 2025-04-11T11:28:19.841068+00:00 | 1 | false |
# Code
```cpp []
class Solution {
public:
#define ll long long
int dp[2001][51];
ll mod=1000000007;
int find(int i,int prev1,vector<int> &nums)
{
if(i>=nums.size())
return 1;
if(dp[i][prev1]!=-1)
return dp[i][prev1];
ll res=0;
for(int ar1=0;ar1<=nums[i];ar1++)
{
if(i>0 && ar1<prev1)
continue;
if(i>0 && (nums[i]-ar1)>(nums[i-1]-prev1))
continue;
res=(res+find(i+1,ar1,nums))%mod;
}
return dp[i][prev1]=res;
}
int countOfPairs(vector<int>& nums)
{
memset(dp,-1,sizeof(dp));
return find(0,0,nums);
}
};
``` | 1 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | [Python3] 🤔 Thought process from "3d DP" to 1d DP with prefix sum, bottom-up | python3-thought-process-from-3d-dp-to-1d-7qir | Intuition\n Describe your first thoughts on how to solve this problem. \nSince there\'s a linear relation on the index, arr1 must be non-decreasing, arr2 must b | vvave | NORMAL | 2024-09-03T04:07:03.844878+00:00 | 2024-09-03T04:14:33.888103+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince there\'s a linear relation on the index, arr1 must be non-decreasing, arr2 must be non-increasing. If we can\'t think of a combinatorial approach first go, DP seems appropriate.\n\n**On determining the dimension of DP array:**\n\nThe comparison is linear on index. So at least we have to remember how many pairs can be formed using up to nums[:(i-1)].\nBut is that enough?\n\nThe answer is no. Because for the first constraint:\n**(1) arr1[i] >= arr1[i-1], arr2[i] <= arr2[i-1].**\nIf we don\'t know what arr1[i-1] and what arr2[i-1] is, how can we tell if the last number we add still satisfy the constraint?\nSo it seems good to remember "how many pairs can be formed using arr1[i-1] = j and arr2[i-1] = k", and now we can check if arr1[i] >= j and arr2[i]<=k.\n*Naively, it looks like a 3D DP!*\nThat leads to something like \ndp[i][j][k]:="using nums[:i], dp[i][j][k] pairs of monotonic array can be formed where arr1[i] = j and arr2[i] = k.\n\n**But is 3D really necessary?**\n*The answer is again no.*\n\nBecause for the second constraint:\n**(2) arr1[i] + arr2[i] = nums[i].**\nso if we know arr1[i] = j, we can deduce that any valid arr2 must have arr2[i] = nums[i]-j. arr2[i] can\'t be any other value, because otherwise it violates this constraint. dp[i][j][k] will end up having a lot of 0.\n\nSo let\'s first try 2D DP where\n"dp[i][j] = num of monotonic array up to i-th index, where arr1[i] = j"\n\nAnd see if we can improve to 1D from there. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs mentioned in the intuition, define:\n\n**"dp[i][j] = num of monotonic array up to i-th index, where arr1[i] = j"**\n\nsuppose we alreayd know dp[i-1], how to calculate dp[i][j]?\n\nSince arr1 is non-decreasing, any dp[i-1][k] where k<=j could be valid.\nHowever we also need to guarantee that arr2 is non-increasing. \n\nSpecifically,\nif $$arr1[i-1] = k$$, then \n$$arr2[i-1] = nums[i-1]-k$$. \n\nTo make arr2 non-increasing we must have \n\n$$(nums[i-1]-k == arr2[i-1]) >= (nums[i]-j == arr2[i])$$\n\nmoving k to one side, we find that \n\n$$k <= nums[i-1]-nums[i] + j$$ \nas well.\n\nso \n\n$$dp[i][j] = sum_k(dp[i-1][k])$$ \nwhere $0<=k <= min(nums[i-1]-nums[i] + j, j))$\n\nIf we naively calculate for each $$j$$, a lot of computation is repated. What if we can cache prefix sum of $dp[i-1]$ and just query each time?\n\nFinally, look at the recurrence formula for dp, $dp[i]$ depends only on $dp[i-1]$. So there\'s no need to remember all previous calculations, we only need to remember the previous row.\n\nFor the final implementation, we can define \n\n**"dp[j] = num of monotonic array where arr1[i]=j after i iterations of update."**\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n) = 51*n$$ \n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n$$O(n) = 51*n $$ \n\n# Code\n```python3 []\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD = 10 ** 9 + 7\n cap = max(nums)\n n = len(nums)\n count = [0] * (cap+1)\n #dp[j] = num of monotonic array where arr1[i]=j after i iterations of update.\n \n #base case, every pair of length one is valid.\n for j in range(0, nums[0]+1):\n count[j] = 1\n\n #try adding arr1[i] = j during i-th iteration. \n for i in range(1, n):\n prefix_sum = list(accumulate(count))\n count = [0] * (cap+1)\n for j in range(nums[i]+1):\n upper_bound = min(nums[i-1]-nums[i]+j,j)\n if upper_bound>=0:\n count[j] = prefix_sum[upper_bound] %MOD\n return sum(count)%MOD \n```\n\n\n## 2D version before optimization, for comparison\n```python3 []\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD = 10 ** 9 + 7\n cap = max(nums)\n n = len(nums)\n count = [[0] * (cap+1) for _ in range(n)]\n #count[i][j] num of valid up to i where arr1[i] = j \n #(so arr2[i] = nums[i]-j)\n #count[i][j] = prefix_sum(count[i-1][k] for k \n #such that k <=j and k<= nums[i-1]-nums[i]+j)\n for j in range(0, nums[0]+1):\n count[0][j] = 1\n\n for i in range(1, n):\n \n prefix_sum = list(accumulate(count[i-1]))\n for j in range(nums[i]+1):\n upper_bound = min(nums[i-1]-nums[i]+j,j)\n if upper_bound>=0:\n count[i][j] = prefix_sum[upper_bound] %MOD\n return sum(count[-1])%MOD \n\n``` | 1 | 0 | ['Dynamic Programming', 'Prefix Sum', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Python DP with explanation | python-dp-with-explanation-by-pchen36-snhm | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | pchen36 | NORMAL | 2024-08-11T21:47:12.987471+00:00 | 2024-08-16T17:29:12.407725+00:00 | 96 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n *51 *51)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n*51)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD = 10**9+7\n n = len(nums)\n #dp solution. Focusing on arr1, for each num in nums, checking all 50 possible values.\n dp = [[0]*51 for _ in range(n)]\n for j in range(nums[0]+1):\n dp[0][j] = 1\n\n #loop each num one by one\n for i in range(1,n):\n #check all possible values for arr1\n for j in range(nums[i]+1):\n #constraints:\n #1. each valid arr1[i] should be larger or equal than prior(arr1[i-1])\n #2. each valid arr2[i] should be less or equal than prior(arr2[i-1])\n #current valid arr1[i][j] is the sum of valid arr1[i-1] \n for p in range(j+1):\n arr2_j = nums[i] - j\n arr2_p = nums[i-1] - p\n if arr2_j <= arr2_p:\n dp[i][j] += dp[i-1][p]\n\n return sum(dp[-1])%MOD\n``` | 1 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Simple | Intuitive | Top - Down DP | C++ | simple-intuitive-top-down-dp-c-by-rishab-48g0 | Code\n\n#define MOD 1000000007\nclass Solution {\npublic:\n int helper(vector<int>&arr,int idx,int num1,int num2,vector<vector<int>>&dp){\n if(idx==ar | rishabhteli14 | NORMAL | 2024-08-11T07:37:47.443457+00:00 | 2024-08-11T07:37:47.443485+00:00 | 68 | false | # Code\n```\n#define MOD 1000000007\nclass Solution {\npublic:\n int helper(vector<int>&arr,int idx,int num1,int num2,vector<vector<int>>&dp){\n if(idx==arr.size())return 1;\n int ans = 0;\n if(dp[idx][num1]!=-1)return dp[idx][num1] % MOD;\n for(int i=num1;i<=arr[idx];i++){\n if(arr[idx]-i<=num2){\n ans = (ans +(helper(arr,idx+1,i,arr[idx]-i,dp) % MOD)) % MOD;\n }\n }\n return dp[idx][num1] = ans % MOD;\n\n }\n int countOfPairs(vector<int>& arr) {\n int n = arr.size();\n int mx = *max_element(arr.begin(),arr.end());\n vector<vector<int>>dp(n+1, vector<int>(mx+1,-1));\n return helper(arr,0,0,arr[0],dp);\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Memoized Solution | Python | memoized-solution-python-by-sheshankkuma-wc7u | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sheshankkumarsingh28 | NORMAL | 2024-08-11T05:23:26.709500+00:00 | 2024-08-11T12:37:16.557940+00:00 | 38 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n*max(nums)^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom functools import cache\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n\n n = len(nums)\n mod = 10**9 + 7\n\n @cache\n def func(i,up):\n if i == n:\n return 1\n if i == 0:\n down = 50\n else:\n down = nums[i-1]-up\n count = 0\n for j in range(max(up,nums[i]-down),nums[i]+1):\n count += func(i+1,j)\n return count%mod\n\n ans = func(0,0)\n\n return ans\n\n \n``` | 1 | 0 | ['Recursion', 'Memoization', 'Python', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | O(n x max(nums)^3) -> O(n x max(nums)^2) | c-on-x-maxnums3-on-x-maxnums2-by-abg_001-uv9p | Intuition\nThe core idea is to use dynamic programming (DP) to break down the problem into smaller subproblems. The key challenge is to ensure that:\n\n- arr1 r | abg_001 | NORMAL | 2024-08-11T05:16:40.028704+00:00 | 2024-08-11T05:16:40.028727+00:00 | 45 | false | # Intuition\nThe core idea is to use dynamic programming (DP) to break down the problem into smaller subproblems. The key challenge is to ensure that:\n\n- arr1 remains non-decreasing as we move from left to right in the array.\n- arr2 remains non-increasing as we move from left to right in the array.\n\nThis requires careful tracking of the previous values in both arr1 and arr2 to ensure the monotonic conditions are met.\n\n# **Approach 1 : 3D Dynamic Programming**\n# **DP State Definition**\nIn the 3D DP approach, we define a state fun(ind, prev1, prev2):\n- ind is the current index in the array nums.\n- prev1 is the last value chosen for arr1 (arr1[ind-1]).\n- prev2 is the last value chosen for arr2 (arr2[ind-1]).\n\nThe function fun(ind, prev1, prev2) represents the number of valid ways to construct the pairs (arr1, arr2) starting from index ind, given that the previous values in arr1 and arr2 are prev1 and prev2, respectively.\n\n# **Base Case**\nWhen ind == n (i.e., we\'ve processed all elements in nums), we return 1 because we have found a valid sequence.\n\n# Transition\nFor each possible value i of arr1[ind] (from 0 to nums[ind]):\n\n- Compute `arr2[ind] = nums[ind] - i`.\n- Ensure that:\n1. i >= prev1 to keep arr1 non-decreasing.\n1. `nums[ind] - i <= prev2` to keep arr2 non-increasing.\nIf these conditions are met, we recursively call `fun(ind + 1, i, nums[ind] - i)` to extend the sequence.\n\n# Memoization\nTo avoid recalculating results for the same subproblems, we store the results in a 3D DP table `dp[ind][prev1][prev2]`. This allows us to quickly return previously computed results.\n\n# Complexity\n- Time complexity: *O(n x max(nums)^3)*\n\n- Space complexity: *O(n x max(nums)^2)*\n\n# Approach 2 : 2D Dynamic Programming (Optimized)\n# Optimization Insight\nIn the 3D DP solution, the state prev2 (i.e., arr2[ind-1]) is directly related to prev1 (i.e., arr1[ind-1]) and the value nums[ind-1]. Specifically, `prev2 = nums[ind-1] - prev1`. This means that the prev2 state can be derived from prev1 and does not need to be tracked separately.\n\n# DP State Definition\nIn the optimized 2D DP approach, we redefine the state as fun(ind, prev1):\n\n- ind is the current index in the array nums.\n- prev1 is the last value chosen for arr1 (arr1[ind-1]).\n\nThis represents the number of valid ways to construct the pairs (arr1, arr2) starting from index ind, given that the previous value in arr1 is prev1.\n\n# Base Case\nThe base case remains the same: when ind == n, return 1.\n\n# Transition\nFor each possible value i of arr1[ind] (from 0 to nums[ind]):\n\n- Compute arr2[ind] = nums[ind] - i.\n- Ensure that:\n1. i >= prev1 to keep arr1 non-decreasing.\n1. nums[ind] - i <= nums[ind-1] - prev1 to keep arr2 non-increasing.\n\nIf these conditions hold, we recursively call `fun(ind + 1, i)`.\n\n# Memoization\nWe now use a 2D DP table `dp[ind][prev1]` to store the results, reducing the memory usage and potentially speeding up the computation.\n\n# Complexity\n- Time complexity: *O(n x max(nums)^2)*\n\n- Space complexity: *O(n x max(nums))*\n\n# Code : 2D DP Approach\n```\nclass Solution {\npublic:\n using ll = long long;\n int mod = 1e9 + 7;\n\n ll modAdd(ll a, ll b, ll mod) { return (((a % mod) + (b % mod)) % mod); }\n\n ll modSub(ll a, ll b, ll mod) { return (((a % mod) - (b % mod)) % mod); }\n\n ll modMul(ll a, ll b, ll mod) { return (((a % mod) * (b % mod)) % mod); }\n\n int fun(int ind, int prev1, vector<int>& nums, vector<vector<int>>& dp) {\n int n = nums.size();\n if (ind == n) {\n return 1;\n }\n if (dp[ind][prev1] != -1)\n return dp[ind][prev1];\n int ans = 0;\n int prev2 = nums[ind - 1] - prev1;\n for (int i = 0; i <= nums[ind]; ++i) {\n if (i >= prev1 && nums[ind] - i <= prev2) {\n ans = modAdd(ans, fun(ind + 1, i, nums, dp), mod);\n }\n }\n return dp[ind][prev1] = ans;\n }\n\n int countOfPairs(vector<int>& nums) {\n int ans = 0;\n int n = nums.size();\n vector<vector<int>> dp(n, vector<int>(1001, -1));\n for (int i = 0; i <= nums[0]; ++i) {\n ans = modAdd(ans, fun(1, i, nums, dp), mod);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | Easy DP Memoization with unordered_map | c-easy-dp-memoization-with-unordered_map-olqb | \n# Complexity\n- Time complexity: O(nm^2) where n = length of nums, and m is how high the value in nums[i] is\n\n- Space complexity: O(nm^2)\n\nFaster solution | bramar2 | NORMAL | 2024-08-11T04:45:17.724870+00:00 | 2024-08-11T04:45:49.541366+00:00 | 25 | false | \n# Complexity\n- Time complexity: $$O(n*m^2)$$ where n = length of nums, and m is how high the value in nums[i] is\n\n- Space complexity: $$O(n*m^2)$$\n\nFaster solution at Q4 sol: https://leetcode.com/problems/find-the-count-of-monotonic-pairs-ii/solutions/5619514/c-dp-tabulation-table-complement-comments/\n# Code\n```\nusing ull = unsigned long long;\nusing ll = long long;\nconst ll MOD = 1e9 + 7;\nclass Solution {\npublic:\n int countOfPairs(const vector<int>& nums) {\n int n = (int) nums.size();\n vector<unordered_map<ll,ll>> memo(n, unordered_map<ll, ll>());\n function<ll(int,ll,ll)> calc = [&](int len, ll prevIncreasing, ll prevDecreasing) -> ll {\n if(len >= n) {\n return 1;\n }\n if(auto itr = memo[len].find((prevIncreasing << 10) | prevDecreasing); itr != memo[len].end()) {\n return itr->second;\n }\n int target = nums[len];\n ll incr = prevIncreasing;\n ll decr = (target - incr);\n while(decr >= 0 && !(incr >= prevIncreasing && (prevDecreasing == -1 || decr <= prevDecreasing))) {\n incr++;\n decr--;\n }\n ll ways = 0;\n while(decr >= 0 && incr >= prevIncreasing && (prevDecreasing == -1 || decr <= prevDecreasing)) {\n ways += calc(len+1, incr, decr);\n ways %= MOD;\n\n incr++;\n decr--;\n }\n return memo[len][(prevIncreasing << 10) | prevDecreasing] = ways;\n };\n return calc(0, 0, -1) % MOD;\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Bit Manipulation', 'Memoization', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | DP - simple MEMOIZATION [beats 100%] | dp-simple-memoization-beats-100-by-zaid5-b9u5 | Intuition\nThe goal of the problem is to count the number of valid pairs in a given list nums where certain conditions are met. The specific conditions involve | zaid5496 | NORMAL | 2024-08-11T04:25:05.033975+00:00 | 2024-08-11T04:26:19.082485+00:00 | 29 | false | # Intuition\nThe goal of the problem is to count the number of valid pairs in a given list nums where certain conditions are met. The specific conditions involve partitioning each element of the list into two parts and ensuring that the pairs meet specific criteria defined by the indices and the constraints\n\n# Approach\nRecursive Solution:\n\nWe use a recursive function solve(idx, x, y) where:\nidx is the current index in the nums list.\nx is a running value that represents part of the partitioned value.\ny is another running value that represents the difference needed from the partitioned value.\nThe function tries to partition the current number nums[idx] into two parts such that the first part is at least x and the second part is at most y.\n\n**1).Base Case:**\nWhen idx reaches the length of nums, we have processed all elements, and the only valid outcome is 1 (indicating one valid way to partition all numbers).\n\n\n**2). Recursive Case:**\nFor each number nums[idx], we check all possible values i from 0 to nums[idx].\nWe ensure that the chosen value i fits the constraints (i.e., i should be at least x and the remainder nums[idx] - i should be at most y).\nWe recursively compute the number of valid pairs for the next index using solve(idx + 1, i, nums[idx] - i).\n \n\n**3). Memoization:**\nTo avoid redundant calculations and improve efficiency, we use a dictionary dp to store the results of previously computed states (idx, x, y).\n\n\n**4).Modulo Operation:**\nWe use modulo 10**9 + 7 to ensure that the numbers don\'t become too large and to fit within standard integer ranges.\n\n# Complexity\n- Time complexity:\nIn the worst case, the time complexity is O(n * m^2), where n is the length of nums, and m is the maximum value in nums. This is because for each number, we potentially iterate through all possible partitions, and we have n recursive calls. \n\n- Space complexity:\nThe space complexity is primarily determined by the size of the dp dictionary and the recursion stack. The dp dictionary stores results for each combination of (idx, x, y), and the recursion stack depth is O(n). Thus, the overall space complexity is O(n * m^2).\n\n# Code\n\n```python []\nclass Solution(object):\n def countOfPairs(self, nums):\n dp ,mod ={} ,10**9+7\n def solve(idx,x,y):\n if idx==len(nums):\n return 1\n elif (idx,x,y) in dp:\n return dp[(idx,x,y)]\n else:\n t=0\n for i in range(nums[idx]+1):\n if i>=x and nums[idx]-i<=y:\n c = solve(idx+1,i,nums[idx]-i)\n t = (t+c)%mod\n dp[(idx,x,y)]=t\n return t\n return solve(0,0,nums[0])\n \n```\n```java []\nputs class Solution {\n private Map<String, Integer> dp = new HashMap<>();\n private final int MOD = 1000000007;\n\n public int countOfPairs(int[] nums) {\n return solve(0, 0, nums[0], nums);\n }\n\n private int solve(int idx, int x, int y, int[] nums) {\n if (idx == nums.length) {\n return 1;\n }\n String key = idx + "," + x + "," + y;\n if (dp.containsKey(key)) {\n return dp.get(key);\n }\n int total = 0;\n for (int i = 0; i <= nums[idx]; i++) {\n if (i >= x && nums[idx] - i <= y) {\n int count = solve(idx + 1, i, nums[idx] - i, nums);\n total = (total + count) % MOD;\n }\n }\n dp.put(key, total);\n return total;\n }\n}\n```\nGive your feedback in the comments!\nAn Upvote might be appreciated.\n\n \n``` | 1 | 0 | ['Dynamic Programming', 'Python', 'Java'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ || DP || Recursion+Memoization | c-dp-recursionmemoization-by-akash_ktr-lji7 | Intuition\n Describe your first thoughts on how to solve this problem. \nwe need to count all the pairs of arrays, that means we need to check for all the pairs | Akash_Ktr | NORMAL | 2024-08-11T04:19:15.742868+00:00 | 2024-08-11T04:19:15.742888+00:00 | 87 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe need to count all the pairs of arrays, that means we need to check for all the pairs of elements at every index. This can be done by solving the question dynamically\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ndp[ind][p1][p2] keeps track of the number of ways till index ind, where previous element of array1 is p1 and previous element of array2 is p2.\niterate k from 0 to nums[ind] and consider current element of arr1 as k and arr2 as nums[ind]-k\nThen check whether both current elements satisfy the conditions mentioned in the question or not, if yes, then that is a valid way to make pair\n\n\n# Complexity\n- Time complexity: $$O(n^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n int MOD = 1e9 + 7;\n vector<vector<vector<int>>> dp;\n\n int f(int ind, int p1, int p2, vector<int>& nums) {\n int n = nums.size();\n \n if (ind == n) {\n return 1;\n }\n\n if (dp[ind][p1+1][p2+1] != -1) {\n return dp[ind][p1+1][p2+1];\n }\n\n int ways = 0;\n \n for (int k = 0; k <= nums[ind]; k++) {\n int a1 = k;\n int a2 = nums[ind] - k;\n \n if ((p1 == -1 || a1 >= p1) && (p2 == -1 || a2 <= p2)) {\n ways = (ways + f(ind + 1, a1, a2, nums)) % MOD;\n }\n }\n \n return dp[ind][p1+1][p2+1] = ways;\n }\n \npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n dp = vector<vector<vector<int>>>(n, vector<vector<int>>(52, vector<int>(52, -1)));\n return f(0, -1, -1, nums);\n }\n};\n\n``` | 1 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | ✅ 🎯 📌 Simple Solution || Beats 100% in Time || Dynamic Programming ✅ 🎯 📌 | simple-solution-beats-100-in-time-dynami-4g12 | Initialization:\n - We start by initializing an array curr for the first element of nums.\n - curr[i] stores the number of ways to form valid pairs where ar | vvnpais | NORMAL | 2024-08-11T04:06:48.889815+00:00 | 2024-08-11T04:14:46.898305+00:00 | 94 | false | 1. **Initialization**:\n - We start by initializing an array `curr` for the first element of `nums`.\n - `curr[i]` stores the number of ways to form valid pairs where `arr1[0] = i` and `arr2[0] = nums[0] - i`. Each index in `curr` is initially set to `1` because any valid split of `nums[0]` has exactly one valid pair.\n\n2. **State Transition**:\n - As we iterate through the elements of `nums`, we create a new array `newcurr` for each `num`.\n - The loop that updates `newcurr` starts from the index `max(len(newcurr) - len(curr), 0)`. This ensures we don\'t access out-of-bounds indices when transitioning from `curr` to `newcurr`, especially when `newcurr` is larger than `curr`.\n - For each possible value of `arr1[i]`, we use a cumulative sum (`val`) from the previous `curr` array to populate `newcurr`. This sum ensures that as `arr1` increases, the number of valid pairs correctly reflects the non-decreasing property of `arr1`.\n - The cumulative sum is adjusted using `i + 1 - max(len(newcurr) - len(curr), 0)` to ensure correct indexing, especially when the sizes of `curr` and `newcurr` differ.\n\n3. **Final Calculation**:\n - After processing all elements in `nums`, the sum of all elements in the final `curr` array gives the total count of valid pairs.\n - Since the number can be very large, we take the result modulo \\(10^9 + 7\\).\n# Code\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n curr=[1 for i in range(nums[0]+1)]\n for num in nums[1:]:\n newcurr=[0 for i in range(num+1)]\n val=curr[0]\n for i in range(max(len(newcurr)-len(curr),0),len(newcurr)):\n newcurr[i]+=val\n if i+1-max(len(newcurr)-len(curr),0)<len(curr): val+=curr[i+1-max(len(newcurr)-len(curr),0)]\n curr=newcurr\n return sum(curr)%1_000_000_007\n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | 2D Dp solution | c-2d-dp-solution-by-pranjal_dubey-np72 | Intuition\nApply 2D Dp using index and the last element(for the decreasing array) as the states.\n\n# Complexity\n- Time complexity:\nO(n 50 * 50)\n\n- Space co | Pranjal_Dubey_ | NORMAL | 2024-08-11T04:03:00.000793+00:00 | 2024-08-11T04:03:00.000824+00:00 | 124 | false | # Intuition\nApply 2D Dp using index and the last element(for the decreasing array) as the states.\n\n# Complexity\n- Time complexity:\nO(n* 50 * 50)\n\n- Space complexity:\nO(n*50) + O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n \n int solve(vector<int>& nums, int idx, int last_ele, vector<vector<int>>& dp) {\n if (idx >= nums.size()) return 1;\n \n if (dp[idx][last_ele] != -1) return dp[idx][last_ele];\n \n long long int result = 0;\n \n for (int i = nums[idx-1]-last_ele; i <= nums[idx]; i++) {\n if (nums[idx] - i <= last_ele) {\n result = (result%mod + solve(nums, idx + 1, nums[idx] - i, dp)%mod) % mod;\n }\n }\n \n return dp[idx][last_ele] = result;\n }\n \n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n nums.insert(nums.begin(),51);\n vector<vector<int>> dp(n + 2, vector<int>(52, -1));\n return solve(nums,1,nums[0], dp);\n }\n};\n\n``` | 1 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | straightforward dp | straightforward-dp-by-zinchse-2czh | Observation. It\'s sufficient to control only arr_1, as the arr_2 is automatically determined by the sum condition (nums[i] = arr_1[i] + arr_2[i])\n\n# Approach | zinchse | NORMAL | 2024-08-11T04:02:38.550196+00:00 | 2024-08-13T16:06:39.719604+00:00 | 67 | false | **Observation.** It\'s sufficient to control only `arr_1`, as the `arr_2` is automatically determined by the sum condition (`nums[i] = arr_1[i] + arr_2[i]`)\n\n# Approach\n\nLet `m = max(nums)`, which bounds the values in the arrays due to the non-negativity constraint. We introduce a `dp` array, where `dp[i]` represents the number of ways to create monotonic pairs on the "[:i]"-subarrays. \n\n**Algorithm:**\n1. for each possible value `val` in `arr_1` (ranging from `0` to `m`), iterate over all previous values `prev_val` that maintain the monotonicity of `arr_1` (ranging from `0` to `val`).\n2. check if the condition for the monotonicity of `arr_2` is satisfied.\n\n# Complexity\nTime complexity: $$\\mathcal{O}(n \\cdot m \\cdot m)$$\nSpace complexity: $$\\mathcal{O}(m)$$\n\n```python3\ndef countOfPairs(self, nums: List[int]) -> int:\n M, MOD = max(nums) + 1, 10 ** 9 + 7\n dp = [0 for _ in range(M)]\n for i in range(nums[0]+1):\n dp[i] = 1\n \n res = 0\n for i, num in enumerate(nums[1:], start=1):\n new_dp = [0 for _ in range(M)]\n for val in range(num+1):\n for prev_val in range(val+1):\n if nums[i-1] - prev_val >= nums[i] - val:\n new_dp[val] += dp[prev_val] % MOD\n dp = new_dp \n\n return sum(dp) % MOD\n``` | 1 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | Bootom up 2D DP | optimized space - O(50), time - O(n * 50 * 50) | c-bootom-up-2d-dp-optimized-space-o50-ti-to0r | We count all the possible ending value combination at each index,\nand keep results saved in dp for easy calculation for next step.\n\n\nclass Solution {\npubli | zhhackk | NORMAL | 2024-08-11T04:00:58.960012+00:00 | 2024-08-11T05:35:18.727997+00:00 | 169 | false | We count all the possible ending value combination at each index,\nand keep results saved in dp for easy calculation for next step.\n\n```\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n long long kMod = 1e9 + 7;\n int n = nums.size();\n int max_num_size = 50;\n // dp to state store f(n, x) == count of possible arrays ending first one with x\n // n - size of array, x = arr1(non-decreasing ending at x)\n vector<vector<long long>> dp(2, vector<long long>(max_num_size + 1, 0));\n\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n ans = 0;\n // x can not be more than the nums[i]. we try all possibilties.\n // and make sure counterpart in other array (arr2) is non-increasing\n for (int x = 0; x <= nums[i]; ++x) {\n dp[i%2][x] = i == 0; // for i == 0, all values of x are possible, so we mark count 1\n for (int z = 0; z <= x; ++z) // if we are trying x, what are the possible ending values at previous step in arr1, lets call it z\n if (i && nums[i-1] - z >= nums[i] - x) // also check if other array (arr2) will be in order as per constraint\n dp[i%2][x] = (dp[i%2][x] + dp[1 - (i%2)][z]) % kMod;\n\n ans = (ans + dp[i%2][x])%kMod; \n }\n }\n\n return ans;\n }\n};\n```\n\nSpace - O(max_num_size)\nTime - T(n * max_num_size * max_num_size)\n\nNot sure how to do the 4th hard one :P | 1 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | JS Beats 100% DP Top Bottom : Look Behind and continue | js-beats-100-dp-top-bottom-look-behind-a-qlf3 | IntuitionAt each state you can choose which combination is valid to continue the previous oneApproachComplexity
Time complexity:
5 * 10e6
Space complexity:
1 | tonitannoury01 | NORMAL | 2025-03-16T17:01:08.907588+00:00 | 2025-03-16T17:01:08.907588+00:00 | 1 | false | # Intuition
At each state you can choose which combination is valid to continue the previous one
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
5 * 10e6
- Space complexity:
10e5
# Code
```javascript []
/**
* @param {number[]} nums
* @return {number}
*/
var countOfPairs = function(nums) {
let max = Math.max(...nums)
let mod = 10**9 + 7
let memo = Array(nums.length + 1).fill(0).map(()=>Array(max + 1).fill(-1))
let helper = (p , prev)=>{
if(p === nums.length){
return 1
}
let res = 0
if(memo[p][prev] !== -1){
return memo[p][prev]
}
for(let i = prev ; i <= nums[p] ; i++){
let curr = nums[p]
let pre = nums[p - 1]
let prev2 = pre - prev
let in2 = nums[p] - i
if(in2 <= prev2){
res = (res % mod + helper(p+1 , i) % mod) % mod
}
}
memo[p][prev] = res % mod
return res % mod
}
let res = 0
for(let i = 0 ; i <= nums[0] ; i++){
res = (res % mod + helper(1 , i) % mod) % mod
}
return res
};
``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-count-of-monotonic-pairs-i | 💥 Beats 100% on runtime [EXPLAINED] | beats-100-on-runtime-explained-by-r9n-qe17 | IntuitionI first realize that the goal is to count all the possible pairs of numbers from the given list where each pair satisfies a specific condition. The mai | r9n | NORMAL | 2025-02-04T02:08:34.690175+00:00 | 2025-02-04T02:08:34.690175+00:00 | 5 | false | # Intuition
I first realize that the goal is to count all the possible pairs of numbers from the given list where each pair satisfies a specific condition. The main idea is to explore each number and try to find valid combinations based on the previous choices, and keep track of the results to avoid recalculating overlapping subproblems.
# Approach
Use DP to store the results of subproblems in a 2D array, where each entry represents the number of valid pairs starting from a certain index and with a given previous value. I then recursively calculate the results, filling up the DP table as I go, and use memoization to improve efficiency.
# Complexity
- Time complexity:
O(n * m), where n is the length of the input list and m is the range of possible values (in this case, 1001), since we iterate through each number and each possible previous value for each recursive call.
- Space complexity:
O(n * m) due to the 2D DP array that stores results for every index and value.
# Code
```kotlin []
class Solution {
companion object {
const val MOD = 1_000_000_007
}
fun countOfPairs(nums: IntArray): Int {
val n = nums.size
val dp = Array(n) { IntArray(1001) { -1 } }
return f(0, 0, nums, dp)
}
fun f(i: Int, prev: Int, nums: IntArray, dp: Array<IntArray>): Int {
if (i >= nums.size) return 1
if (dp[i][prev] != -1) return dp[i][prev]
var c = 0
for (val1 in prev..nums[i]) {
val k = nums[i] - val1
if (i == 0 || k <= nums[i - 1] - prev) {
c = (c + f(i + 1, val1, nums, dp)) % MOD
}
}
dp[i][prev] = c // Separate the assignment from the return statement
return c
}
}
``` | 0 | 0 | ['Array', 'Hash Table', 'Math', 'Dynamic Programming', 'Bit Manipulation', 'Memoization', 'Combinatorics', 'Kotlin'] | 0 |
find-the-count-of-monotonic-pairs-i | DP, O(n (max(nums))^2) | dp-on-maxnums2-by-filinovsky-x53e | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Filinovsky | NORMAL | 2024-12-25T23:35:40.443360+00:00 | 2024-12-25T23:35:40.443360+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def countOfPairs(self, nums: List[int]) -> int:
from collections import defaultdict
n = len(nums)
dp = [defaultdict(int) for i in range(n)]
for i in range(nums[0] + 1):
dp[0][(i, nums[0] - i)] = 1
for j in range(1, n):
for x in dp[j - 1]:
for k in range(nums[j] + 1):
if 0 <= nums[j] - (x[0] + k) <= x[1]:
dp[j][(x[0] + k, nums[j] - (x[0] + k))] += dp[j - 1][x]
ans = 0
for x in dp[-1]:
ans += dp[-1][x]
ans %= (10**9 + 7)
return ans
``` | 0 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | 3d dp | 3d-dp-by-thamanbharti-cqk8 | Intuitionwe have choices for arr1[i] && arr2[i] also we need to memoize the prev element choosen for both arr1 and arr2 since arr1 should be increasing hence ou | thamanbharti | NORMAL | 2024-12-16T07:06:54.703259+00:00 | 2024-12-16T07:06:54.703259+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have choices for arr1[i] && arr2[i] also we need to memoize the prev element choosen for both arr1 and arr2 since arr1 should be increasing hence out of two parts of nums[i] nums[i]==arr1[i]+arr2[i]\n maxel is choosen for arr1 and minel for arr2 . \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*52*52*50)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n*52*52)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int dp[2001][52][52];\n int helper(int idx,vector<int>&nums,int prev1,int prev2){\n if(idx>=nums.size())return 1;\n int mod=1e9+7; \n if(dp[idx][prev1+1][prev2+1]!=-1)return dp[idx][prev1+1][prev2+1];\n int ans=0;\n int a=prev1,b=prev2;\n for(int i=0;i<=nums[idx];i++){\n if(prev1==-1 && prev2==-1){\n ans=(ans+helper(idx+1,nums,i,nums[idx]-i))%mod;\n }\n else {\n if(i>=prev1 && nums[idx]-i <=prev2){\n ans=(ans+helper(idx+1,nums,i,nums[idx]-i))%mod;\n }\n }\n }\n\n\n return dp[idx][prev1+1][prev2+1]=ans%mod;\n }\n int countOfPairs(vector<int>& nums) {\n memset(dp,-1,sizeof(dp));\n return helper(0,nums,-1,-1);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | 3d dp | 3d-dp-by-thamanbharti-d7vv | Intuitionwe have choices for arr1[i] && arr2[i] also we need to memoize the prev element choosen for both arr1 and arr2 since arr1 should be increasing hence ou | thamanbharti | NORMAL | 2024-12-16T07:06:50.437683+00:00 | 2024-12-16T07:06:50.437683+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have choices for arr1[i] && arr2[i] also we need to memoize the prev element choosen for both arr1 and arr2 since arr1 should be increasing hence out of two parts of nums[i] nums[i]==arr1[i]+arr2[i]\n maxel is choosen for arr1 and minel for arr2 . \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*52*52*50)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n*52*52)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int dp[2001][52][52];\n int helper(int idx,vector<int>&nums,int prev1,int prev2){\n if(idx>=nums.size())return 1;\n int mod=1e9+7; \n if(dp[idx][prev1+1][prev2+1]!=-1)return dp[idx][prev1+1][prev2+1];\n int ans=0;\n int a=prev1,b=prev2;\n for(int i=0;i<=nums[idx];i++){\n if(prev1==-1 && prev2==-1){\n ans=(ans+helper(idx+1,nums,i,nums[idx]-i))%mod;\n }\n else {\n if(i>=prev1 && nums[idx]-i <=prev2){\n ans=(ans+helper(idx+1,nums,i,nums[idx]-i))%mod;\n }\n }\n }\n\n\n return dp[idx][prev1+1][prev2+1]=ans%mod;\n }\n int countOfPairs(vector<int>& nums) {\n memset(dp,-1,sizeof(dp));\n return helper(0,nums,-1,-1);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ Simple Bottom-up DP, O(1) space | c-simple-bottom-up-dp-o1-space-by-pradyu-4tq1 | Code\ncpp []\n/*\nNOTE: the k-loop can be optimised further using a prefix array. \n*/\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n | pradyumnaym | NORMAL | 2024-11-26T11:52:53.714989+00:00 | 2024-11-26T11:52:53.715015+00:00 | 4 | false | # Code\n```cpp []\n/*\nNOTE: the k-loop can be optimised further using a prefix array. \n*/\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size(), MOD = 1e9 + 7;\n vector<int> prev(51, 0), next(51);\n\n for (int i = 0; i < 51; i++) {\n if (nums[0] - i < 0) break;\n prev[i] = 1;\n }\n\n for (int i = 1; i < n; i++) {\n fill(begin(next), end(next), 0);\n\n for (int j = 0; j < 51; j++) {\n // too large a value, nothing to pair with\n if (nums[i] - j < 0) break;\n\n // arr1[i] = j can work\n // what are the lists this thing can extend?\n // ALL previous lists with arr1[i-1] <= j\n // NOTE: This can be optimised using a prefix sum \n for (int k = 0; k <= j; k++) {\n // if the decreasing order for arr2 is not maintained, \n // we can not extend this sequence ending with k at i-1\n if (nums[i-1] - k < nums[i] - j) continue;\n next[j] += prev[k];\n next[j] %= MOD;\n }\n }\n\n swap(prev, next);\n }\n\n int ans = 0;\n for (int i = 0; i < 51; i++) ans = (ans * 1L + prev[i]) % MOD;\n\n return ans;\n }\n};\n\nauto init = [](){\n ios::sync_with_stdio(0);\n cin.tie(0);\n return 0;\n}();\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Typescript | 3D memoization | typescript-3d-memoization-by-deejaydee-rrus | \nfunction countOfPairs(nums: number[]): number {\n \n const mod = 1e9 + 7;\n const dp = Array.from({length: nums.length}, () => Array.from({length: 5 | winterarc22 | NORMAL | 2024-11-15T19:59:53.242615+00:00 | 2024-11-15T19:59:53.242653+00:00 | 2 | false | ```\nfunction countOfPairs(nums: number[]): number {\n \n const mod = 1e9 + 7;\n const dp = Array.from({length: nums.length}, () => Array.from({length: 54}, () => Array(54).fill(-1)));\n \n const solve = (index, prev1, prev2) : number => {\n \n if(index === nums.length) {\n return 1;\n }\n else if (dp[index][prev1+1][prev2] != -1) {\n return dp[index][prev1+1][prev2];\n }\n \n let possibleWays = 0;\n \n for(let possibleVals = 0; possibleVals <= nums[index]; possibleVals++) {\n if(possibleVals >= prev1 && (nums[index]-possibleVals) <= prev2) {\n possibleWays = ( possibleWays + solve(index+1, possibleVals, (nums[index]-possibleVals)) ) % mod;\n }\n }\n \n return dp[index][prev1+1][prev2] = possibleWays\n };\n \n return solve(0, -1, 51);\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization'] | 0 |
find-the-count-of-monotonic-pairs-i | [C++] Bottom up DP. | c-bottom-up-dp-by-lovebaonvwu-6oqj | \ncpp []\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int dp[2001][51] = {0};\n int mod = 1e9 + 7;\n for (int j | lovebaonvwu | NORMAL | 2024-10-18T01:45:33.564441+00:00 | 2024-10-18T01:45:33.564464+00:00 | 2 | false | \n```cpp []\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int dp[2001][51] = {0};\n int mod = 1e9 + 7;\n for (int j = 0; j <= nums[0]; ++j) {\n dp[0][j] = 1;\n }\n\n int n = nums.size();\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j <= nums[i]; ++j) {\n for (int k = 0; k <= j; ++k) {\n if (dp[i - 1][k] > 0 && (nums[i] - j) <= (nums[i - 1] - k)) {\n dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod;\n }\n }\n }\n }\n\n int ans = 0;\n for (int i = 0; i < 51; ++i) {\n ans = (ans + dp[n - 1][i]) % mod;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Clean C++ Solution using DP | clean-c-solution-using-dp-by-ritikraj26-tjwx | Intuition\n Describe your first thoughts on how to solve this problem. \nDynamice Programming since we have to find the number of arrays.\n\n# Approach\n Descri | ritikraj26 | NORMAL | 2024-10-10T17:22:03.553818+00:00 | 2024-10-10T17:26:14.229939+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamice Programming since we have to find the number of arrays.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe are always iterating from the previously picked element up to nums[i], so Case 1 is already satisifed (case for array1). \nTo satisfy case 2, just check for the condition nums[i]-i<=nums[i-1]-pre. If this condition is true we can pick the current number for index i.\n\n# Complexity\n- Time complexity: StatesxTransition = O(50*N)*O(50)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N*50) + O(N) stack space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n const int mod=1e9+7;\n int findArrs(vector<int>& nums,int ind,int pre,vector<vector<int>>& dp){\n // base case\n if(ind==nums.size())\n return 1;\n\n if(dp[ind][pre]!=-1)\n return dp[ind][pre];\n int res=0;\n \n for(int i=pre;i<=nums[ind];i++){\n if(ind==0||(nums[ind-1]-pre>=nums[ind]-i)){\n res+=findArrs(nums,ind+1,i,dp);\n res%=mod;\n }\n }\n return dp[ind][pre]=res;\n }\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<int>>dp(n,vector<int>(51,-1));\n return findArrs(nums,0,0,dp);\n\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Python , Dynamic programming | python-dynamic-programming-by-ashish3804-6b0u | Problem\n\nYou are given an array nums where each element nums[i] represents the total number of pairs to split. For each element, you can split it into two non | ashish380431 | NORMAL | 2024-09-21T19:48:41.504254+00:00 | 2024-09-21T19:48:41.504278+00:00 | 5 | false | ## Problem\n\nYou are given an array `nums` where each element `nums[i]` represents the total number of pairs to split. For each element, you can split it into two non-negative values `a` and `b` such that `a + b = nums[i]`. The goal is to find the number of valid ways to split all elements such that for every pair `(a[i], b[i])` in the split array, the condition holds:\n\n- For all `i > 0`: `a[i-1] <= a[i]` and `b[i-1] >= b[i]`.\n\nYou need to return the total number of ways to achieve this, modulo `10^9 + 7`.\n\n## Approach\n\nWe can use dynamic programming (DP) to solve this problem efficiently. \n\n### Key Points:\n\n1. **Recursion with Memoization**: \n - For each element `nums[i]`, we need to iterate through all possible ways to split it into two parts: `a[i]` and `b[i]`.\n - We ensure that the conditions `a[i-1] <= a[i]` and `b[i-1] >= b[i]` hold for all `i > 0`.\n - If the condition fails, we skip that split and move to the next possible split.\n\n2. **Memoization**:\n - We use a DP table `dp[i][ec]` where `i` is the index of `nums` we are processing and `ec` represents one of the possible split values for the current element.\n - This memoization helps in avoiding recalculating the number of valid splits for the same state.\n\n3. **Base Case**:\n - When we have processed all elements, we return `1` since a valid way to split has been found.\n\n4. **Modular Arithmetic**:\n - Since the result can be large, we return the result modulo `10^9 + 7`.\n\n### Code Implementation\n\n```python\nclass Solution:\n MOD = 10**9 + 7\n\n def helper(self, i, p1, p2):\n if i == len(self.nums):\n return 1\n \n ans = 0\n for ec in range(self.nums[i] + 1):\n myVal = ec\n otherVal = self.nums[i] - ec\n if i != 0 and (p1 > myVal or p2 < otherVal):\n continue\n if self.dp[i][ec] != -1:\n ans = (ans + self.dp[i][ec]) % self.MOD\n else:\n self.dp[i][ec] = self.helper(i + 1, myVal, otherVal) % self.MOD\n ans = (ans + self.dp[i][ec]) % self.MOD\n \n return ans\n\n def countOfPairs(self, nums):\n n = len(nums)\n self.dp = [[-1] * 51 for _ in range(n)]\n self.nums = nums\n return self.helper(0, 0, 0) % self.MOD\n | 0 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Recursive two-pointer / prefix sum 94.82% on Monotonic Pairs II, 99.70% on Monotonic Pairs I | recursive-two-pointer-prefix-sum-9482-on-ibtn | Intuition\n\nIf [$k_1$,$k_2$,...$k_{i-1}$, $k_i$] is a part of a monotonic pair for the first $i$ element prefix array, \n[$k_1$,$k_2$,...$k_{i-1}$] is one for | glugglug | NORMAL | 2024-09-12T17:28:20.840120+00:00 | 2024-09-12T17:28:20.840152+00:00 | 2 | false | # Intuition\n\nIf [$k_1$,$k_2$,...$k_{i-1}$, $k_i$] is a part of a monotonic pair for the first $i$ element prefix array, \n[$k_1$,$k_2$,...$k_{i-1}$] is one for the first $i-1$ element prefix array.\n\nThe count of monotonic pairs will also be the count of pairs ending in $x_1$ + the count ending in $x_2$ + the count ending in $x_3$, etc for each possible ending value.\n\n# Approach\n\nCreate a helper function for finding the counts of monotonic pairs of prefix arrays up to element `end_index` of the first `end_index+1` elements with each ending value. The range of possible ending values from this helper for the first $n$ elements is limited in the following ways:\n\n1. Since arr1 is monotonically non-decreasing, the min value must be >= the min value for the first $n-1$ element ending values. It also must be >= 0.\n2. The maximum value must be <= `nums[n - 1]`, aliased as `target` in the code.\n3. Since `arr1[i] + arr2[i] == nums[i]`, the range of arr2 ending values is `[target - a1_max; target - a1_min]`, where a1_min & a1_max are the limits for the a1 ending value described in 1 & 2. Furthermore, since arr2 is non-increasing, the prior a2_min must be >= target - a1_max, which gives us additional restriction on a1_max, and since a1 = target - a2, with a2 <= previous a2, a1 >= target - previous_a2, so calculating the prior a2 range gives us additional restriction on a1.\n\nTo save space, we store the list of counts as an offset and a vector, where `offset` = the minimum possible ending value, so each vector element `counts[i]` represents the # of possible monotonic pairs where the $arr1$ ending element is `offset + i`.\n\nWe loop through each possible ending value in the range `[a1_min; a1_max]`, calculating the values that are acceptable for the end of the previous prefix array for that value, and from there offsets into the previous `CountsByEnd`. In order to avoid needing to loop adding up the entire subset of the vector for each ending value, we keep track of a prefix sum (`sum`), and the range that was already added, adjusting that range to the new range by adding or subtracting values from the ends. This range should really never vary by more than 1 element from 1 ending value to the next. \n\n\n# Complexity\n- Time complexity:\nO($nR$), where $n$ is the size of the arrays and $R$ is the size of the range of values for each array element. I believe for working out the `arr1[k]` end value counts, $R$ ends up being 1 + the minimum element of the first k + 1 elements of `nums`. Automatic analysis incorrectly identifies this as O($n^2$).\n\n- Space complexity:\nO(`nums[0] + min(nums[0], nums[1])`)\n\nAt any point during this algorithm, the size of the working array will be the size of the minimum value seen in `nums` so far, and we need the previous working array still around. This can only shrink after the first 2 elements, and despite being recursive, the previous recursive call has returned before the new working `CountsByEnd` is constructed.\n\n# Code\n```cpp []\nauto fast = (ios::sync_with_stdio(0), cout.tie(0), cin.tie(0), false);\nconstexpr int kMod = 1000000007;\nstruct CountsByEnd {\n int offset;\n vector<int> counts;\n};\nCountsByEnd kEmptyCounts{.offset = 0};\nstruct Solution {\n CountsByEnd helper(const vector<int>& nums, int end_index) {\n if (end_index == 0) {\n return CountsByEnd{.offset = 0,\n .counts = vector<int>(nums.front() + 1, 1)};\n }\n CountsByEnd pc = helper(nums, end_index - 1);\n const auto& pc_vec = pc.counts;\n if (pc.counts.empty())\n return pc;\n int target = nums[end_index], pt = nums[end_index - 1],\n pamn = pc.offset, pamx = pamn + (int)pc_vec.size() - 1,\n pa2mn = pt - pamx,\n a1_min = max(max(0, pamn), target - min(pt - pamn + 1, pt - pamn));\n if (target < a1_min) {\n return kEmptyCounts;\n }\n CountsByEnd ans{\n .offset = a1_min,\n };\n auto& ans_counts = ans.counts;\n ans_counts.reserve(target - a1_min + 1);\n int prior_included_a1_begin = 0, pr_end_offset = 0;\n int64_t sum = 0;\n for (int a1 = a1_min; a1 <= target; ++a1) {\n int pa1max = min(min(a1, pamx), pt - max(target - a1, pa2mn)),\n end_offset = min(pa1max + 1 - pamn, (int)pc_vec.size());\n while (pr_end_offset < end_offset)\n sum += pc_vec[pr_end_offset++];\n while (pr_end_offset > end_offset)\n sum -= pc_vec[--pr_end_offset];\n while (sum >= kMod)\n sum -= kMod;\n ans_counts.push_back(sum);\n }\n return ans;\n }\n int countOfPairs(vector<int>& nums) {\n int64_t ans = 0;\n CountsByEnd cbe = helper(nums, nums.size() - 1);\n return std::accumulate(cbe.counts.begin(), cbe.counts.end(), 0LL) %\n kMod;\n }\n};\n\n``` | 0 | 0 | ['Two Pointers', 'Dynamic Programming', 'Recursion', 'Prefix Sum', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Commented solution. You will definitely understand guys | commented-solution-you-will-definitely-u-vhaf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | parth_gujral_ | NORMAL | 2024-09-08T05:25:34.310945+00:00 | 2024-09-08T05:25:34.310975+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp\n/*\nIntuition\nTo tackle the problem of counting monotonic pairs (arr1, arr2), we need to construct two arrays:\n\narr1 which is monotonically non-decreasing.\narr2 which is monotonically non-increasing.\nThe sum of corresponding elements from arr1 and arr2 should be equal to the elements of the given array nums.\nGiven the constraints, a brute-force approach would be inefficient. Instead, we use dynamic programming to count the valid pairs efficiently.\nApproach\nDynamic Programming Table: Use a DP table memo where memo[ind][prev] stores the number of valid ways to form the arrays starting from index ind with the last value of arr1 being prev.\n\nRecursive Function: Define a recursive function solve(ind, prev, nums, memo):\n\nBase Case: If ind is equal to or greater than the size of nums, return 1 as it signifies that all indices have been processed.\n\nMemoization Check: If memo[ind][prev] has a computed value, return it to avoid redundant calculations.\n\nCount Valid Pairs: Iterate over possible values for arr1[ind] from prev to nums[ind]. Compute the corresponding value for arr2[ind] as nums[ind] - arr1[ind]. Check if this value satisfies the monotonic constraints for arr2 and recursively count the number of valid pairs for subsequent indices.\n\nResult Calculation: Start the recursion from index 0 with an initial previous value of 0 and return the result.\n*/\n\nclass Solution {\npublic:\nconst int mod=1e9+7;\n int countOfPairs(vector<int>& nums) {\n //TC->O(n*X*X)\n //where X is For every element ind in nums (with n elements), the function iterates from prev to nums[ind] (at most 1000 iterations since nums[ind] ranges from 0 to 1000).\n // X for prev1 and another X for prev2\n //both compute\n int n=nums.size();\n vector<vector<int>> memo(n,vector<int>(51,-1));\n return solve(0,0,nums,memo);\n }\n int solve(int ind,int prev,vector<int> &nums,vector<vector<int>> &memo){\n if(ind>=nums.size())//all traversed elements in array so return 1 \n return 1;\n\n if(memo[ind][prev]!=-1) return memo[ind][prev];\n\n int cnt=0;\n for(int val1=prev;val1<=nums[ind];val1++){\n //all possible values from 0 to nums[index] \n \n int val2=nums[ind]-val1; //value2 or prev2 equals to nums[index] - prev1 -> prev1+prev2=nums[index]\n\n if(ind==0 || val2<=nums[ind-1]-prev){\n //prev2 = nums[ind-1]-prev \n //nums[ind-1] value vo h jo pichli usme se prev agr minus kre to prev2 pichle index ki value dedega \n cnt=(cnt+solve(ind+1,val1,nums,memo))%mod;\n }\n }\n\n return memo[ind][prev]=cnt;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Detailed explanation, recursion with memoization, Python3 | detailed-explanation-recursion-with-memo-jbp3 | Let\'s start with the most brute force solution possible and then optimize it.\n\nThe brute force solution is to generate all the valid arrays and then count th | barris | NORMAL | 2024-09-04T14:52:15.838943+00:00 | 2024-09-04T14:52:15.838979+00:00 | 13 | false | Let\'s start with the most brute force solution possible and then optimize it.\n\nThe brute force solution is to generate all the valid arrays and then count them all. I get that it may seem a little silly to do this since our complexity will be exponential, but going through this step will help us understand the problem more deeply and provide a starting point.\n\nTo see why the complexity of this solution is exponential, let m be the biggest number in the array of n numbers. Then an upper bound for the number of arrays we\'ll generate is $$(m+1)^n$$.\n\nThis is because we\'re generating combinations of integer sums of each number in `nums`, even if we end up throwing some out due to the descending/ascending constraint. As an example, consider the array [2]. There are three ascending/descending array pairs (since we include 0):\n\n```\n[0] [2]\n[1] [1]\n[2] [0]\n```\n\nNow let\'s consider the array [2,1].\n\nFor each of the above pairs, we need to create 2 arrays for each combination of the numbers that can sum to 1 (0 and 1). If we take the pair [0] [2], we generate:\n\n```\n[0,0] [2,1]\n[0,1] [2,0]\n```\n\nAfter we do this for each of the 3 pairs for the array [2], we have $$3*2=6$$ pairs for the array [2,1].\n\nIf 2 is the largest number in the array, we\'ll end up with an upper bound of:\n\n```\n 3*3*3*...*3\n|-----n-----|\n```\n\n$$= 3^n$$ pairs of ascending/descending arrays.\n\nI would encourage you to implement this inefficient solution yourself before reading on.\n\nHere\'s my implementation, which, of course, gets Time Limit Exceeded (TLE):\n\n def countOfPairs(self, nums: List[int]) -> int:\n asc_arrays = []\n des_arrays = []\n for num in nums:\n new_asc_arrays = []\n new_des_arrays = []\n for i in range(num+1):\n if len(asc_arrays) == 0:\n new_asc_arrays.append([i])\n new_des_arrays.append([num-i])\n else:\n for arr in range(len(asc_arrays)):\n curr_asc_arr = asc_arrays[arr]\n if curr_asc_arr[-1] > i:\n continue\n j = num-i\n curr_des_arr = des_arrays[arr]\n if curr_des_arr[-1] < j:\n continue\n new_asc_arrays.append(curr_asc_arr + [i])\n new_des_arrays.append(curr_des_arr + [j])\n asc_arrays = new_asc_arrays\n des_arrays = new_des_arrays\n if len(asc_arrays) == 0:\n return 0\n return len(asc_arrays)\n\nThere\'s a simple optimization we can do right off the bat: we don\'t have to hold on to the entire arrays. Because we only ever look at the previous elements, we can hold onto just those elements.\n\nBut that still means we\'re going to have to hold on to $$O(m^n)$$ elements. It would be better if we could just count them as we go. But how can we let go of all the elements from an iteration when we need them for the next iteration?\n\nIt\'ll be better to think of this recursively so we can use the previous element, increment the count if possible, and then let the previous element go.\n\nThe easiest way to start a recursive solution is to think of the base case. Since the smallest array size in the input is 1, we may think that could work as our base case:\n\n def countOfPairs(self, nums: List[int]) -> int:\n def countOfPairsRec(nums):\n if len(nums)==1:\n return nums[0] + 1\n\n return countOfPairsRec(nums)\n\nHowever, this quickly runs into a problem when len(nums) > 1: not all of the arrays this base case counts will be valid further up the call stack. We have to evaluate each one. So the base case needs to be len(nums) == 0:\n\n def countOfPairs(self, nums: List[int]) -> int:\n def countOfPairsRec(nums):\n if len(nums)==0:\n return 1\n\n return countOfPairsRec(nums)\n\nTechnically, for an array of size 0, the count should be 0 because we can\'t make any array pairs out of it. However, in this case, it means that we\'ve reached the end of nums and have managed to successfully create one array pair.\n\nWhen we have an array of size 1 containing integer m, we have to:\n* loop through every integer i <= m+1 (the +1 is so we include m itself)\n* recursively call the function on the rest of the array (i.e. an empty array):\n\n```\n def countOfPairsRec(nums):\n if len(nums)==0:\n return 1\n count = 0\n for i in range(nums[0]+1):\n j = nums[0] - i\n count += countOfPairsRec(nums[1:])\n return count\n```\n\nNow what happens if the size of nums is 2? Let\'s say the array is [5,6]. When we get to 6, we need to know what the previous numbers were in the ascending and descending arrays to see if 0-6 will form valid arrays. We can pass these values in as arguments:\n\n def countOfPairs(self, nums: List[int]) -> int:\n\n def countOfPairsRec(prev_asc, prev_des, nums):\n if len(nums)==0:\n return 1\n count = 0\n for i in range(nums[0]+1):\n if prev_asc != None and i < prev_asc:\n continue\n j = nums[0] - i\n\n if prev_des != None and j > prev_des:\n continue\n count += countOfPairsRec(i, j, nums[1:])\n return count\n\n return countOfPairsRec(None, None, nums)\n\n\nNow we:\n* consider all numbers from 0 to the first integer in the array,\n* check whether those numbers meet our constraints for the ascending/decending arrays, and\n* if so, sum up the count from calling countOfPairsRec() recursively on the rest of the array.\n\nThis solution still gives us TLE. Notice that we\'re copying nums every time we call countOfPairsRec() with nums[1:], so instead of doing that, let\'s pass in the index we\'re considering.\n\nLet\'s also slap a [functools.cache](https://docs.python.org/3/library/functools.html#functools.cache) decorator on there to memoize anything we\'ve already computed. We\'ll also need to modulo our answers with 10^9+7 now that they\'re going to get rather large.\n\n def countOfPairs(self, nums: List[int]) -> int:\n mod = pow(10, 9)+7\n\n @cache\n def countOfPairsRec(prev_asc, prev_des, num):\n if num == len(nums):\n return 1\n count = 0\n curr_num = nums[num]\n for i in range(curr_num+1):\n if prev_asc!=None and i < prev_asc:\n continue\n j = curr_num - i\n\n if prev_des!=None and j > prev_des:\n continue\n count += countOfPairsRec(i, j, num+1)\n return count % mod\n return countOfPairsRec(None, None, 0)\n\nThis now passes leetcode\'s tests. | 0 | 0 | ['Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | CPP || DP (Rec+Memo) | cpp-dp-recmemo-by-satyamshivam366-3ptd | Intuition\n Describe your first thoughts on how to solve this problem. \ncheck all ways == dp\nalso we only have to determine the number of ways\n\n# Approach\n | satyamshivam366 | NORMAL | 2024-09-03T06:53:53.320118+00:00 | 2024-09-03T06:53:53.320150+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncheck all ways == dp\nalso we only have to determine the number of ways\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define MOD 1000000007\nclass Solution {\npublic:\n int rec(int index,int last_1,int last_2,vector<int>& num,vector<vector<vector<int>>>& dp)\n {\n int n=num.size();\n if(index==n){return 1;}\n if(dp[index][last_1][last_2]!=-1){return dp[index][last_1][last_2];}\n int ways=0;\n for(int i=last_1;i<=num[index];i++)\n {\n if(last_2<(num[index]-i)){continue;}\n ways=(ways%MOD+rec(index+1,i,num[index]-i,num,dp)%MOD)%MOD;\n }\n return dp[index][last_1][last_2]=ways%MOD;\n }\n int countOfPairs(vector<int>& num) {\n int n=num.size();\n vector<vector<vector<int>>> dp(n+1,vector<vector<int>>(52,vector<int>(52,-1)));\n return rec(0,0,51,num,dp)%MOD;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | SIMPLEST SOLUTION | simplest-solution-by-animesh_maurya-oztg | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Animesh_Maurya | NORMAL | 2024-08-28T04:18:43.907232+00:00 | 2024-08-28T04:18:43.907261+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n int countPair(int index,int prev1,int prev2,vector<int>& nums,vector<vector<vector<int>>>& dp){\n if(index==nums.size()){\n return 1;\n }\n if(dp[index][prev1+1][prev2]!=-1)return dp[index][prev1+1][prev2];\n int count=0;\n int temp=nums[index];\n int i=0;\n while(i<=temp){\n if(i>=prev1 && temp-i<=prev2){\n count=(count+countPair(index+1,i,temp-i,nums,dp) % 1000000007) % 1000000007;\n }\n i++;\n }\n return dp[index][prev1+1][prev2]=count % 1000000007;\n }\npublic:\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<vector<int>>> dp(n,vector<vector<int>>(52,vector<int>(52,-1)));\n return countPair(0,-1,51,nums,dp) % 1000000007;\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Python || Dynamic Programming | python-dynamic-programming-by-vilaparthi-ahyt | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | vilaparthibhaskar | NORMAL | 2024-08-23T15:31:31.390518+00:00 | 2024-08-23T15:31:31.390556+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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)$$ -->\nm = max element\nn = len(nums)\nO(n * m * m)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n * m)\n\n# Code\n```python3 []\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n m = max(nums)\n l = len(nums)\n mod = (10 ** 9) + 7\n dp = [[0 for _ in range(m + 1)] for _ in range(l)]\n for i in range(nums[-1] + 1):\n dp[-1][i] = 1\n for i in range(l - 2, -1, -1):\n for j in range(nums[i] + 1):\n a, b = j, nums[i] - j\n temp = 0\n for k in range(nums[i + 1], a - 1, -1):\n hold = nums[i + 1] - k\n if not (b >= hold):\n break\n temp += dp[i + 1][k]\n dp[i][j] = temp % mod\n return sum(dp[0]) % mod\n\n\n \n``` | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'Combinatorics', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Beats 95% users 🔥🔥 | beats-95-users-by-arnavsoney-7puu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | arnavsoney | NORMAL | 2024-08-22T12:06:27.885023+00:00 | 2024-08-22T12:06:27.885051+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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)$$ -->\nO(N^3)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n const int MOD = 1e9+7;\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<int> arr1(n);\n vector<int> arr2(n);\n vector<vector<int>> dp(n, vector<int>(1001, 0));\n for (int j = 0; j <= nums[0]; j++)\n dp[0][j] = 1;\n for (int i = 1; i < n; i++){\n int ways = 0;\n int k = 0;\n for (int j = 0; j <= nums[i]; j++){\n // problem I\n // for (int j = 0; j <= nums[i]; j++){\n // int ways = 0;\n // for (int k = 0; k <= 50; k++){\n // if (k <= j && nums[i - 1] - k >= nums[i] - j)\n // ways = (ways + dp[i - 1][k]) % MOD;\n // }\n // dp[i][j] = ways;\n // }\n // problem II\n if (k <= min(j, j - (nums[i] - nums[i - 1]))){\n ways = (ways + dp[i - 1][k]) % MOD;\n k++;\n }\n dp[i][j] = ways;\n }\n }\n int res = 0;\n for (int i = 0; i <= 1000; i++)\n res = (res + dp[n - 1][i]) % MOD;\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Memoization Recursion | memoization-recursion-by-ducanh123-02zm | Intuition\n Describe your first thoughts on how to solve this problem. \nmemorizaton recursion f(curr_idx,pre_el_ar1,pre_el_ar2)\nkeep track 1 current idx becau | ducanh123 | NORMAL | 2024-08-19T05:43:34.267072+00:00 | 2024-08-19T05:43:34.267105+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nmemorizaton recursion f(curr_idx,pre_el_ar1,pre_el_ar2)\nkeep track 1 current idx because each recursion we take element for ar1 and ar2, and pre_el_ar1, pre_el_ar2 for keep track array condition that question mention \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*X*X)\n N: size of nums: <= 2000\n X: max element of nums <=50\n- Space complexity:O(N*X*X)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n mod = 10**9 + 7 \n n = len(nums)\n @cache\n def f(idx,pre1,pre2):\n if idx >= n:\n return 1\n ans = 0\n for i in range(nums[idx]+1):\n x1,x2 = i ,nums[idx] - i\n if pre1 == -1 and pre2 == -1:\n ans += (f(idx+1, x1 , x2)%mod)\n else:\n if pre1 <= x1 and pre2 >= x2:\n ans += (f(idx+1,x1,x2) % mod)\n return ans% mod\n return f(0,-1,-1) \n``` | 0 | 0 | ['Recursion', 'Memoization', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | Dynamic Programming Solution (2D DP C++) | dynamic-programming-solution-2d-dp-c-by-pczj9 | Intuition\nThe problem requires us to find the number of ways to split an array into two subarrays: one in increasing order and the other in decreasing order. S | Yash-mehra | NORMAL | 2024-08-17T12:37:04.903390+00:00 | 2024-08-17T12:37:04.903423+00:00 | 5 | false | # Intuition\nThe problem requires us to find the number of ways to split an array into two subarrays: one in increasing order and the other in decreasing order. Specifically:\n\n- We need to create two arrays, first_array and second_array, from the given array nums.\n- The element at index i in first_array should be between 0 and nums[i].\n- The element at index i in second_array is determined by subtracting the corresponding element in first_array from nums[i] (i.e., second_array[i] = nums[i] - first_array[i]).\n\nThe goal is to ensure:\n- first_array is in non-decreasing order.\n- second_array is in non-increasing order.\n\nTo count the number of valid pairs (first_array, second_array), we can use dynamic programming. We iterate over each element in nums and consider all possible values for first_array[i], ensuring the required conditions for both arrays are met. \n\n# Approach\n1. Dynamic Programming Table:\n- Define a DP table dp[i][current] where dp[i][current] stores the number of valid ways to construct pairs up to index i such that first_array[i] is equal to current.\n\n2. Base Case:\n- Initialize dp[0][i] for all i from 0 to nums[0] with 1, as there\'s only one way to assign a value at the first index, given that there\'s no previous element to compare.\n\n3. DP Transition:\n- For each index i from 1 to size-1 (where size is the length of nums):\n - For each possible value current from 0 to nums[i] (the value for first_array[i]):\n - Iterate through all possible previous values prev from 0 to nums[i-1].\n - Update dp[i][current] by adding dp[i-1][prev] if both conditions hold:\n 1. prev <= current ensures first_array is non-decreasing.\n 2. (nums[i] - current) <= (nums[i-1] - prev) ensures second_array is non-increasing.\n \n4. Final Count:\n- After processing all indices, the answer is the sum of all values in the last row of the DP table, i.e., dp[size-1][i] for all i from 0 to nums[size-1]\n\n# Complexity\nwhere *n* is the size of nums and *m* is the maximum value in nums which is 50 in this case.\n- Time Complexity: \uD835\uDC42(\uD835\uDC5B\xD7\uD835\uDC5A^2).\n- Space complexity:\n*O(n\xD7m)* due to the DP table.\n\n# Code\n```\nclass Solution {\nprivate:\n int modulo = 1e9 + 7;\npublic:\n int countOfPairs(vector<int>& nums) {\n int size = nums.size();\n\n vector<vector<int>> dp(size, vector<int>(51, 0));\n\n for (int i = 0; i <= nums[0]; i++) {\n dp[0][i] = 1;\n }\n\n for (int i = 1; i < size; i++) {\n for (int current = 0; current <= nums[i]; current++) {\n for (int prev = 0; prev <= nums[i-1]; prev++) {\n if (prev <= current && (nums[i] - current <= nums[i-1] - prev)) {\n dp[i][current] = (dp[i][current] + dp[i-1][prev]) % modulo;\n }\n }\n }\n }\n\n int count = 0;\n for (int i = 0; i <= nums[size-1]; i++) {\n count = (count + dp[size-1][i]) % modulo;\n }\n\n return count;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | beats 81% in time, and 98 %in space | beats-81-in-time-and-98-in-space-by-morn-e5b3 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Morningstar_30 | NORMAL | 2024-08-17T10:23:35.999810+00:00 | 2024-08-17T10:23:35.999840+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nconst int mod=1e9+7;\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n int dp[n][51];\n for(int i=0;i<=nums[0];i++)\n {\n dp[0][i]=1;\n }\n for(int i=nums[0]+1;i<=50;i++)\n {\n dp[0][i]=0;\n }\n for(int i=1;i<n;i++)\n {\n for(int j=0;j<=50;j++)\n {\n dp[i][j]=0;\n }\n }\n for(int i=1;i<n;i++)\n {\n for(int j=0;j<=nums[i];j++)\n {\n for(int k=0;k<=j;k++)\n {\n if(nums[i-1]-k<0)\n {\n break;\n }\n if(nums[i-1]-k<nums[i]-j)\n {\n break;\n }\n dp[i][j]+=dp[i-1][k];\n dp[i][j]%=mod;\n }\n }\n }\n int ans=0;\n for(int i=0;i<=50;i++)\n {\n ans+=dp[n-1][i];\n ans%=mod;\n }\n return ans;\n\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Recursion -> DP, Intuitive, Memoization, Python3, 3D DP | recursion-dp-intuitive-memoization-pytho-5bgv | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition is similar to longest consequetive subarray problem where we pass the las | stiffmeister1122 | NORMAL | 2024-08-17T08:52:12.799847+00:00 | 2024-08-17T08:52:12.799871+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is similar to longest consequetive subarray problem where we pass the last element to the function.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSend prev1 and prev2 for arr1 and arr2 respetively, return 1 as i == n and add the function return to totalPairs\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(50X50Xn)\n\n# Code\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n retArr = []\n n = len(nums)\n\n self.monotonic = 0\n \n dp = [[[-1 for _ in range(51)] for __ in range(51)] for ___ in range(n)]\n\n def f(i,prev1,prev2):\n if i >=n:\n\n return 1\n \n if dp[i][prev1][prev2] !=-1:\n return dp[i][prev1][prev2]\n \n totalPairs = 0\n \n for j in range(nums[i]+1):\n if j>=prev1 and nums[i]-j<= prev2:\n\n totalPairs += f(i+1,j,nums[i]-j)\n\n dp[i][prev1][prev2] = totalPairs % (1e9 + 7)\n return dp[i][prev1][prev2]\n\n \n return int(f(0,0,50))\n # return self.monotonic\n\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Python3'] | 0 |
find-the-count-of-monotonic-pairs-i | DP + Prefix in Time O(NM) || Space O(M), Beat 99% || 91%🔥 | dp-prefix-in-time-onm-space-om-beat-99-9-d0jw | Intuition\n Describe your first thoughts on how to solve this problem. \nassume M = Max_element\nUsing DP by n * M array\n# Approach\n Describe your approach to | hsu_1997 | NORMAL | 2024-08-17T07:26:23.327721+00:00 | 2024-08-17T07:30:42.095383+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nassume M = Max_element\nUsing DP by n * M array\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach amount in dp[i][j] is insert j at the last monotonically non-decreasing arr1.\nWe can count the number in monotonically non-increasing arr2 by nums[i]- j\n\nEach round, we find the index\n\narr1 limit by accumulate dp[i-1][0] to dp[i-1][d]\narr2 limit by accumulate dp[i-1][0] to dp[i-1][nums[i-1] - (nums[i] - j)]\n\nIf both smaller than 0, this solution is non-valid\nSo we get index = min({j, nums[i-1] - (nums[i] - j), M})\n\nBy prefix every round, We can get accumulated number by acc[index] in O(1)\n\nThe answer is dp[i-1][0] to dp[i-1][M], we can just return acc.back()\n# Complexity\n- Time complexity: O(n * M)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int M = *max_element(nums.begin(), nums.end());\n int n = nums.size();\n int MOD = 1e9+7;\n vector<int> acc(M + 1, 0);\n vector<int> temp_acc(M + 1, 0);\n int count = 0;\n for (int j = 0; j <= M; j++){\n if (j <= nums[0]) acc[j] = j + 1;\n }\n for (int i = 1; i < n; i++){\n count = 0;\n int dp;\n for (int j = 0; j <= M; j++){\n if (j > nums[i]) dp = 0;\n else{\n int index = min({j, nums[i-1] - (nums[i] - j), M});\n if (index < 0) dp = 0;\n else dp = acc[index];\n }\n count = (count + dp) % MOD;\n temp_acc[j] = count;\n }\n swap(acc, temp_acc);\n }\n return acc.back();\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Prefix Sum', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | [C++] DP | c-dp-by-ericyxing-pp26 | Code\n\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n long long mod = 1e9 + 7, ans = 0;\n int n = nums.size();\n v | EricYXing | NORMAL | 2024-08-16T22:36:52.531002+00:00 | 2024-08-16T22:36:52.531033+00:00 | 0 | false | # Code\n```\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n long long mod = 1e9 + 7, ans = 0;\n int n = nums.size();\n vector<vector<long long>> dp(n, vector<long long>(51, 0));\n for (int j = 0; j <= nums[0]; j++)\n dp[0][j] = 1;\n for (int i = 1; i < n; i++)\n {\n long long s = 0, k = 0;\n for (int j = 0; j <= nums[i]; j++)\n {\n while (k <= nums[i - 1] && k <= j && nums[i - 1] - k >= nums[i] - j)\n {\n s = (s + dp[i - 1][k]) % mod;\n k++;\n }\n dp[i][j] = s;\n }\n }\n for (int j = 0; j <= nums[n - 1]; j++)\n ans = (ans + dp[n - 1][j]) % mod;\n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ optimal Solution✅✅|Space optimization | c-optimal-solutionspace-optimization-by-9tikk | 3D DP SOLUTION \n\nclass Solution {\npublic:\n const long long MOD = 1e9 + 7;\n vector<vector<vector<long long>>> memo;\n\n long long solve(int ind, lo | Jayesh_06 | NORMAL | 2024-08-16T10:06:45.174286+00:00 | 2024-08-16T10:06:45.174322+00:00 | 10 | false | # 3D DP SOLUTION \n```\nclass Solution {\npublic:\n const long long MOD = 1e9 + 7;\n vector<vector<vector<long long>>> memo;\n\n long long solve(int ind, long long mn, long long mx, vector<int>& nums) {\n if (ind >= nums.size()) {\n return 1; }\n \n \n if (memo[ind][mn][mx] != -1) {\n return memo[ind][mn][mx];\n }\n\n long long ans = 0;\n int a = nums[ind];\n\n for (long long i = mn; i <= a; i++) {\n long long b = a - i;\n if (b <= mx) {\n ans = (ans + solve(ind + 1, i, b, nums)) % MOD;\n }\n }\n\n memo[ind][mn][mx] = ans;\n return ans;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n \n memo.resize(n, vector<vector<long long>>(51, vector<long long>(51, -1)));\n \n long long ct = 0;\n for (int i = 0; i <= nums[0]; i++) {\n ct = (ct + solve(1, i, nums[0] - i, nums)) % MOD;\n }\n return ct;\n }\n};\n```\n\n\n\n\n---\n\n\n# 2D DP SOLUTION OPTIMIZATION FROM 3D->2D\nHere i have calculate prev2 from prev2 because prev1+prev2=sum.so i can easily calculate prev2 from prev1 .In this way i have reduce space from 3d to 2d .but Time complexity is same .TC is O(N*50*50) where N is size of vector v.\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dp[2001][52];\n int solve(int i, int n, vector<int>& v, int prev1) {\n if (i == n)\n return 1;\n if (dp[i][prev1] != -1)\n return dp[i][prev1];\n int ans = 0,prev2=(i==0)?50:v[i-1]-prev1;\n for (int j = prev1; j <= v[i]; j++) {\n int x1 = j;\n int x2 = v[i] - j;\n if (x1 >= prev1 && x2 <= prev2) {\n ans = (ans + solve(i + 1, n, v, x1)) % mod;\n }\n }\n return dp[i][prev1] = ans;\n }\n int countOfPairs(vector<int>& v) {\n int n = v.size();\n memset(dp, -1, sizeof(dp));\n int ans = solve(0, n, v, 0);\n return ans;\n }\n};\n```\n# Like post if like my solution and approach\u2705\n | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'Combinatorics', 'Prefix Sum', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | DP Memorization Solution C++✅✅ | dp-memorization-solution-c-by-jayesh_06-8mna | \n# Code\n\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dp[2001][52][52];\n int solve(int i, int n, vector<int>& v, int prev1, int prev2) {\n | Jayesh_06 | NORMAL | 2024-08-16T09:54:53.369283+00:00 | 2024-08-16T09:54:53.369320+00:00 | 1 | false | \n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int dp[2001][52][52];\n int solve(int i, int n, vector<int>& v, int prev1, int prev2) {\n if (i == n)\n return 1;\n if (dp[i][prev1][prev2] != -1)\n return dp[i][prev1][prev2];\n int ans = 0;\n for (int j = prev1; j <= v[i]; j++) {\n int x1 = j;\n int x2 = v[i] - j;\n if (x1 >= prev1 && x2 <= prev2) {\n ans = (ans + solve(i + 1, n, v, x1, x2)) % mod;\n }\n }\n return dp[i][prev1][prev2] = ans;\n }\n int countOfPairs(vector<int>& v) {\n int n = v.size();\n memset(dp, -1, sizeof(dp));\n int ans = solve(0, n, v, 0, 50);\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'Combinatorics', 'Prefix Sum', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | [Java] Bottom up DP solution 50 * 50 * N solution | java-bottom-up-dp-solution-50-50-n-solut-0cut | \n\n# Approach\nSame as DFS Memo, for each dp[v1][v2] calculate sum of all previous valid pairs at i - 1 position \n\n# Complexity\n- Time complexity: O(51 * 51 | yrq | NORMAL | 2024-08-15T18:47:40.414118+00:00 | 2024-08-16T17:24:43.568494+00:00 | 10 | false | \n\n# Approach\nSame as DFS Memo, for each dp[v1][v2] calculate sum of all previous valid pairs at i - 1 position \n\n# Complexity\n- Time complexity: O(51 * 51 * N)\n\n- Space complexity: O(51 * 51)\n# Code\n```\nclass Solution {\n public int countOfPairs(int[] nums) {\n int n = nums.length;\n if(n == 1) {\n return nums[0] + 1;\n }\n int mod = 1000_000_007;\n long[][] dp = new long[51][51];\n for(int v1 = 0; v1 <= nums[0]; v1++) {\n dp[v1][nums[0] - v1] = 1;\n }\n long ans = 0;\n for(int i = 1; i < n; i++) {\n long[][] next = new long[51][51];\n long cnt = 0;\n for(int v1 = 0; v1 <= nums[i]; v1++) {\n int v2 = nums[i] - v1;\n for(int preV2 = v2; preV2 <= 50; preV2++) {\n cnt += dp[v1][preV2];\n cnt %= mod;\n }\n for(int preV1 = v1 - 1; preV1 >= 0; preV1--) {\n cnt += dp[preV1][v2];\n cnt %= mod;\n }\n next[v1][v2] = cnt;\n if(i == n - 1) {\n ans += cnt;\n ans %= mod;\n }\n }\n dp = next;\n }\n return (int)ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-count-of-monotonic-pairs-i | Find Count of Monotonic Pairs I [C++]: 2D-DP Approach, Beats 92% of all solutions | find-count-of-monotonic-pairs-i-c-2d-dp-wtk1o | Intuition\n Describe your first thoughts on how to solve this problem. \nYou need to divide the nums array into two monotonic arrays of left and right which sho | amrit2104 | NORMAL | 2024-08-15T14:42:48.128872+00:00 | 2024-08-15T14:42:48.128905+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou need to divide the nums array into two monotonic arrays of left and right which should be non-increasing and non-decreasing respectively. Think of how to do it!!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. After you divide the array is two parts, conside one array, in my case its right array, you decrease 1 from right most element and then check if still your right and left arrays(remember you need to increase 1 in left if you decrease one in right) are monotonic.\n\n2. Check how much you can decrease right array starting from rightmost to left in right array and then store it in a 2D-DP array. \n\n3. Simply iterate for the other positions in right array. Below two lines are the key\n if(left[k] + right[k] - i <= left[k+1] + right[k+1] - j)\n dp[k][i] = (dp[k][i] + dp[k+1][j])%mod;\n\n4. Check for testcases like [2,3,4] & [4,3,2] for better understanding\n\n# Complexity\n- Time complexity: O(n X maxi X maxi)\n- Space complexity: O(n X maxi)\n- maxi -> largest number in right array\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) \n {\n int n=nums.size();\n vector<int> left(n,0);\n vector<int> right(n,0);\n \n long long count=0;\n for(int i=0;i<n;i++)\n {\n right[i] = nums[i]-left[i];\n if(i>0)\n {\n if(right[i]>right[i-1])\n {\n int d = right[i] - right[i-1];\n right[i] = right[i] - d;\n left[i] = left[i] + d;\n }\n if(left[i]<left[i-1])\n {\n int d = 0-left[i] + left[i-1];\n right[i] = right[i] - d;\n left[i] = left[i] + d;\n }\n }\n }\n\n int maxi = *max_element(right.begin(),right.end());\n vector<vector<long long>> dp(n,vector<long long> (maxi+1,0));\n long long mod = 1e9 + 7;\n for(int k=n-1;k>=0;k--)\n {\n for(int i=right[k];i>=0;i--)\n {\n if(k==n-1)\n dp[k][i] = 1;\n else\n {\n for(int j=i;j>=0;j--) \n {\n if(left[k] + right[k] - i <= left[k+1] + right[k+1] - j)\n dp[k][i] = (dp[k][i] + dp[k+1][j])%mod;\n }\n }\n }\n }\n for(int i=0;i<=maxi;i++)\n {\n count = (count + (long long)dp[0][i])%(mod);\n }\n\n return count;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Dynamic Programming | dynamic-programming-by-codecarbon-e7o3 | Intuition\n Describe your first thoughts on how to solve this problem. The problem is essentially about counting pairs in a sequence while adhering to specific | codecarbon | NORMAL | 2024-08-15T11:36:41.320542+00:00 | 2024-08-15T11:36:41.320581+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->The problem is essentially about counting pairs in a sequence while adhering to specific constraints. This often hints at using dynamic programming (DP) to keep track of valid states as we iterate through the list. By using DP, we can break down the problem into smaller subproblems, solve each one, and use those solutions to build up the answer to the original problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. State Representation: Use a 2D DP array where dp[i][j] represents the number of ways to have a valid sequence up to the i-th element with j being the value of the pair for the i-th element.\n2. Initialization: Initialize the DP array for the first element, which can be any value from 0 to nums[0].\n3. Transition: For each subsequent element, update the DP table based on the previous element\'s values and the current constraints. Specifically, for each possible value of the current element, check if it forms a valid pair with the previous element.\n4. Summation: After processing all elements, sum up all possible values for the last element to get the total number of valid pairs.\n\n# Complexity\n- Time complexity:Time complexity is \uD835\uDC42(\uD835\uDC5B\xD7max(\uD835\uDC5B\uD835\uDC62\uD835\uDC5A\uD835\uDC60)^2), where n is the length of the nums array, and max(nums) is the maximum value within the nums array. This is because for each element, we are iterating through all possible pairs, leading to a nested iteration.\n\n- Space complexity: Space complexity is O(n\xD7max(nums)), as we need to store the DP table with dimensions based on the length of the array and the possible values of the elements.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#include <vector>\n#include <cstring>\nusing namespace std;\n\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n int dp[2005][55];\n memset(dp, 0, sizeof(dp));\n\n // Initialize for the first element\n for (int i = 0; i <= nums[0]; ++i) {\n dp[0][i] = 1;\n }\n\n // Fill the dp table iteratively\n for (int i = 1; i < n; ++i) {\n for (int l1 = 0; l1 <= nums[i-1]; ++l1) {\n int l2 = nums[i-1] - l1;\n for (int j = 0; j <= nums[i]; ++j) {\n if (j >= l1 && (nums[i] - j) <= l2) {\n dp[i][j] = (dp[i][j] + dp[i-1][l1]) % mod;\n }\n }\n }\n }\n\n // Sum up all the valid pairs\n int ans = 0;\n for (int i = 0; i <= nums[n-1]; ++i) {\n ans = (ans + dp[n-1][i]) % mod;\n }\n\n return ans;\n }\n};\n\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Easy Dp solution . | easy-dp-solution-by-lcb_2022039-8baf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | LCB_2022039 | NORMAL | 2024-08-15T11:33:37.896559+00:00 | 2024-08-15T11:33:37.896586+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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)$$ -->\nO(N*51*51) = O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N*51*51) = O(N)\n\n# Code\n```\nclass Solution {\npublic: \n int solve(vector<vector<vector<int>>>&dp,vector<int>&nums,int idx,int prev1,int prev2)\n {\n if(idx==nums.size())\n {\n return 1;\n }\n if (dp[idx][prev1][prev2] != -1) {\n return dp[idx][prev1][prev2];\n }\n int ans=0;\n for(int i=0;i<=nums[idx];i++)\n {\n if(prev1<=i && prev2>=nums[idx]-i)\n {\n ans = (ans + solve(dp, nums, idx + 1, i, nums[idx] - i)) % 1000000007;\n\n }\n }\n return dp[idx][prev1][prev2]=ans;\n }\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<vector<int>>>dp(n,vector<vector<int>>(51,vector<int>(51,-1)));\n //idx=0 (this is index)\n //int prev1=0 (since arr1 is in increasing order . so start from lowest value possible)\n //int prev2=51(max), arr2 is in decreasing order so , start from max value possible\n return solve(dp,nums,0,0,50);\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | using 3D DP | using-3d-dp-by-sauravjuyal001-qwkl | Intuition \n\n\n\n\n# Approach \n\npass two variable asc and desc to function with 0,0.\nThese two value will be used to check monotonic arrangement of array we | sauravjuyal001 | NORMAL | 2024-08-14T08:37:57.152011+00:00 | 2024-08-14T08:37:57.152030+00:00 | 9 | false | # Intuition \n\n\n\n\n# Approach \n\npass two variable asc and desc to function with 0,0.\nThese two value will be used to check monotonic arrangement of array we are creating.\nfor each value of num run a from 0 to num[i] loop and check if asc<=i\n and num[i]-i>=desc if true then you find a pair for a index then make all for next index to find more pair. Once you reach end of nums array and there is no more value left then it means you finally find one monotonic array pair and return 1.\n\n\n\n# Complexity\n- Time complexity: O(N^3)\n\n- Space complexity: O(N^2)\n\n# Code\n```\nclass Solution {\npublic:\n\n int dp[2001][51][51];\n int mod=1000000007;\n\n int solve(int i,vector<int>& nums,int ascN,int descN){\n\n if(i>=nums.size())return 1;\n\n if(dp[i][ascN][descN]!=-1)return dp[i][ascN][descN];\n\n int x=nums[i];\n int collect=0;\n\n for(int j=0;j<=x;j++){\n \n int a=j;\n int d=x-j;\n\n if(i==0)collect=((collect%mod)+(solve(i+1,nums,a,d)%mod))%mod;\n else{\n if(ascN<=a && descN>=d)collect=((collect%mod)+(solve(i+1,nums,a,d)%mod))%mod;\n }\n\n }\n \n return dp[i][ascN][descN]=collect;\n }\n\n\n int countOfPairs(vector<int>& nums){\n \n for(int i=0;i<2001;i++)\n for(int j=0;j<51;j++)\n for(int k=0;k<51;k++)\n dp[i][j][k]=-1;\n\n return solve(0,nums,0,0);\n }\n};\n\n\n``` | 0 | 0 | ['Array', 'Math', 'Dynamic Programming', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | 2d dp simple approach with recursion | 2d-dp-simple-approach-with-recursion-by-9jbs3 | \n Describe your first thoughts on how to solve this problem. \n\n# Approach\n So basically in most of the dp problem if we can \n find what are the values that | Arantx1 | NORMAL | 2024-08-13T18:07:30.972958+00:00 | 2024-08-13T18:07:30.972998+00:00 | 0 | false | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n So basically in most of the dp problem if we can \n find what are the values that are changing in every transition than we can easily find the solution.\nchange state are (index,number)\nwe can use the fact that if first number is x than \nother number will be a[i]-x\nnow the only thing left to do is write the recursion statement\n\n\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n\nint n;\n vector<vector<int>>dp;\n int MOD=1e9+7;\n int solve(int pa,int pb,vector<int>&a,int i)\n { \n if(i>=n)\n { // we have found our array so ans+1\n \n return 1;\n }\n int ans=0;\n //this get us all possible value\n for(int ia=pa;ia<=a[i];ia++)\n {\n int x=a[i]-ia;\n \n if(x<=pb)//we have to make the second array decreasing\n { if(dp[i][ia]!=-1)\n ans = (ans + dp[i][ia]) % MOD;\n else \n { dp[i][ia]=solve(ia,x,a,i+1);\n ans = (ans + dp[i][ia]) % MOD; \n }\n }\n }\n\n return ans;\n }\n int countOfPairs(vector<int>& a) {\n n=a.size();int ans=0;\n int x;int mr;\n for(int i=0;i<n;i++)\n {\n mr=max(mr,a[i]);\n }\n dp.resize(n, vector<int>(mr, -1));\n \n return solve(0,INT_MAX,a,0);\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | 2D DP || Recursion + Memoization || Super Easy || C++ | 2d-dp-recursion-memoization-super-easy-c-pukr | Code\n\nclass Solution \n{\npublic:\n int dp[51][2001];\n int mod=1e9+7;\n int f(int prev1, int i, vector<int> &nums)\n {\n if(i==nums.size() | lotus18 | NORMAL | 2024-08-13T06:22:49.613706+00:00 | 2024-08-13T06:32:06.062176+00:00 | 31 | false | # Code\n```\nclass Solution \n{\npublic:\n int dp[51][2001];\n int mod=1e9+7;\n int f(int prev1, int i, vector<int> &nums)\n {\n if(i==nums.size()) return 1;\n if(dp[prev1][i]!=-1) return dp[prev1][i];\n int prev2=(i?nums[i-1]-prev1:nums[0]);\n int ans=0;\n for(int x=prev1; x<=nums[i]; x++)\n {\n if(nums[i]-x<=prev2)\n {\n ans=((long long)ans+f(x,i+1,nums))%mod;\n }\n }\n return dp[prev1][i]=ans;\n }\n int countOfPairs(vector<int>& nums) \n {\n memset(dp,-1,sizeof(dp));\n return f(0,0,nums);\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Easy Recursive 3d Dp Solution | easy-recursive-3d-dp-solution-by-kvivekc-2t3d | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kvivekcodes | NORMAL | 2024-08-13T05:11:21.676770+00:00 | 2024-08-13T05:11:21.676797+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int solve(int a, int b, int i, int n, vector<int>& nums, vector<vector<vector<long long> > >& dp){\n if(i == n) return 1;\n\n if(dp[i][a][b] != -1) return dp[i][a][b];\n long long cnt = 0;\n\n for(int j = a; j <= nums[i]; j++){\n int k = nums[i] - j;\n if(k <= b){\n cnt += solve(j, k, i+1, n, nums, dp);\n cnt %= 1000000007;\n }\n }\n\n return dp[i][a][b] = cnt;\n }\npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<vector<long long> > > dp(n, vector<vector<long long> > (51, vector<long long> (51, -1)));\n return solve(0, 50, 0, n, nums, dp);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Use DP - Easy to Understand - ✅|| Java || 3 ms ||🔥|| Beats 100.00% ||🏆 | use-dp-easy-to-understand-java-3-ms-beat-udyv | Code\n\nclass Solution {\n private static final int MOD = 1_000_000_007;\n\n public int countOfPairs(int[] nums) {\n int[] maxShift = new int[nums. | djqtdj | NORMAL | 2024-08-13T00:56:38.355379+00:00 | 2024-08-13T00:56:38.355406+00:00 | 12 | false | # Code\n```\nclass Solution {\n private static final int MOD = 1_000_000_007;\n\n public int countOfPairs(int[] nums) {\n int[] maxShift = new int[nums.length];\n maxShift[0] = nums[0];\n int currShift = 0;\n\n for (int i = 1; i < nums.length; i++) {\n currShift = Math.max(currShift, nums[i] - maxShift[i - 1]);\n maxShift[i] = Math.min(maxShift[i - 1], nums[i] - currShift);\n if (maxShift[i] < 0) {\n return 0;// Early return optimization\n }\n }\n\n int[][] cases = getAllCases(nums, maxShift);\n\n return cases[nums.length - 1][maxShift[nums.length - 1]];\n }\n\n private int[][] getAllCases(int[] nums, int[] maxShift) {\n int[][] cases = new int[nums.length][];\n\n // Initialize cases for the first element\n cases[0] = new int[maxShift[0] + 1];\n for (int i = 0; i <= maxShift[0]; i++) {\n cases[0][i] = i + 1;\n }\n\n for (int i = 1; i < nums.length; i++) {\n cases[i] = new int[maxShift[i] + 1];\n cases[i][0] = 1;\n\n for (int j = 1; j <= maxShift[i]; j++) {\n int prevCases = j < cases[i - 1].length\n ? cases[i - 1][j]\n : cases[i - 1][cases[i - 1].length - 1];\n\n cases[i][j] = (cases[i][j - 1] + prevCases) % MOD;\n }\n }\n\n return cases;\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
find-the-count-of-monotonic-pairs-i | C++ | DP | c-dp-by-ghost_tsushima-v124 | \n#define mod 1000000007\n\nclass Solution {\npublic:\n \n int getPrev2(int i, int prev1, vector<int> &nums) {\n if (i == 0) return 50;\n re | ghost_tsushima | NORMAL | 2024-08-12T18:07:44.513089+00:00 | 2024-08-12T18:07:44.513117+00:00 | 0 | false | ```\n#define mod 1000000007\n\nclass Solution {\npublic:\n \n int getPrev2(int i, int prev1, vector<int> &nums) {\n if (i == 0) return 50;\n return nums[i-1] - prev1;\n }\n \n int find(vector<vector<int> > &dp, int i, int prev, vector<int> &nums) {\n if(i == nums.size()) return 1;\n \n if (dp[i][prev] != -1) return dp[i][prev];\n \n dp[i][prev] = 0;\n \n int prev1 = prev;\n int prev2 = getPrev2(i, prev1, nums);\n \n for(int j = prev; j <= nums[i]; j++) {\n int newPrev1 = j;\n int newPrev2 = getPrev2(i+1, newPrev1, nums);\n if (newPrev2 >= 0 && newPrev2 <= prev2) {\n dp[i][prev] = (dp[i][prev] + find(dp, i+1, newPrev1, nums))%mod;\n }\n }\n return dp[i][prev];\n }\n \n int countOfPairs(vector<int>& nums) {\n \n vector<vector<int> > dp(nums.size(), vector<int> (51, -1));\n \n return find(dp, 0, 0, nums);\n \n }\n};\n``` | 0 | 0 | [] | 0 |
find-the-count-of-monotonic-pairs-i | easy solution 👇👇 | easy-solution-by-aman2839-q053 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | AMAN2839 | NORMAL | 2024-08-12T16:45:31.222599+00:00 | 2024-08-12T16:45:31.222634+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int m = 1e9+7;\n int solve(vector<int>& nums , int prev1 , int prev2 , int i , vector<vector<vector<int>>> &t){\n if(i == nums.size()){\n return 1;\n }\n if(t[i][prev1+1][prev2+1] != -1){\n return t[i][prev1+1][prev2+1];\n }\n int ans = 0;\n if(prev1 == -1 and prev2 == -1){\n int num = nums[i];\n for(int j = 0 ; j <= num ; j++){\n ans = (ans + solve(nums, j, num-j, i+1, t)) % m;\n }\n }\n else{\n int num = nums[i];\n for(int j = 0 ; j <= num ; j++){\n if(j >= prev1 and num-j <= prev2){\n ans = (ans + solve(nums, j, num-j, i+1, t)) % m;\n }\n }\n }\n return t[i][prev1+1][prev2+1] = ans;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<vector<int>>> t(n, vector<vector<int>>(52, vector<int>(52, -1)));\n return solve(nums , -1 , -1 , 0 , t)%m;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-count-of-monotonic-pairs-i | very easy java | very-easy-java-by-murariambofficial-f36j | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | murariambofficial | NORMAL | 2024-08-12T15:45:47.829631+00:00 | 2024-08-12T15:45:47.829668+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution \n{\n int mod = (int)Math.pow(10,9)+7;\n public int countOfPairs(int[] nums) \n {\n int[][] dp = new int[51][nums.length];\n for(int[] rw:dp)Arrays.fill(rw,-1);\n return (int)(khafa(nums,nums[0],0,dp)%mod);\n }\n public int khafa(int[] nums, int high, int i, int[][] dp)\n {\n if(i>=nums.length)return 1;\n if(dp[high][i]!=-1)return dp[high][i];\n int ans = 0;\n for(int j = high; j>=0; j--)\n {\n if((i!=0 && nums[i]-j<nums[i-1]-high) || nums[i]-j<0)continue;\n ans += khafa(nums,j,i+1,dp);\n ans = ans%mod;\n }\n return dp[high][i]=ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-count-of-monotonic-pairs-i | Beats 100% in Time Complexity | beats-100-in-time-complexity-by-kumarabh-j9gk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kumarabhinav002 | NORMAL | 2024-08-12T15:27:40.196304+00:00 | 2024-08-12T15:27:40.196337+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countOfPairs(int[] nums) {\n int mod = 1000000007, n = nums.length;\n int dp[][] = new int[n][51];\n for (int i = 0; i < dp[0].length && i <= nums[0]; i++) {\n dp[0][i] = 1;\n }\n for (int i = 1; i < dp.length; i++) {\n for (int j = 0; j <= nums[i]; j++) {\n int sum = 0;\n for (int k = 0; k <= j && nums[i] - j <= nums[i - 1] - k; k++) {\n sum = (sum + dp[i - 1][k]) % mod;\n }\n dp[i][j] = sum;\n }\n }\n int ans = 0;\n for (int i = 0; i < dp[n - 1].length; i++) {\n ans = (ans + dp[n - 1][i]) % mod;\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-count-of-monotonic-pairs-i | 76 ms Beats 100 % | 76-ms-beats-100-by-kavyanlavti-kn4l | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | KavyanLavti | NORMAL | 2024-08-12T13:15:45.598465+00:00 | 2024-08-12T13:15:45.598494+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution \n{\n int mod = (int)Math.pow(10,9)+7;\n public int countOfPairs(int[] nums) \n {\n int[][] dp = new int[51][nums.length];\n for(int[] rw:dp)Arrays.fill(rw,-1);\n return (int)(khafa(nums,nums[0],0,dp)%mod);\n }\n public int khafa(int[] nums, int high, int i, int[][] dp)\n {\n if(i>=nums.length)return 1;\n if(dp[high][i]!=-1)return dp[high][i];\n int ans = 0;\n for(int j = high; j>=0; j--)\n {\n if((i!=0 && nums[i]-j<nums[i-1]-high) || nums[i]-j<0)continue;\n ans += khafa(nums,j,i+1,dp);\n ans = ans%mod;\n }\n return dp[high][i]=ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-count-of-monotonic-pairs-i | Recursion+ 2D DP | recursion-2d-dp-by-pushprog-yvgb | \nclass Solution {\npublic:\n using ll = long long;\n ll M=1e9+7;\n ll dp[2001][52];\n ll rec(int i,int aprev,int bprev,vector<int> &v, int mx){\n | Pushprog | NORMAL | 2024-08-12T12:29:14.953475+00:00 | 2024-08-12T12:29:14.953503+00:00 | 17 | false | ```\nclass Solution {\npublic:\n using ll = long long;\n ll M=1e9+7;\n ll dp[2001][52];\n ll rec(int i,int aprev,int bprev,vector<int> &v, int mx){\n int n=v.size();\n if(i==n){return 1;}\n \n if(dp[i][aprev]!=-1){return dp[i][aprev];}\n \n ll res=0;\n \n for(int x=0;x<=v[i];x++)\n {\n int f=0;\n int curra=x,currb=v[i]-x;\n \n if(curra<=mx and curra>=aprev){f++;}\n if(currb>=0 and currb<=bprev){f++;}\n \n if(f==2){\n res=(res+rec(i+1,curra,currb,v,mx))%M;\n }\n }\n \n return dp[i][aprev]=res%M;\n }\n int countOfPairs(vector<int>& v) {\n ll ans=0;\n int n=v.size();\n \n memset(dp,-1,sizeof(dp));\n int mx=v[n-1],aprev=0,bprev=v[0];\n ans=rec(0,aprev,bprev,v,mx);\n \n return ans%M;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C', 'C++'] | 0 |
find-the-count-of-monotonic-pairs-i | Using tabulation | using-tabulation-by-venkatarohit_p-l6j0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | venkatarohit_p | NORMAL | 2024-08-12T09:36:13.478312+00:00 | 2024-08-12T09:36:13.478332+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\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\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countOfPairs(int[] nums) {\n int[][] dp=new int[nums.length][51];\n for(int i=0;i<=nums[0];i++){\n dp[0][i]=1;\n }\n for(int i=1;i<nums.length;i++){\n for(int curr_num=0;curr_num<=nums[i];curr_num++){\n int ways=0;\n for(int prev_num=0;prev_num<=50;prev_num++){\n if(prev_num<=curr_num && nums[i-1]-prev_num>=nums[i]-curr_num){\n ways=(ways+dp[i-1][prev_num])%(1000000007);\n }\n }\n dp[i][curr_num]=ways;\n }\n }\n int totalways=0;\n for(int i=0;i<=50;i++){\n totalways=(totalways+dp[nums.length-1][i])%(1000000007);\n }\n return totalways;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.