Good question. I get the same thing, usually it happens frequently for a month or so and then goes away. I hate those, ouch!
I tried potassium (via bananas) and multivitamins also, and while I think that's a good idea, it didn't do anything for me.
What I've been using lately is drinking unsweetened coconut water regularly, especially after exercising. Coconut water supposedly is a perfect source of electrolytes, not just potassium.
It's been a few months since it happened which is the longest stretch yet. I'm not sure if I have a solution or if it's just lurking waiting to come back.
Other treatments I've heard have worked is drinking tonic water before bed (quinine), but liquid too close to bedtime might disturb your sleep.