LeetCode-in-Java

3678. Smallest Absent Positive Greater Than Average

Easy

You are given an integer array nums.

Return the smallest absent positive integer in nums such that it is strictly greater than the average of all elements in nums.

The average of an array is defined as the sum of all its elements divided by the number of elements.

Example 1:

Input: nums = [3,5]

Output: 6

Explanation:

Example 2:

Input: nums = [-1,1,2]

Output: 3

Explanation:

Example 3:

Input: nums = [4,-1]

Output: 2

Explanation:

Constraints:

Solution

public class Solution {
    public int smallestAbsent(int[] nums) {
        int sum = 0;
        for (int j : nums) {
            sum += j;
        }
        double avg = (double) sum / nums.length;
        int num;
        if (avg < 0) {
            num = 1;
        } else {
            num = (int) avg + 1;
        }
        while (true) {
            boolean flag = false;
            for (int j : nums) {
                if (num == j) {
                    flag = true;
                    break;
                }
            }
            if (!flag && num > avg) {
                return num;
            }
            num++;
        }
    }
}