Home > Back-end >  Find Maximum Difference using array
Find Maximum Difference using array

Time:11-12

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
    int num;
    long long max = 0;
    long long min;
    cin >> num;
    long long *ptr = new long long[num];
    for (int x = 0; x < num; x  )
    {
        cin >> ptr[x];
    }
    cout << "ptr for first elemnt" << endl;
    cout << ptr[0];
    for (int x = 1; x < num; x  ) // 1 4 6 3 min 1  max 1
    {
        max = ptr[0];
        if (max < ptr[x])
            max = ptr[x];
        min = ptr[0];
        if (min > ptr[x])
            min = ptr[x];
    }

    cout << "max value " << max;
    cout << "Min value is " << min;
    cout << max - min; // biggest number minues smallest number

    return 0;
}

I try to find max difference between number in array but so i get max and min number in array which have biggest difference but i when i check the max value and min value i find them wrong so why that happen?

CodePudding user response:

for (int x = 1; x < num; x  ) // 1 4 6 3 min 1  max 1
{
    max = ptr[0];
    if (max < ptr[x])
        max = ptr[x];
    min = ptr[0];
    if (min > ptr[x])
        min = ptr[x];
}

Try this instead:

max = ptr[0];
min = ptr[0];
for (int x = 1; x < num; x  ) // 1 4 6 3 min 1  max 1
{
    if (max < ptr[x])
        max = ptr[x];
    if (min > ptr[x])
        min = ptr[x];
}

The problem is that you're reseting min and max each time, so it's basically going to become either ptr[0] or ptr[n] with no possible value in between.

This might not be your only problem, but it's a start.

CodePudding user response:

Alternatively, you can use the minmax_element algorithm to get the array's min and max values:

#include <algorithm> // minmax_element
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    int num;
    long long max = 0;
    long long min;
    cin >> num;
    long long *ptr = new long long[num];
    for (int x = 0; x < num; x  )
    {
        cin >> ptr[x];
    }
    cout << "ptr for first element: " << ptr[0] << "\n";

    auto [min_it, max_it] = std::minmax_element(ptr, ptr   num);
    cout << "max - min: " << *max_it - *min_it << "\n";

    return 0;
}

Demo

CodePudding user response:

what i am trying to do is sort the array first and then subtract the first number from the last number (hoping you know about pointers)

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    int num ; 
    cin >> num ;
    int*ptr = new int[num];
    for(int i=0 ; i<num ; i  ){
        cin >> ptr[i];
    }
    sort(ptr , ptr num);
    int max_diff = ptr[num-1] - ptr[0];
    cout << "max difference is " << max_diff;
    return 0;
}
  • Related