jayati

Maximum Product Subarray

Nov 16th, 2023
885
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. // } Driver Code Ends
  7. //User function template for C++
  8. class Solution{
  9. public:
  10.  
  11.     // Function to find maximum product subarray
  12.     long long maxProduct(vector<int> arr, int n) {
  13.         // code here
  14.         long long ans=arr[0];
  15.         long long mx=arr[0];
  16.         long long mn=arr[0];
  17.        
  18.         for(int i=1;i<n;i++)
  19.         {
  20.             if(arr[i]<0)
  21.             {
  22.                 swap(mx,mn);
  23.             }
  24.             mx = max((long long)arr[i],arr[i]*mx);
  25.             mn = min((long long)arr[i],arr[i]*mn);
  26.             ans = max(ans,mx);
  27.         }
  28.         return ans;
  29.     }
  30. };
  31.  
  32. //{ Driver Code Starts.
  33.  
  34. int main() {
  35.     int t;
  36.     cin >> t;
  37.     while (t--) {
  38.         int n, i;
  39.         cin >> n;
  40.         vector<int> arr(n);
  41.         for (i = 0; i < n; i++) {
  42.             cin >> arr[i];
  43.         }
  44.         Solution ob;
  45.         auto ans = ob.maxProduct(arr, n);
  46.         cout << ans << "\n";
  47.     }
  48.     return 0;
  49. }
  50. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment