Ternary Array Cost
Local Cost Minimization / GreedySolved Nov 9, 2025
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementGiven an array A (elements can be anything), convert it to a ternary array B (elements must be 0, 1, or 2). The cost is sum |A[i] - B[i]|. Crucially, the constraint is that A[i] ≠ B[i]. Find the minimum total conversion cost.ReadHide
Problem Description
Given an array A (elements can be anything), convert it to a ternary array B (elements must be 0, 1, or 2). The cost is sum |A[i] - B[i]|. Crucially, the constraint is that A[i] ≠ B[i]. Find the minimum total conversion cost.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
For each element A[i], calculate the conversion cost |A[i] - B[i]| for B[i] = 0, 1, and 2 (where B[i] != A[i]). Choose the B[i] that yields the minimum cost locally.
Approaches
1. Greedy Local Minimum (Optimal) - O(N) ⭐
Idea: Since the choice made for A[i] does not affect the cost calculation for any other element A[j], the total minimum cost is the sum of the minimum cost at each index. This is a purely greedy local minimization problem.
For each A[i], we test the three possible target values (0, 1, 2) and select the one that minimizes the cost |A[i] - B[i]|, subject to A[i] ≠ B[i].
Time: O(N) (Three constant-time checks per element).
Space: O(1) (Storing a single total sum).
Solution code
import sys
def solve_ternary_array_cost():
try:
# Read N (not strictly needed for the cost calculation)
N = int(sys.stdin.readline())
# Read the array elements
A = list(map(int, sys.stdin.readline().split()))
except:
return
min_total_cost = 0
# Optimal: O(N) Time - Greedy Local Minimization
for a_i in A:
# Possible target values for B[i] are 0, 1, 2
# Start with a very high cost
min_local_cost = float('inf')
for b_i in [0, 1, 2]:
# Constraint check: A[i] != B[i]
if a_i != b_i:
# Calculate the cost: |A[i] - B[i]|
cost = abs(a_i - b_i)
# Update the minimum local cost
if cost < min_local_cost:
min_local_cost = cost
# Add the minimum local cost to the total
min_total_cost += min_local_cost
print(min_total_cost)
if __name__ == "__main__":
solve_ternary_array_cost()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language