java - Find the second largest sum of consecutive integers in array -
can please provide , explain solution problem
i have array of integers
int[] arr = {1,6,2,3,8};
i want find second largest sum of consecutive integers in array , display element pair who's sum produces second largest number
for example above array, sum of consecutive integers is
- 1+6 = 7
- 6+2 = 8
- 2+3 = 5
- 3+8 = 11
the output of program
8 elements 6,2
conditions problem are
- must done in single loop
- must not use new array
- must not sort given array
- must not use collection framework
class solution { public static void main(string[] args) throws ioexception { long max = long.min_value + 1, secondmax = long.min_value; int positionmax = -1, positionsecondmax = -1; int[] arr = {1,6,2,3,8}; for(int = 0; < arr.length - 1; i++){ if(arr[i] + arr[i + 1] > max){ secondmax = max; positionsecondmax = positionmax; max = (long)arr[i] + (long)arr[i + 1]; positionmax = i; } else if(arr[i] + arr[i + 1] < max && arr[i] + arr[i + 1] > secondmax){ secondmax = (long)arr[i] + (long)arr[i + 1]; positionsecondmax = i; } } system.out.println(secondmax + " elements " + arr[positionsecondmax] + ", " + arr[positionsecondmax + 1]); } }
Comments
Post a Comment