(Coderbyte) Array Addition I - Solução
Have the function ArrayAdditionI(arr) take the array of numbers stored in arr
and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true
because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not
contain all the same elements, and may contain negative numbers.
Solução:
import java.util.*;
import java.io.*;
class Function {
private String resposta = "false";
private int tamanho;
private int maior;
String ArrayAdditionI(int[] arr) {
Arrays.sort(arr);
maior = arr[arr.length-1];
tamanho = arr.length-1;
somatorio(-1, arr, 0);
return resposta;
}
void somatorio(int indice, int[] arr, int soma) {
for (int i = indice+1; i < tamanho; i++) {
soma += arr[i];
if (soma == maior) {
resposta = "true";
}
somatorio(i, arr, soma);
soma -= arr[i];
}
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.ArrayAdditionI(s.nextLine()));
}
}
Solução:
import java.util.*;
import java.io.*;
class Function {
private String resposta = "false";
private int tamanho;
private int maior;
String ArrayAdditionI(int[] arr) {
Arrays.sort(arr);
maior = arr[arr.length-1];
tamanho = arr.length-1;
somatorio(-1, arr, 0);
return resposta;
}
void somatorio(int indice, int[] arr, int soma) {
for (int i = indice+1; i < tamanho; i++) {
soma += arr[i];
if (soma == maior) {
resposta = "true";
}
somatorio(i, arr, soma);
soma -= arr[i];
}
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
Function c = new Function();
System.out.print(c.ArrayAdditionI(s.nextLine()));
}
}
Comments
Post a Comment