intlongestWPI(int* hours, int hoursSize) { int s[hoursSize + 1]; int stk[hoursSize + 1]; int top = 0; stk[top++] = 0; s[0] = 0; for (int i = 1; i <= hoursSize; i++) { s[i] = s[i - 1] + (hours[i - 1] > 8 ? 1 : -1); if (s[stk[top - 1]] > s[i]) { stk[top++] = i; } }
int res = 0; for (int r = hoursSize; r >= 1; r--) { while (top && s[stk[top - 1]] < s[r]) { res = MAX(res, r - stk[top - 1]); top--; } } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var longestWPI = function(hours) { const n = hours.length; const s = newArray(n + 1).fill(0); const stk = [0]; for (let i = 1; i <= n; i++) { s[i] = s[i - 1] + (hours[i - 1] > 8 ? 1 : -1); if (s[stk[stk.length - 1]] > s[i]) { stk.push(i); } }
let res = 0; for (let r = n; r >= 1; r--) { while (stk.length && s[stk[stk.length - 1]] < s[r]) { res = Math.max(res, r - stk.pop()); } } return res; };
复杂度分析
时间复杂度:O(n),其中 n 为 hours 的长度。每个元素最多入栈和出栈一次,因此时间复杂度为 O(n)。
classSolution { public: intlongestWPI(vector<int>& hours){ int n = hours.size(); unordered_map<int, int> ump; int s = 0, res = 0; for (int i = 0; i < n; i++) { s += hours[i] > 8 ? 1 : -1; if (s > 0) { res = max(res, i + 1); } else { if (ump.count(s - 1)) { res = max(res, i - ump[s - 1]); } } if (!ump.count(s)) { ump[s] = i; } } return res; } };
publicclassSolution { publicintLongestWPI(int[] hours) { int n = hours.Length; IDictionary<int, int> dictionary = new Dictionary<int, int>(); int s = 0, res = 0; for (int i = 0; i < n; i++) { s += hours[i] > 8 ? 1 : -1; if (s > 0) { res = Math.Max(res, i + 1); } else { if (dictionary.ContainsKey(s - 1)) { res = Math.Max(res, i - dictionary[s - 1]); } } if (!dictionary.ContainsKey(s)) { dictionary.Add(s, i); } } return res; } }
intlongestWPI(int* hours, int hoursSize) { HashItem *ump = NULL; int s = 0, res = 0; for (int i = 0; i < hoursSize; i++) { s += hours[i] > 8 ? 1 : -1; if (s > 0) { res = MAX(res, i + 1); } else { if (hashFindItem(&ump, s - 1)) { res = MAX(res, i - hashGetItem(&ump, s - 1, 0)); } } if (!hashFindItem(&ump, s)) { hashAddItem(&ump, s, i); } } hashFree(&ump); return res; }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var longestWPI = function(hours) { const n = hours.length; const map = newMap(); let s = 0, res = 0; for (let i = 0; i < n; i++) { s += hours[i] > 8 ? 1 : -1; if (s > 0) { res = Math.max(res, i + 1); } else { if (map.has(s - 1)) { res = Math.max(res, i - map.get(s - 1)); } } if (!map.has(s)) { map.set(s, i); } } return res; };