color adjustment algorithm – Computer Science Stack Exchange

Got a problem I’m not sure how to approach.

I’m being given a string of text with indeterminate length, around typical “body text” size. The text is a solid color, and the background can be a solid OR a gradient of one or more colors of varying luminance. The goal is to make the text readable across the entire background while adjusting the color channels as little as possible.

How could I find the SMALLEST possible color adjustments to the foreground and/or background that would make the text readable, according to WCA standards or others?