Easy C++ Solution | Simple approach | no trees no dp only maths | with Video Explanation
Video Solution\nhttps://youtu.be/rSd_8XRW6Us?si=5SzuMhNlCKotrcR1\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involve
# Video Solution\nhttps://youtu.be/rSd_8XRW6Us?si=5SzuMhNlCKotrcR1\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves counting the number of teams of 3 soldiers that can be formed from an array of ratings such that the ratings of the soldiers form either an increasing or a decreasing sequence. The intuitive approach is to use three nested loops, where the middle loop iterates over each possible "middle" soldier of the team, and the inner loops count the number of soldiers to the left and right that satisfy the conditions for forming a team.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization:\n\n- Initialize teams to 0 to keep track of the number of valid teams.\n2. Outer Loop:\n\n- Iterate over each soldier as the middle soldier (index j) from 1 to n-2 (since we need at least one soldier on both sides).\n3. Inner Loops:\n\n- For each middle soldier j, count the number of soldiers to the left (i) that are smaller and larger.\n- Similarly, count the number of soldiers to the right (k) that are smaller and larger.\n4. Count Teams:\n\n- The number of valid increasing teams with j as the middle soldier is the product of the number of smaller soldiers on the left and larger soldiers on the right.\n- The number of valid decreasing teams with j as the middle soldier is the product of the number of larger soldiers on the left and smaller soldiers on the right.\n- Add these products to teams.\n# Complexity\n- Time complexity:$$O(n^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int numTeams(vector<int>& ratings) {\n\n        int n = ratings.size();\n\n        int teams = 0;\n\n        for(int j = 1; j<n-1;j++){\n\n            int smallerLeft = 0;\n            int largerRight = 0;\n            int smallerRight = 0;\n            int largerLeft = 0;\n\n            for(int i=0;i<j;i++){\n\n                if(ratings[i] > ratings[j]){\n                    largerLeft++;\n                }else{\n                    smallerLeft++;\n                }\n                \n            }\n\n            for(int k =j+1;k<n;k++){\n\n                if(ratings[k] > ratings[j]){\n                    largerRight++;\n                }else{\n                    smallerRight++;\n                }\n                \n            }\n\n            teams += (smallerLeft * largerRight) + (largerLeft * smallerRight);\n            \n        }\n\n        return teams;\n        \n    }\n};\n```
['C++']