Similar to problem max area in Histogram
It is similar to the problem of finding maximum area in a histogram,.\nsimply do the following things -\n Find the nearest position to the left that is smaller 
It is similar to the problem of finding maximum area in a histogram,.\nsimply do the following things -\n* Find the nearest position to the left that is smaller than current position.\n* Find the nearest position to the right that is smaller than current position.\n* Get the subarray (inbetween above 2 positions) sum with prefix-sum.\n**Finding next and previous elements using brute force**   (TLE)\n```\nclass Solution {\npublic:\n    int maxSumMinProduct(vector<int>& nums) {\n        long long  n = size(nums);\n        vector<long long>pre(n+1,0);\n        for(long long  i=0;i<n;i++){\n            pre[i+1] = pre[i]+nums[i];\n         }\n        long long ans = 0;\n        for(long long  i=0;i<n;i++){\n            long long  j=i-1;\n            while(j>=0 && nums[i]<=nums[j]) j--;\n            long long  k = i+1;\n            while(k<n && nums[i]<=nums[k]) k++;\n             ans = max(ans,nums[i]*(pre[k]-pre[j+1]));\n         }\n        long long M = 1e9+7;\n        return ans%(M);\n    }    \n};\n```\n**Using Stack**\n```\nclass Solution {\npublic:\n    int maxSumMinProduct(vector<int>& nums) {\n        long long  n = size(nums);\n        vector<long long>pre(n+1,0),l(n,-1),r(n,n);\n        for(long long  i=0;i<n;i++){\n            pre[i+1] = pre[i]+nums[i];\n         }\n        stack<int>st;\n        for(int i=0;i<n;i++){\n            while(size(st) && nums[st.top()]>nums[i]){\n                r[st.top()]=i;\n                st.pop();\n            }\n            st.push(i);\n        }\n        while(size(st)) st.pop();\n        for(int i=n-1;i>=0;i--){\n            while(size(st) && nums[st.top()]>nums[i]){\n                l[st.top()]=i;\n                st.pop();\n            }\n            st.push(i);\n        }\n        long long ans = 0;\n        for(long long  i=0;i<n;i++){\n             ans = max(ans,nums[i]*(pre[r[i]]-pre[l[i]+1]));\n         }\n        long long M = 1e9+7;\n        return ans%(M);\n    }    \n};\n```\n**Pls Upvote if you found it useful**
['Stack']