search
HomeBackend DevelopmentPHP TutorialFind Missing Observations

Find Missing Observations

Sep 06, 2024 am 08:30 AM

Find Missing Observations

2028. Find Missing Observations

Difficulty: Medium

Topics: Array, Math, Simulation

You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.

You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.

Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.

The average value of a set of k numbers is the sum of the numbers divided by k.

Note that mean is an integer, so the sum of the n + mrolls should be divisible by n + m.

Example 1:

  • Input: rolls = [3,2,4,3], mean = 4, n = 2
  • Output: [6,6]
  • Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.

Example 2:

  • Input: rolls = [1,5,6], mean = 3, n = 4
  • Output: [2,3,2,2]
  • Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.

Example 3:

  • Input: rolls = [1,2,3,4], mean = 6, n = 4
  • Output: []
  • Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.

Constraints:

  • m == rolls.length
  • 1 5
  • 1

Hint:

  1. What should the sum of the n rolls be?
  2. Could you generate an array of size n such that each element is between 1 and 6?

Solution:

We need to determine an array of missing rolls such that the average of all n + m dice rolls is exactly equal to mean. Here's the step-by-step breakdown of the solution:

Steps to Approach:

  1. Calculate the total sum for n + m rolls:
    Given that the average value of n + m rolls is mean, the total sum of all the rolls should be total_sum = (n + m) * mean.

  2. Determine the missing sum:
    The sum of the m rolls is already known. Thus, the sum of the missing n rolls should be:

   missing_sum = total_sum - ∑(rolls)

where ∑(rolls) is the sum of the elements in the rolls array.

  1. Check for feasibility: Each roll is a 6-sided die, so the missing values must be between 1 and 6 (inclusive). Therefore, the sum of the missing n rolls must be between:
   min_sum = n X 1 = n

and

   max_sum = n X 6 = 6n

If the missing_sum is outside this range, it's impossible to form valid missing observations, and we should return an empty array.

  1. Distribute the missing sum: If missing_sum is valid, we distribute it across the n rolls by initially filling each element with 1 (the minimum possible value). Then, we increment elements from 1 to 6 until we reach the required missing_sum.

Let's implement this solution in PHP: 2028. Find Missing Observations

<?php /**
 * @param Integer[] $rolls
 * @param Integer $mean
 * @param Integer $n
 * @return Integer[]
 */
function missingRolls($rolls, $mean, $n) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example 1
$rolls = [3, 2, 4, 3];
$mean = 4;
$n = 2;
print_r(missingRolls($rolls, $mean, $n));

// Example 2
$rolls = [1, 5, 6];
$mean = 3;
$n = 4;
print_r(missingRolls($rolls, $mean, $n));

// Example 3
$rolls = [1, 2, 3, 4];
$mean = 6;
$n = 4;
print_r(missingRolls($rolls, $mean, $n));
?>

Explanation:

  1. Input:

    • rolls = [3, 2, 4, 3]
    • mean = 4
    • n = 2
  2. Steps:

    • The total number of rolls is n + m = 6.
    • The total sum needed is 6 * 4 = 24.
    • The sum of the given rolls is 3 + 2 + 4 + 3 = 12.
    • The sum required for the missing rolls is 24 - 12 = 12.

We need two missing rolls that sum up to 12, and the only possibility is [6, 6].

  1. Result:
    • For example 1: The output is [6, 6].
    • For example 2: The output is [2, 3, 2, 2].
    • For example 3: No valid solution, so the output is [].

Time Complexity:

  • Calculating the sum of rolls takes O(m), and distributing the missing_sum takes O(n). Hence, the overall time complexity is O(n + m), which is efficient for the input constraints.

This solution ensures that we either find valid missing rolls or return an empty array when no solution exists.

Contact Links

このシリーズが役立つと思われた場合は、GitHub で リポジトリ にスターを付けるか、お気に入りのソーシャル ネットワークで投稿を共有することを検討してください。あなたのサポートは私にとって大きな意味を持ちます!

このような役立つコンテンツがさらに必要な場合は、お気軽にフォローしてください:

  • LinkedIn
  • GitHub

The above is the detailed content of Find Missing Observations. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

What is Content Security Policy (CSP) header and why is it important?What is Content Security Policy (CSP) header and why is it important?Apr 09, 2025 am 12:10 AM

CSP is important because it can prevent XSS attacks and limit resource loading, improving website security. 1.CSP is part of HTTP response headers, limiting malicious behavior through strict policies. 2. The basic usage is to only allow loading resources from the same origin. 3. Advanced usage can set more fine-grained strategies, such as allowing specific domain names to load scripts and styles. 4. Use Content-Security-Policy-Report-Only header to debug and optimize CSP policies.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

What is HTTPS and why is it crucial for web applications?What is HTTPS and why is it crucial for web applications?Apr 09, 2025 am 12:08 AM

HTTPS is a protocol that adds a security layer on the basis of HTTP, which mainly protects user privacy and data security through encrypted data. Its working principles include TLS handshake, certificate verification and encrypted communication. When implementing HTTPS, you need to pay attention to certificate management, performance impact and mixed content issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use