problem -find two number 'a' and 'b' such that a+b>sum where sum can be any given integer value...
here is the code ......
logic =you have to execute two passes of bubble sort and then pick the last two elements ...
public class findElements {
public static void main(String[] args) {
int[] arr = {
45,
4,
23,
56,
87,
27,
34,
89
};
int temp;
int sum = 100;
for (int y = 0; y < 2; y++) {
for (int i = 0; i < arr.length - y - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
if (arr[arr.length - 1] + arr[arr.length - 2] > sum)
System.out.println("required elements are" + arr[arr.length - 1] + " and " + arr[arr.length - 2]);
else System.out.println("elements not found");
//for(int s:arr) { System.out.print(s); System.out.print(" ");}
}
}
time complexity = 2(first loop) + n(second loop) = O(n)
No comments:
Post a Comment