Greedy Action from Action Values
Problem Statement
Given a list of action values q (one entry per action), return the index of the greedy action — the action with the highest value. Break ties by choosing the smallest index.
Implement greedy_action(q).
Example:
greedy_action([0.1, 0.5, 0.3])
1
- Initialize the candidate for the greedy action to the first index, setting the current best value to 0.1 at index 0.
- Compare the value at index 1 (0.5) against the current best value (0.1); since 0.5>0.1, update the best index to 1 and the best value to 0.5.
- Compare the value at index 2 (0.3) against the current best value (0.5); since 0.3≯0.5, the best index remains 1.
- The final output is 1
Constraints:
1 <= len(q) <= 1000- Values may be negative.
- On ties, return the lowest index.
1. Background Knowledge
In Reinforcement Learning (RL), an agent interacts with an environment by selecting actions based on a policy. A fundamental policy is the greedy policy, which always selects the action with the highest estimated value. This approach is central to algorithms like Q-Learning and SARSA, where the agent learns an action-value function Q(s,a) that estimates the expected return for taking action a in state s.
The action-value function Q(s,a) represents the expected cumulative reward starting from state s, taking action a, and then following the policy thereafter. When making a decision, the agent compares the Q-values of all available actions and picks the one with the maximum value. This is known as argmax selection. In practice, ties can occur when multiple actions have identical values, and a deterministic tie-breaking rule (such as choosing the smallest index) ensures consistent behavior.
Understanding this concept is crucial because greedy action selection is the backbone of many RL algorithms. It provides a simple yet effective way to exploit known information while balancing exploration in more advanced strategies.
2. Algorithm Approach
The problem reduces to finding the index of the maximum element in a list, with a specific tie-breaking rule. The standard approach is:
- Iterate through the list of action values.
- Track the maximum value seen so far and its index.
- When a value is strictly greater than the current maximum, update both the maximum and its index.
- If a value is equal to the current maximum, do not update the index (this naturally preserves the smallest index due to left-to-right traversal).
This is a classic linear scan pattern. No sorting or complex data structures are needed.
3. Step-by-Step Strategy
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.