Sponsored
Sponsored
This approach involves iterating through the array while maintaining a variable to track the length of the current continuous increasing subsequence. As we encounter each element, we check if it is larger than the previous one to decide if we should continue the current subsequence or start a new one. We also maintain a global maximum to store the maximum length found during our iteration.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as we use a constant amount of space.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int findLengthOfLCIS(vector<int>& nums) {
6 if (nums.empty()) return 0;
7 int maxLen = 1, currLen = 1;
8
9 for (size_t i = 1; i < nums.size(); ++i) {
10 if (nums[i] > nums[i - 1]) {
11 currLen++;
12 maxLen = max(maxLen, currLen);
13 } else {
14 currLen = 1;
15 }
16 }
17 return maxLen;
18}
19
20int main() {
21 vector<int> nums = {1, 3, 5, 4, 7};
22 cout << findLengthOfLCIS(nums) << endl;
23 return 0;
24}
The C++ solution is quite similar to the C solution. It uses a vector to store the input, iterates through the vector, compares elements, and updates the sequence length and maximum length as necessary.
The greedy approach leverages a single pass through the array to determine the maximum length of an increasing subsequence. This method is optimal because it immediately processes each element only once, updating the sequence lengths on the fly, and computing the maximum without revisiting any part of the array.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as no additional space other than variables is utilized.
The Java implementation showcases an immediately greedy nature in computation by updating in place, thus keeping the max sequence on top and tracked through this repetitive check.