Problem:
Start with 2 int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.
biggerTwo({1, 2}, {3, 4}) → {3, 4}
biggerTwo({3, 4}, {1, 2}) → {3, 4}
biggerTwo({1, 1}, {1, 2}) → {1, 2}
Solution:
public int[] biggerTwo(int[] a, int[] b) { if (b[1] + b[0] > a[1] + a[0]) return b; else return a; }
Thats the algorithm for any size of an array:
ReplyDeletepublic int [] biggerTwo(int [] a, int[] b) {
int temp;
int temp2;
int sum=0;
int sum1=0;
int [] x = new int [a.length];
int [] z = new int [b.length];
for(int i=0;isum1)
return a;
if(sum==sum1)
return a;
else
return b;
}
Best and easiest way:
ReplyDeletepublic int[] biggerTwo(int[] a, int[] b) {
int sum1 = 0;
int sum2 = 0;
for(int x : a){
sum1 = sum1 + x;
}
for(int y : b){
sum2 = sum2 + y;
}
if(sum1 >= sum2){
return a;
} else {
return b;
}
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint aVal = a[0] + a[1];
int bVal = b[0] + b[1];
if(aVal == bVal) return a;
return aVal > bVal ? a:b;
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint i=0;
int sum=0;
int j=0;
int sum2=0;
while(i=sum2)
return a;
else
return b;
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint i=0;
int sum=0;
int j=0;
int sum2=0;
while(i=sum2)
return a;
else
return b;
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint sum = a[0]+a[1];
int summ = b[0]+b[1];
if(sum==summ)
return a;
if(sum>summ)
return a;
else
return b;
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteif(a[0]+a[1]>b[0]+b[1] || a[0]+a[1]==b[0]+b[1])
return a;
return b;
}
public int[] biggerTwo(int[] a, int[] b) {
ReplyDeleteint sumA = Arrays.stream(a).sum();
int sumB = Arrays.stream(b).sum();
if(sumA < sumB){
return b;
} else {
return a;
}
}