algorithm binary-search(lo,hi) while the search area has elments do: mid <- lo + (hi-lo)/2; if f(mid) satisfied: // the answer may occur here ans := mid; hi <- mid; // the search area could have no elments when in the next loop, so return ans; // but mid>ans if next loop continues, // for this is a right-open area, hi <- mid; else : lo <- mid + 1; // mid is not the answer, and mid < answer; // for this is a left-close area, lo <- mid + 1; end while return ans;
funcf(x int, lengths []int)bool { count := 0 for _, l := range lengths { if l >= 2*x { returntrue } if l >= x { count++ if count >= 2 { returntrue } }else{ count = 0 } } returnfalse }
funcmaxIncreasingSubarrays(nums []int)int { n := len(nums) lengths := []int{} cur := 1 for i := 1; i < n; i++ { if nums[i] > nums[i-1] { cur++ } else { lengths = append(lengths, cur) cur = 1 } } lengths = append(lengths, cur)
lo := 1; hi := len(nums)/2+1 var ans int for lo<hi{ mi := lo + (hi-lo)/2 if f(mi,lengths){ ans = mi lo = mi + 1 }else{ hi=mi } } return ans }