JavaScript DP Beats 100% with explanation
The basic idea here is that we\'re keeping track of two arrays: one that lists the number of integers after rating[i] that are greater than rating[i], and anoth
The basic idea here is that we\'re keeping track of two arrays: one that lists the number of integers after rating[i] that are greater than rating[i], and another that lists the number of integers after rating[i] that are less than rating[i]. We do this with nested for loops. \n\nFor the input `[2,5,3,4,1]`, this yields the following arrays:\n\n```\n[ 3, 0, 1, 0, 0 ]\n[ 1, 3, 1, 1, 0 ]\n```\n\nWe then use another nested forloop, where `i` only increases up until the third to last integer in rating. If `rating[j] > rating[i]` then we know we can add greaterThan[j] teams to our total number of teams. The "teams" this represents is effectively (Player i, Player j, Player x where x is a number after j greater than j). \n\nSimilarly, If `rating[j] < rating[i]`, then we can add lessThan[j] number of teams to our result. \n\n**Full Solution:**\n```\n/**\n * @param {number[]} rating\n * @return {number}\n */\nconst numTeams = (rating) => {\n    if(rating.length < 3) return 0;\n    let result = 0;\n\n    let greaterThan = new Array(rating.length).fill(0);\n    let lessThan = new Array(rating.length).fill(0);\n\n    for(let i = 0; i < rating.length; i++) {\n        for(let j = i + 1; j < rating.length; j++) {\n            if(rating[j] > rating[i]) {\n                ++greaterThan[i];\n            } else if(rating[j] < rating[i]) {\n                ++lessThan[i];\n            }\n        }\n    }\n        \n    for(let i = 0; i < rating.length - 2; i++) {\n        for(let j = i + 1; j < rating.length; j++) {\n            if(rating[j] > rating[i]) {\n                result += greaterThan[j];\n            } else if(rating[j] < rating[i]) {\n                result += lessThan[j];\n            }\n        }\n    }\n\n    return result;    \n};\n```
[]