Problem Definition
You are provided with a sequence of integers representing daily stock valuation records. Your objective is to execute exactly one pruchase followed by one sale at a subsequent point in time to achieve the highest possible financial gain.
Return the calculated net earnings. If the market conditions do not permit a positive yield, return zero.
Operational Example
Input Sequence: [7, 1, 5, 3, 6, 4]
Calculated Result: 5
Rationale: Purchase occurs on day index 1 (Value: 1). Sale occurs on day index 4 (Value: 6).
Net Yield: 6 - 1 = 5
Note: Selling prior to buying is prohibited. A larger theoretical spread (like 7-1) does not exist if chronological order is violated.
Implementation Approach
Utilize a linear scan to maintain the state of the lowest acquisition cost encountered thus far. Simultaneously track the maximum raelized difference between the current valuation and that minimum historical cost.
Optimized Solution
class StockProfitCalculator:
def calculate_maximum_gain(self, price_data):
min_purchase_value = float('inf')
max_accumulated_profit = 0
for current_val in price_data:
if current_val < min_purchase_value:
min_purchase_value = current_val
current_diff = current_val - min_purchase_value
if current_diff > max_accumulated_profit:
max_accumulated_profit = current_diff
return max_accumulated_profit
Core Logic
This method relies on the greedy principle. As the iteration progresses, min_purchase_value constantly updates to reflect the cheapest entry point found up to the current index. For every step, we evaluate whether selling today yields a better return compared to previous best attempts (max_accumulated_profit). By the end of the dataset, the tracked maximum represents the global optimum for a single transaction window. No future data influences past decisions beyond the running minimum update.