Find middle point segment from given segment lengths | Java implementation of the approach ; Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code
class GFG { static int findSegment ( int n , int m , int [ ] segment_length ) { double meet_point = ( 1.0 * n ) / 2.0 ; int sum = 0 ; int segment_number = 0 ; for ( int i = 0 ; i < m ; i ++ ) { sum += segment_length [ i ] ; if ( ( double ) sum == meet_point ) { segment_number = - 1 ; break ; } if ( sum > meet_point ) { segment_number = i + 1 ; break ; } } return segment_number ; } public static void main ( String [ ] args ) { int n = 13 ; int m = 3 ; int [ ] segment_length = new int [ ] { 3 , 2 , 8 } ; int ans = findSegment ( n , m , segment_length ) ; System . out . println ( ans ) ; } }