Intuition + Algorithm Explanation + Understandable  Code
Intuition\nFew things to notice.\n\n1. The size of nums is 1000.\n2. We asked to sort each and every subarray..instead of doing that we can use set.\n\n# Approa
# Intuition\nFew things to notice.\n\n1. The size of nums is 1000.\n2. We asked to sort each and every subarray..instead of doing that we can use set.\n\n# Approach\n1. Lets start making all subarray which start at index 0.\n2. insert nums[0] in our set.\n3. for subsequent indexs we will check a number greater than it and number smaller than it in the set which we can do using simply set upper bound and lower bound. cause these are the only two numbers which get affected by insertion.\n4. if those two number already forming a valid pair i.e nums[i]<=nums[i+1] we need to do ans-- cause it wont be counted for subsequent subarrays.\n5. now check the validity of our current number with its neighbours and increse answers accordingly.\n6. Simmilarly like 0 Repeat this for all indexes 1,2,3,... indicating array starts from 1,2,...resp.\n\n# Complexity\n- Time complexity:\nO(n^2*log(n))\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n      ios_base::sync_with_stdio(false);\n      cin.tie(NULL);\n\n       int n = nums.size();\n\n       long long res = 0;\n\n\n        for(int i=0;i<n;i++){\n\n         set<int> s;\n         s.insert(nums[i]);\n         long ans = 0;\n          cout<<i<<endl;\n          for(int j=i+1;j<n;j++){\n              int x = nums[j];\n              int y = x;\n              int z = x;\n              bool flag = true;\n              \n              if(s.upper_bound(x) != s.end()){\n                z = *s.upper_bound(x);\n              }\n              else{\n                flag = false;\n              }\n\n              if(((s.upper_bound(x))) != s.begin()){\n                y = *(--(s.upper_bound(x)));\n              }\n              else{\n                flag = false;\n              }\n\n\n\n              if((z - y)>1 && flag) {\n                ans--;\n              }\n\n              if((x-y)>1){\n                ans++;\n              }\n\n              if((z-x)>1){\n                ans++;\n              }\n\n              res += ans;\n              s.insert(x);\n          }\n        }\n\n        return res; \n    }\n};\n\n\n// 0\n// 3 2 3\n// 1 1 2\n// 4 3 4\n// 1\n// 1 1 3\n// 4 3 4\n// 2\n// 4 1 4\n// 3\n```
['C++']