Jump to content

Primele doua maxime din sirul de n numere?


Niram

Recommended Posts

Cum pot modifica programul astfel incat sa retin primele doua maxime din sirul de n numere, folosind aceeasi metoda (adica citesti un numar si il compare cu cele 2 maxime)?

#include<iostream>
using namespace std;
int main()
{
    int max=0, a, n, i;
    cout<<"Please insert the count of number from sting:";
    cin>>n;
    for(i=1; i<=n; i++)
    {
        cout<<"Please insert a number of the string:";
        cin>>a;
        if(max<a) max=a;
    }
    cout<<"The max number is:"<<max;
    return 0;
}

Multumesc!

Link to comment
Share on other sites

Salut. Se foloseste metoda Greedy, in care avem:

mx1 - Cel mai mare numar

mx2 - Al doilea cel mai mare numar (mx2 <= mx1)

Asadar, avem:

#include <iostream>

using namespace std;

int N, mx1, mx2, nr;

int main() {
    cin >> N;
    
    for(int i = 1; i <= N; ++i) {
        cin >> nr;
        
        if(mx1 < nr) {
            mx2 = mx1;
            mx1 = nr;
        }
        else {
            if(mx2 < nr) {
                mx2 = nr;
            }
        }
    }
    
    cout << mx1 << ' ' << mx2 << '\n';
    
    return 0;
}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.