কম্পিউটার

C++ প্রোগ্রাম সর্বাধিক সাবঅ্যারে যোগফল O(n^2) সময় (অনেক পদ্ধতি) খুঁজে বের করতে


সর্বাধিক সাবয়ারের যোগফল O(n^2) সময় (অনেক পদ্ধতি) খুঁজে পেতে আমরা একটি C++ প্রোগ্রাম তৈরি করব।

অ্যালগরিদম

Begin
   Take the array elements as input.
   Make a loop for the length of the sub-array from 1 to n, within this loop,
   Make another loop nested with the previous one, calculate the sum of first sub-array of that length.
   For remaining sub-array sum, add the next element to the sum and subtract the first element of that sub-array.
   Compare it with the global max and update if found out to be more.
   Print the max sub-array and their sum as a result.
End.

উদাহরণ কোড

#include<iostream>
using namespace std;
int main() {
   int n, i, j, m=-1, s, ini_m, fi_m;
   cout<<"\nEnter the number of data element in the array: ";
   cin>>n;
   int a[n];
   for(i = 0; i < n; i++) {
      cout<<"Enter element "<<i+1<<": ";
      cin>>a[i];
   }
   for(i = 1; i < n+1; i++) {
      s = 0;
      for(j = 0; j < n; j++) {
         if(j < i)
            s += a[j];
         else
            s = s+a[j]-a[j-i];
         if(m< s) {
            ini_m = j-i+1;
            fi_m = j;
            m = s;
         }
      }
   }
   cout<<"\nThe maximum sub array is: ";
   for(i = ini_m; i <= fi_m; i++)
      cout<<a[i]<<" ";
      cout<<"\nThe maximum sub-array sum is: "<<m;
}

আউটপুট

Enter the number of data element in the array: 10
Enter element 1: 1
Enter element 2: -2
Enter element 3: 3
Enter element 4: -4
Enter element 5: 5
Enter element 6: -6
Enter element 7: 7
Enter element 8: 8
Enter element 9: -9
Enter element 10: 10
The maximum sub array is: 7 8 -9 10
The maximum sub-array sum is: 16

  1. C++ এ গভীরতম নোডের যোগফল খুঁজে বের করার জন্য প্রোগ্রাম

  2. একটি গ্রাফে সর্বাধিক কাট খুঁজে পেতে C++ প্রোগ্রাম

  3. অ্যারে পার্টিশন করার পদ্ধতি দ্বারা kth ক্ষুদ্রতম উপাদান খুঁজে বের করার জন্য C++ প্রোগ্রাম

  4. পাইথনে m দ্বারা সাবয়ারের মডিউলের সর্বাধিক যোগফল খুঁজে বের করার প্রোগ্রাম