humane_rdgfc's blog

By humane_rdgfc, history, 13 months ago, In English

Given an array { 1, 7, 7, 2,3, 7, 6,-20}. Find the longest nondecreasing contiguous sequence with substitution. we can substitute any array element with any integer such as all occurrences of 7 replaced with 1. In this way new array would be { 1,1,1,2,3,1,6,-20}. here, the answer would be 5 from [1,1,1,2,3] Only one substitution is allowed.

Could anyone help me in solving this question. currently i have only bruteforce one O(n*k^2),k is no of unique elements.If anyone has better solution than this please comment below.Expected TC is O(n) ish.

Thanks in advance !

  • Vote: I like it
  • -8
  • Vote: I do not like it

| Write comment?
»
13 months ago, hide # |
 
Vote: I like it -10 Vote: I do not like it

We can do substitution any no. of times?

»
13 months ago, hide # |
 
Vote: I like it -10 Vote: I do not like it
  1. First, find all non-decreasing segments. Example: [1, 2, 2, 1, 3, 4] → segments: [1,2,2] and [1,3,4].

  2. Find breakpoints where arr[i] > arr[i+1]. Those are the “gaps” that stop a non-decreasing sequence.

  3. At each breakpoint (i, i+1): Check if replacing one element type could make the left and right segments merge. If yes, compute merged length.

  4. Since you can replace all occurrences of one unique value, merging is valid only if that value appears consistently in the gap pattern

  • »
    »
    13 months ago, hide # ^ |
    ← Rev. 2  
    Vote: I like it -10 Vote: I do not like it

    Thanks for reply i think 3rd step will cost O(n) because we need to replace all occurrences of x(say replace a[i] with a[i+1] to merge at breakpoint,now we need to replace all values of a[i] in the array with value a[i+1]) but replacing can cause before non-decreasing segments decreasing and it may cause merging as you discussed.so to find longest nondecreasing contiguous sequence for this new substitution we need to apply 2 pointers which will cost O(n).

    This we need to do for every break point,but i see this reduced TC to O(n*b),where b is number of breakpoints (which in worst case O(n^2)) is significant improvement.

    Any thoughts on making total TC O(n) ish?

    • »
      »
      »
      13 months ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      Keep two extra arrays to store the last and the next occurrence of each element, that way when you replace x just check if the next or the last index, if it cause any trouble take that as the end point of the segment or else you are good.