Optimal Dynamic Subset Sampling: Theory and Applications