How to export maximum quality in minimum size
You will want to use the H.264 codec, as it has one of the best quality/filesize-ratios of all the codecs out there. For this codec, your file size (and consequently it's quality) is mainly determined by the bitrate settings.

Let's do the math:

40 min = 2400 sec
400 MB = 3200 Mb (Megabit)
3200 Mb / 2400 sec = **1.33 Mb/s**


So you can set your Maximum Bitrate to 1,33 Mbps and the Target Bitrate to the same value or slightly below that. Make sure to change your Bitrate Encoding to VBR, 2 pass for best results (this will take longer than exporting with 1 pass though). This is already quite low, with these settings you will probably get significant artifacts in your video. However, Youtube uses an even lower bitrate for it's video encoding (at least up to Full HD, not sure about 4k), so you could argue that people are used to it anyway. The amount of quality loss also depends on how much entropy (that is, small particles et c.) is in your video, watch this for an explanation.