Wrong stack approach. just see what happens if you have input 6, 9, 12, 17, 11, 15 . When you work with 15, your stack has been forgotten about 12 and 17. But the closest small left element A [5] is 12.
Said's algorithm is also wrong. Just try to calculate.
The correct answer may be something like this
b[1] = a[1]; s[1] = 1; for (i=2; i<=n; i+=1) { j = i - 1; while (j>1){ if (a[j]<a[i]) { b[i] = a[j]; s[i] = j; break; } else { j = s[j]; } } if (j = 1) { b[i] = a[j]; s[i] = j; } }
I'm not sure, but it has O (n) complexity.
Maxim Welikobratov
source share