The two leaders' joint statement came as they held talks in Baghdad before Mr Brown headed to Basra.
The UK PM praised his forces for making Iraq a "better place".
There are currently about 4,100 UK troops in Basra, southern Iraq. Between 200 to 300 military advisers are likely to remain after combat troops leave.
The withdrawal announcement comes after at least 18 people were killed and dozens wounded in a twin bomb attack in Baghdad on Wednesday.
BBC diplomatic correspondent Paul Adams said the announcement ended months of speculation.
At a press conference, Mr Brown said: "We have agreed today that the mission will end no later than 31 May next year.
Mr Maliki confirmed that the agreement included a provision for the Iraqi government to request an extension of the British military presence.
However, both leaders indicated it was not expected to be used.
Mr Brown said: "We have made a huge contribution and of course given people an economic stake in the future of Iraq. We leave Iraq a better place."
He added: "I am proud of the contribution British forces have made. They are the pride of Britain and the best in the world."
In their joint statement, the leaders said the role played by the UK combat forces was "drawing to a close".