So I was solving a leetcode problem and there was only one test case out of 803 which is failing and I am not able to resolve it, someone please help me:
Question: https://leetcode.com/problems/check-if-array-is-good/
Failed Test case: [1,4,5,4,3,3]
class Solution {
//base 1 [1 1] base 2 [1 2 2] base 3 [1 2 3]
//max element find and store in n and add each in sum
//n * n + 1 / 2 + n - sum == 0 true else false
public boolean isGood(int[] nums) {
int n = Integer.MIN_VALUE;
int sum = 0;
int count = 0;
for (int num : nums) {
sum += num;
if (n < num) {
n = num;
}
}
for (int num : nums) {
if (num == n) {
count++;
}
}
return count <= 2 && (n * (n + 1) / 2) == (sum - n);
}
}
LeetCode
Can you solve this real interview question? Check if Array is Good - You are given an integer array nums. We consider an array good if it is a permutation of an array base[n].
base[n] = [1, 2, ..., n - 1, n, n] (in other words, it is an array of length n + 1 which contains 1 to n - 1 exactly once, plus two occurrences of n). For example, base[1...