Freshman tailback Johnny White added a career-high 92 yards rushing for the Tar Heels (3-6, 2-3 Atlantic Coast Conference). Barth moved within four of Josh McGee's school record of 52 career field goals.
It was the Tar Heels' first victory over the Terrapins since a 13-10 win in 2000.
Keon Lattimore had a 5-yard TD run and Obi Egekeze kicked two field goals for Maryland (4-5, 1-4), which got off to a slow start. The Terrapins had just 3 yards on nine plays in the first quarter.
Maryland had the ball with 2:49 left in the game, and Chris Turner completed four consecutive passes to help move the Terps to the North Carolina 41. But on fourth-and-2, he was pressured by defensive tackle Kentwan Balmer and threw high toward the sideline, ending the drive with 36 seconds remaining.
Barth's 45-yard field goal gave the Tar Heels a 6-3 lead with 1:01 left in the second. Yates completed three consecutive passes, two to Brooks Foster, to help set up Barth's kick.
After the ensuing kickoff, Turner was intercepted by safety Trimane Goddard on Maryland's first play from scrimmage. Yates worked the hurry-up offense again, and a 20-yard completion to Nicks led to another 45-yard field goal for Barth.
Yates' 30-yard touchdown pass to Nicks put North Carolina ahead 16-3 in the third.
Maryland responded with Lattimore's TD run in the third and Egekeze made a 29-yard field goal in the fourth to cut it to 16-13.
Nicks finished with eight catches for 88 yards.