![]() |
VOOZH | about |
Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it.
Examples:
Input: arr[] = [1, 1, 0, 0, 0, 0, 0]
Output: 2
Explanation: Count of 1's in the given array is 2.Input: arr[] = [1, 1, 1, 1, 1, 1, 1]
Output: 7Input: arr[] = [0, 0, 0, 0, 0, 0, 0]
Output: 0
Table of Content
A simple solution is to linearly traverse the array until we find the 1's in the array and keep count of 1s. If the array element becomes 0 then return the count of 1's.
4
Since the array is sorted with all 1s before 0s, there is a single transition point from 1 to 0. We use binary search to find the last occurrence of 1 by checking the middle element and narrowing the search space accordingly. The index of this last 1 plus one gives the count.
4