Sensory adaptation as optimal resource allocation