简体   繁体   中英

Maximum Integer Value java

I was trying to solve the Maximum Integer Value problem form Geeksforgeeks .
The problem states the following: Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.

Input: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.

Output: For each testcase, print the maximum value obtained.

this is what I did:

class GFG
 {
    public static void sort(int[] numbers)
    {
        int n = numbers.length; 
        for (int i = 1; i < n; ++i) 
        { 
            int key = numbers[i]; 
            int j = i - 1; 

            while (j >= 0 && numbers[j] > key) 
            { 
                numbers[j + 1] = numbers[j]; 
                j = j -1 ; 
            } 
            numbers[j + 1] = key; 
        }

        System.out.println(numbers.length - 1);
    }
    public static void main (String[] args)
     {
        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        int [] maxNum;
        for(int i = 0; i< testCases; i++)
        {
            String numbers = sc.nextLine();
            char[] cNumbers = numbers.toCharArray();
            maxNum = new int [cNumbers.length];
            for(int j = 0; j + 1 < cNumbers.length; j++)
            {
                int sum = 0;
                int mult = 0;
                sum = cNumbers[j] + cNumbers[j + 1];
                mult = cNumbers[j] * cNumbers[j + 1];
                int maxNumber = Math.max(sum, mult);
                maxNum[i] = maxNumber;
            }               
            sort(maxNum);
        }
     }
}

an example of Input: 2 01230 891 My Output: -1 4 Correct Output: 9 73

What is wrong with my code?!

Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.

I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer) So there is a code that works for your output:

public class GFG
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testCases = Integer.valueOf(sc.nextLine());
        for (int i = 0; i < testCases; i++)
        {
            String numbers = sc.nextLine();
            char[] cNumbers = numbers.toCharArray();
            long maxUntilNow = cNumbers[0] - '0';
            for (int j = 1; j < cNumbers.length; j++)
            {
                int numberOfThisPlace = cNumbers[j] - '0';
                maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
                              maxUntilNow * numberOfThisPlace);
            }
            System.out.println(maxUntilNow);
        }
    }
}   

I hope this is what you want.

The idea is to put the operators alternatively and choose the maximum results.

import java.util.Scanner;

    public class Demo {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int testCases = Integer.parseInt(sc.nextLine());
            for (int i = 0; i < testCases; i++) {
                String numbers = sc.nextLine();
                int max = 0;
                for (int j = 0; j + 1 < numbers.length(); j++) {
                    int next = Integer.parseInt(numbers.substring(j, j+1));
                    if (max +  next > max * next)
                        max = max + next;
                    else
                        max = max * next;
                }
                System.out.println(max);
            }
            sc.close();
        }
    }

After the execution of

int testCases = sc.nextInt();

the buffer contains a new line character. So when executing the line

String numbers = sc.nextLine();

it read '\\n' into numbers, so you got -1 as the first output. Also you need to convert character to Integer before using it any arithmetic operations.

sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];

So the above code will give you wrong results.

I tried the following sample and worked.

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String inputAsString = sc.nextLine();
        int testCases = Integer.parseInt(inputAsString);
        int maxNumber = 0;
        for (int i = 0; i < testCases; i++) {
            String numbers = sc.nextLine();
            if(!numbers.matches("\\d+")){
                System.out.println("Only numeric values are expected.");
                continue;
            }
            char[] cNumbers = numbers.toCharArray();
            int sum = 0;
            int mult = 1;
            for (int j = 0; j < cNumbers.length; j++) {
                int nextNumber = Character.getNumericValue(cNumbers[j]);
                sum = sum + nextNumber;
                mult = mult * nextNumber;
                maxNumber = mult > sum ? mult : sum;
                sum = maxNumber;
                mult = maxNumber;
            }

            System.out.println(maxNumber);
        }
        sc.close();
    }

As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time. So, this can be solved in O(n) without using any sorting algorithm. The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*". Here is my solution which got successfully submitted:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
    public static void main (String[] args) {
        Scanner scan = new Scanner(System.in);
        int T = Integer.parseInt(scan.nextLine());
        while(T-- > 0) {
            String str = scan.nextLine();
            maxValue(str);
        }
    }

    static void maxValue(String str) {
        long maxNumber = 0;
        for(int i = 0; i < str.length(); i++) {
            int n = Character.getNumericValue(str.charAt(i));
            if (maxNumber == 0 || maxNumber == 1 ||
                n == 0 || n == 1) {
                maxNumber += n;
            } else {
                maxNumber *= n;
            }
        }
        System.out.println(maxNumber);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM