NEW YORK (Reuters) - MedImpact's attempt to recoup about $200 million related to its purchase of Rite Aid's pharmacy benefit unit failed after a judge ruled on Monday that it took on Elixir's debts when it bought the company.

U.S. Bankruptcy Judge Michael Kaplan at a hearing in Trenton, New Jersey said that MedImpact was well aware that Elixir had been operating with a negative cash balance of about $200 million for about two years, due to reimbursement payments it owed to pharmacies including CVS Health and Walgreens Boots Alliance

Kaplan had previously approved MedImpact's $575 million purchase of Elixir, and he ruled that the sale agreement transferred those debts to the buyer.

Rite Aid, one of the largest U.S. pharmacy retailers, filed for bankruptcy in October citing its high debt, revenue declines, increased competition, and litigation over its role in the U.S. opioid crisis as factors that caused its bankruptcy.

The dispute with MedImpact, a pharmacy benefit manager, had threatened to derail Rite Aid's overall restructuring plan, which is up for approval at a final court hearing on Thursday, Kaplan said.

The judge noted that Rite Aid does not have cash to spare, and said MedImpact had no reason to believe Rite Aid was agreeing to cover Elixir's old debts at a time when it was desperately trying to raise cash and shed its own liabilities.

"It is no secret that money in this case is tight, and there is little wiggle room, let alone over $200 million of wiggle room," Kaplan said.

Rite Aid's bankruptcy plan would cut $2 billion in debt and provide $47.5 million to junior creditors, including individuals and local governments who have sued the company for allegedly ignoring possible red flags and illegally filling prescriptions for addictive opioid pain medication.

(Reporting by Dietrich Knauth, Editing by Alexia Garamfalvi and Bill Berkrot)

By Dietrich Knauth