Site Search:

Length of continuous increasing subsequence

Problem

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 
Example 2:
Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1. 

Solution

we scan from left to right, a sequence start at i ==0 or a[i] <= a[i-1], the start of next sequence is also the end of the previous sequence.

public class IncreasingSequence {
  public static int longest(int[] a) {
    //1,3,5,4,7
    int max = 0;
    int count = 1;
    for(int i = 1; i < a.length; i++) { //4
      if(a[i] > a[i-1]) {
        count++; //2
      } else {
        max = Math.max(count, max);
        count = 1;
      }
    }
    max = Math.max(count, max);
    return max;
  }
  public static void main(String...args) {
    int[] a = new int[]{1,3,5,4,7};
    System.out.println(longest(a));
  }
}

The time cost is O(N), the space cost is O(1)