Max P Q Algorithm

The Max P Q Algorithm is an optimization technique that aims to solve the problem of allocating resources to different tasks or projects in order to maximize the overall performance or return on investment. It is commonly used in various fields such as operations research, economics, and finance to optimize resource allocation decisions, especially when dealing with constraints like limited resources, time, or budget. The main idea behind the algorithm is to prioritize tasks or projects based on the ratio of their respective returns (P) to the resources required (Q), and allocate resources accordingly. In other words, the algorithm seeks to maximize the total return by assigning resources to tasks with the highest P/Q ratios first, ensuring that the most valuable tasks are completed before moving on to less valuable ones. The Max P Q Algorithm works by first sorting the tasks or projects based on their P/Q ratio in descending order, effectively ranking them by their relative importance. The algorithm then iteratively allocates resources to the highest-ranked task until its resource requirements are met, or until there are no more resources available. Once the highest-ranked task is completed, the algorithm moves on to the next highest-ranked task and continues the process until all tasks have been considered or no resources remain. This approach ensures that the most valuable tasks are prioritized and completed first, while less valuable tasks are considered only if there are sufficient resources available. The Max P Q Algorithm is particularly useful in situations where resources are scarce, as it ensures that these limited resources are allocated in the most efficient and effective way possible, maximizing the overall return on investment.
package org.gs.queue

import scala.collection.mutable.ArrayBuffer

/** For max value on Q extends PriorityQueue
  *
  * @tparam A keys are generic
  * @param pq priority queue array
  * @param ord implicit Ordering
  * @see [[https://algs4.cs.princeton.edu/24pq/MaxPQ.java.html]]
  * @author Scala translation by Gary Struthers from Java by Robert Sedgewick and Kevin Wayne.
  */
class MaxPQ[A](pq: ArrayBuffer[A])(implicit ord: Ordering[A]) extends PriorityQueue(pq) {

  /** insert key */
  def insert(key: A): Unit = insert(key, less)

  /** remove max element */
  def pop(): Option[A] = pop(less)

  /** check parent and children are in proper indexes */
  def isMaxHeap(): Boolean = checkHeap(less)

  /** return keys in descending sorted order */
  def keys(): Seq[A] = pq sorted(Ordering[A].reverse)

  /** return keys as string */
  override def toString(): String = toString(keys)
}

LANGUAGE:

DARK MODE: