search
HomeBackend DevelopmentPHP TutorialFind Score of an Array After Marking All Elements

Find Score of an Array After Marking All Elements

2593. Find Score of an Array After Marking All Elements

Difficulty: Medium

Topics: Heap (Priority Queue), Sorting, Array, Simulation, Hash Table, Ordered Set, Ordered Map, Greedy, Monotonic Stack, Sliding Window, Two Pointers, Stack, Queue, Bit Manipulation, Divide and Conquer, Dynamic Programming, Doubly-Linked List, Data Stream, Radix Sort, Backtracking, Bitmask, Tree, Design, Hash Function, String, Iterator, Counting Sort, Linked List

You are given an array nums consisting of positive integers.

Starting with score = 0, apply the following algorithm:

  • Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
  • Add the value of the chosen integer to score.
  • Mark the chosen element and its two adjacent elements if they exist.
  • Repeat until all the array elements are marked.

Return the score you get after applying the above algorithm.

Example 1:

  • Input: nums = [2,1,3,4,5,2]
  • Output: 7
  • Explanation: We mark the elements as follows:
    • 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2].
    • 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2].
    • 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2].
    • Our score is 1 2 4 = 7.

Example 2:

  • Input: nums = [2,3,5,1,3,2]
  • Output: 5
  • Explanation: We mark the elements as follows:
    • 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2].
    • 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2].
    • 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2].
    • Our score is 1 2 2 = 5.

Constraints:

  • 1 5
  • 1 6

Hint:

  1. Try simulating the process of marking the elements and their adjacent.
  2. If there is an element that was already marked, then you skip it.

Solution:

We can simulate the marking process efficiently by using a sorted array or priority queue to keep track of the smallest unmarked element. So we can use the following approach:

Plan:

  1. Input Parsing: Read the array nums and initialize variables for the score and marking status.
  2. Heap (Priority Queue):
    • Use a min-heap to efficiently extract the smallest unmarked element in each step.
    • Insert each element into the heap along with its index (value, index) to manage ties based on the smallest index.
  3. Marking Elements:
    • Maintain a marked array to track whether an element and its adjacent ones are marked.
    • When processing an element from the heap, skip it if it is already marked.
    • Mark the current element and its two adjacent elements (if they exist).
    • Add the value of the current element to the score.
  4. Repeat: Continue until all elements are marked.
  5. Output: Return the accumulated score.

Let's implement this solution in PHP: 2593. Find Score of an Array After Marking All Elements

<?php /**
 * @param Integer[] $nums
 * @return Integer
 */
function findScore($nums) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example usage:
$nums1 = [2, 1, 3, 4, 5, 2];
$nums2 = [2, 3, 5, 1, 3, 2];

echo findScore($nums1) . "\n"; // Output: 7
echo findScore($nums2) . "\n"; // Output: 5
?>

Explanation:

  1. Heap Construction:

    • The usort function sorts the array based on values, and by index when values are tied.
    • This ensures that we always process the smallest unmarked element with the smallest index.
  2. Marking Logic:

    • For each unmarked element, we mark it and its adjacent elements using the marked array.
    • This ensures that we skip previously marked elements efficiently.
  3. Time Complexity:

    • Sorting the heap: O(n log n)
    • Processing the heap: O(n)
    • Overall: O(n log n), which is efficient for the given constraints.
  4. Space Complexity:

    • Marked array: O(n)
    • Heap: O(n)
    • Total: O(n)

This solution meets the constraints and works efficiently for large inputs.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Find Score of an Array After Marking All Elements. 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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)