Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Last Updated on March 29, 2022 by Ria Pathak

CONCEPTS USED:

Greedy algorithm

DIFFICULTY LEVEL:

Easy.

PROBLEM STATEMENT(SIMPLIFIED):

Arnab is given a number N, he is asked to remove one digit and print the largest possible number.Help Arnab find the number.

See original problem statement here

For Example :

5
1234
2945
9273
3954
19374

234
945
973
954
9374

SOLVING APPROACH:

Since only one digit is to be removed, brute force will be a sufficient approach here.

Iterate through the length of the given number(the number of digits is the length) and keep removing digits one by one.

Take the maximum of all the number obtained .

SOLUTIONS:

#include <stdio.h>
    long long int solve(long long int n)
    {
    long long int m=1,mi=-1,a,b;
    while(m<n)
    {
    a=n%m;
    b=((long long int)n/(m*10))*(m);
    if((a+b)>mi)
      mi=a+b;
    m*=10;
    }
    return mi;
    }
    int main()
    {  
    int t;
    scanf("%d",&t);
    while(t--)
    {
    long long int n;
    scanf("%lld",&n);
 
    printf("%lld\n",solve(n));
    } 
    return 0;
    }
#include <bits/stdc++.h>
    using namespace std;
    long long int solve(long long int n)
    {
     long long int m=1,mi=-1,a,b;
      while(m<n)
    {
    a=n%m;
    b=((long long int)n/(m*10))*(m);
    if((a+b)>mi)
      mi=a+b;
    m*=10;
    }
    return mi;
     }
    int main()
    {  
    int t;
     cin>>t;
     while(t--)
    {
    long long int n;
    cin>>n;

    cout<<solve(n)<<"\n";
    } 
    return 0;
    }
import java.util.*;
      import java.io.*;

    class largest_number {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int t= sc.nextInt();
        while(t-- >0 ){
           long n = sc.nextInt();
            long m=1,mi=-1,a,b;
      while(m<n)
    {
    a=n%m;
    b=((long)n/(m*10))*(m);
    if((a+b)>mi)
      mi=a+b;
    m*=10;
    }
                System.out.println(mi);

        }
    }
    }
# your code goes here
def solve(n):

	m = 1
	mi = -1
	while m<n:
		a = n % m
		b = n // (m * 10) * m
		if a + b > mi:
			mi = a + b
		m *= 10
	return mi

for _ in range(int(input())):

	n = int(input())
	print(solve(n))


[forminator_quiz id="1461"]

This article tried to discuss Greedy algorithm. Hope this blog helps you understand and solve the problem. To practice more problems on Greedy algorithm you can check out MYCODE | Competitive Programming.

Leave a Reply

Your email address will not be published. Required fields are marked *