MATLAB: How would you automate this code

for loopif statementloops

I have the following situation:
d = [3 39 54 53 6];
n = 103;
What I would like to do is to have a code where: when the sum of the elements in d is bigger than n, then I subtract one from the first column in d that is equal or bigger than n.
In the example above, I would have:
d = [3 39 54 *52* 6];
% since the first column where sum(d) is bigger than n is the fourth column, therefore I subtract 1 from 52
How can I automate this?
Thanks!

Best Answer

Th cumsum and find functions should be useful. Let me know if you have trouble implementing it.