You are viewing a single comment's thread. Return to all comments →
my answer with O(n) time:
static long compute(long a) { return a * (a - 1); } public static long solve(List<Integer> arr) { long res = 0; Deque<long[]> st = new LinkedList<long[]>(); Iterator<Integer> it = arr.iterator(); long cur = it.next(); long cnt = 1; while (it.hasNext()) { int next = it.next(); if (next == cur) cnt++; else if (next < cur) { st.push(new long[] {cur, cnt}); cur = next; cnt = 1; } else { res += compute(cnt); cur = next; cnt = 1; if (st.isEmpty()) continue; while (!st.isEmpty()) { long[] pre = st.peek(); if (pre[0] < next) { st.remove(); res += compute(pre[1]); } else if (pre[0] == next) { st.remove(); cur = pre[0]; cnt = pre[1] + 1; break; } else break; } } } res += compute(cnt); while (!st.isEmpty()) { long[] pre = st.pop(); res += compute(pre[1]); } return res; }
Seems like cookies are disabled on this browser, please enable them to open this website
Jim and the Skyscrapers
You are viewing a single comment's thread. Return to all comments →
my answer with O(n) time: