A late goal from substitute Malcolm in extra time helped Brazil defeat Spain 2-1 in the gold medal match of the Tokyo Olympics.