#Leetcode Problem help

5 messages · Page 1 of 1 (latest)

drowsy seal
#

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...

verbal geyserBOT
#

This post has been reserved for your question.

Hey @drowsy seal! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

brave fjord
#

Sum can't work at all, forget about it. There are other ways to get the right sum, beside being the wanted permutation

#

It's rather weird that so few of tests fail