Advertisement
skb50bd

Maximum_Subarray_Problem [Brute_Force (Iterative)]

Sep 28th, 2016
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //////////////////////////////////////////////////////////////
  2. //      Author: Shakib Haris                                //
  3. //      Problem: Maximum Subarray Problem                   //
  4. //      Solution: Brute-Force Approach // O(n^2)            //
  5. //      Input: The Price(s), not the Change(s) of Prices    //
  6. //      Output: Maximum Subarray                            //
  7. //////////////////////////////////////////////////////////////
  8.  
  9. #include <bits/stdc++.h>
  10. #define SIZE 5
  11. using namespace std;
  12.  
  13. void bruteForce(int A[], int lo, int hi, int &start, int &end) {
  14.     int maxDiff = INT_MIN;
  15.  
  16.     for (int i = lo; i < hi; i++)
  17.         for (int j = i + 1; j <= hi; j++)
  18.             if (A[j] - A[i] > maxDiff) {
  19.                 start = i;
  20.                 end = j;
  21.                 maxDiff = A[j] - A[i];
  22.             }
  23. }
  24.  
  25.  
  26. void display (int A[], int lo, int hi) {
  27.     for (int i = lo; i <= hi; i++)
  28.         cout << A[i] << " ";
  29.     cout << endl << endl;
  30. }
  31.  
  32.  
  33. int main() {
  34.     int A[SIZE], start, end;
  35.  
  36.     for (int i = 0; i < SIZE; i++)
  37.         cin >> A[i];
  38.  
  39.     cout << "Original Array: ";
  40.     display(A, 0, SIZE - 1);
  41.  
  42.     bruteForce(A, 0, SIZE - 1, start, end);
  43.  
  44.     cout << "Sub-array: ";
  45.     display(A, start, end);
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement