Longest Well-Performing Interval Solutions in C++
Number 1124
Difficulty Medium
Acceptance 32.7%
Link LeetCode
Other languages —
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/longest-well-performing-interval//// Author : liuyubobobo/// Time : 2019-07-13#include <iostream>#include <vector>using namespace std;/// Presum + Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(n)class Solution {public:int longestWPI(vector<int>& hours) {for(int& e: hours)e = (e > 8 ? 1 : 0);int n = hours.size();vector<int> presum(n + 1, 0);for(int i = 1; i <= n; i ++)presum[i] = presum[i - 1] + hours[i - 1];int best = 0;for(int end = 0; end < n; end ++)for(int start = 0; start <= end && end - start + 1 > best; start ++)if((presum[end + 1] - presum[start]) * 2 > end - start + 1)best = max(best, end - start + 1);return best;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/longest-well-performing-interval//// Author : liuyubobobo/// Time : 2019-07-15#include <iostream>#include <vector>using namespace std;/// Presum + Binary Search/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:int longestWPI(vector<int>& hours) {for(int& e: hours)e = (e > 8 ? 1 : -1);int n = hours.size();vector<int> presum(n + 1, 0);for(int i = 1; i <= n; i ++)presum[i] = presum[i - 1] + hours[i - 1];int l = 0, r = n;while(l < r){int mid = (l + r + 1) / 2;if(ok(presum, mid))l = mid;elser = mid - 1;}return l;}private:bool ok(const vector<int>& presum, int len){int minv = INT_MAX;for(int i = 0; i + len < presum.size(); i ++){minv = min(minv, presum[i]);if(presum[i + len] - minv > 0)return true;}return false;}};int main() {vector<int> hours = {9,9,6,0,6,6,9};cout << Solution().longestWPI(hours) << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/longest-well-performing-interval//// Author : liuyubobobo/// Time : 2019-07-15#include <iostream>#include <vector>#include <unordered_map>using namespace std;/// Presum + Hash Map/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:int longestWPI(vector<int>& hours) {for(int& e: hours)e = (e > 8 ? 1 : -1);int n = hours.size();vector<int> presum(n + 1, 0);for(int i = 1; i <= n; i ++)presum[i] = presum[i - 1] + hours[i - 1];unordered_map<int, int> pos;int res = 0;for(int i = 1; i <= n; i ++)if(presum[i] > 0) res = max(res, i);else{if(!pos.count(presum[i])) pos[presum[i]] = i;if(pos.count(presum[i] - 1)) res = max(res, i - pos[presum[i] - 1]);}return res;}};int main() {vector<int> hours = {9,9,6,0,6,6,9};cout << Solution().longestWPI(hours) << endl;return 0;}