Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the largest three-digits number "within" a number

For this question, I need to find the largest three-digit number within a larger number.

Sample Test Case 1:
534535
Output:
535


Sample Test Case 2 :
23457888976
Output :
976

I've tried the following code:
        #include <iostream>
        using namespace std;
        int main() {
        int num;
        cin>>num;
        int len= to_string(num).length();
        int arr[10],lnum=0,max=0;
        for (int i =len-1;i>=0;i--)
        {
        arr[i] = num%10;
        num =num/10;    //to convert int into array
        }
        for (int i=0;i<len-2;i++)
        {
        if (arr[i] >arr[i+1])
            lnum = arr[i]*100+arr[i+1]*10+arr[i];
        if (lnum>max)
            max= lnum;  
        }
        cout<<max;
        return 0;
    }

Although this code seems to work for Test Case 1, it doesn't work for most of the inputs.

(Please do help with this too. )
1. This is for numbers with 10-digits only (that too, most of it have wrong output). What to do in case of bigger numbers?
2. Is there any better way to convert the integer into an array? Or will a string array work in similar way?
3. It's really slow, can anyone help me figure out how to speed this up?
Thanks for any help !!
like image 693
Shinichi Avatar asked Jan 27 '26 07:01

Shinichi


1 Answers

#include <iostream>
#include <string>
using namespace std;
int main() {
    int i, n;
    string s;
    cin >> s;
    n = (int)s.size();
    if(n<3){
        /* there are less than 3 digits in the input number
        Here, you can print the number itself as it will be largest number or
        print -1 which can state that no 3 digit number exists.
        */
        cout<<-1;
        return 0;
    }
    int maxans = (s[0]-'0')*100 + (s[1]-'0')*10 + (s[2]-'0');
    // storing the first 3 digits as the maximum answer till now.
    int prev = maxans;
    for(i = 3;i<n;i++){
        int cur = (prev%100)*10 + (s[i]-'0'); // using %100 to extract the last two digits and then multiplying by 10 and adding the ith digit to make the next 3 digit number.
        maxans = max(maxans, cur);
        prev = cur;
    }
    cout<<maxans;
    return 0;
}

This code is of time complexity O(n) where n is the length of input string and space complexity O(1)

like image 96
risingStark Avatar answered Jan 29 '26 19:01

risingStark