How best to allocate stock buys and sells when using specific id to maximize long term capital gains
There's a natural greedy algorithm.  Scan through the buy/sell orders in chronological order.  At each sell order:

Sell as many shares that would be classified as long-term as possible, until you've sold the number required by the sell order.

If you still need to sell more shares, and there are no more shares that would be classified long-term sales, sell the youngest (newest / most recently bought) shares first.


I suggest trying to verify whether that leads to a correct algorithm or not.  See How to prove greedy algorithm is correct.