Brute force solution beats 100%
Disclaimer : this is not the optimal solution, i just saw that most of the solutions are not in this technique\n\n# Intuition\n Describe your first thoughts on 
Disclaimer : this is not the optimal solution, i just saw that most of the solutions are not in this technique\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nintially i tried brute force approach by finding all possible subarray and make a frequency while moving , now we have frequency array which means a sorted array , and for every subarray i have calculated imbalance numbers with this sorted array which takes o(n) time. of course it gives you TLE, so i tried to optimise this calculation of finding imbalance numbers\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nyou are having an array (1,3)\nwhen does the imbalance increases and decreases?\nif you insert 2 , then (1,2,3) , imbalance decreases right?\nelse if you insert 5 , then (1,3,5), imbalance increases right?\n\nso the position matters,\nif you are inserting between two elements(2-1,2,2+1) then it reduces imbalance count by -1 which means count-1\n\nif you insert separately where no adjacent elements are availabe then it is count +1 \n\nthese are the cases\n![WhatsApp Image 2023-07-02 at 7.27.28 PM.png](https://assets.leetcode.com/users/images/38d03a07-b9f3-4aeb-8c56-edcd13cb28de_1688306677.011408.png)\n\n\nand the last things to note, while inserting first time we should not consider about imbalance numbers, if there is an already element availabe in place of inserting element then it does not affect imbalance count (because the element already made its impact on imbalance count)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n\n    int sumImbalanceNumbers(vector<int>& nums) {\n        // generating all possible subarrays\n        int n = nums.size();\n        vector<int> freq(n+1, 0 );\n        int res = 0;\n        for(int start = 0; start<n ; start++){\n            int curr = 0;\n            freq[nums[start]]++;\n            for(int end = start+1; end<n ; end++){\n                freq[nums[end]] ++ ;\n                curr+= help(freq, nums[end]);\n                res+= curr;\n            }\n            freq.clear();\n            freq.resize(n+1,0);\n        }\n        return res;\n    }\n    int help(vector<int>& fre, int num){\n        int left = num==1?0 : fre[num-1];\n        int right = num==fre.size()-1?0 : fre[num+1];\n        \n        if(left && right && fre[num]==1) return -1; // closed\n        return !left && !right && fre[num]==1? 1 : 0; //opened\n    }\n};\n```
['C++']