Stock Trader S Alternating Streak You are a day tr...
Creato il: 2 agosto 2026
Risposto usando GPT-5.6 Thinking da Chat01
Creato il: 2 agosto 2026
Risposto usando GPT-5.6 Thinking da Chat01
Stock Trader S Alternating Streak
You are a day trader watching N price ticks pl1]. p[2],., pINI. You want to find the length of the longest "wiggle" subsequence that satisfies specific conditions.
A subsequence is formed by choosing a subset of the price ticks while preserving their relative order.
Let the chosen subsequence be s[1], [2],.., sk] The subsequence is considered valid if it satisfies the following rules:
satisfy the noise threshold MUsing the
mulligan is optional.
PROBLEM
A Flagged
Find the maximum length of a valid subsequence.
mohdda
Input Format
The first line contains a integer, N, denoting the number of price ticks.
The second line contains a integer, M, denoting the noise threshold
Each line i of the N subsequent lines (where 0 ≤ i < N) contains a integer, Pfil.
mohdd
Constraints
1 <= N<= 1015
1 <= M < = 10^9
1 <= P[i] < = 10^9
Examples
anishsheikhh
A Flagged
EXAMPLE 1
Input:
4
10
10
20
10
20
Output:
4
Explanation:
The entire sequence [10, 20, 10, 20] is valid because every step has an absolute difference of exactly 10 and strictly alternates in direction (up, down, up).
This achieves the maximum length of 4 without needing to use the mulligan.
EXAMPLE 2
Input:
4
10
10
20
30
40
Output:
3
10
10
20
30
40
A Flagged
Output:
3
Explanation:
Choosing [10, 20, 30] yields steps of +10 and +10, which both meet the noise threshold of 10. Using the single allowed mulligan to tolerate these consecutive up-steps results in a maximum length of 3.
EXAMPLE 3
Input:
1
0
1
0
15
12
18
Output:
1
Explanation:
Since no two price ticks have an absolute difference of 10 or more, no valid transitions can be made. The longest valid subsequence is restricted to any single element, resulting in a length of 1.
import sys
input = sys. stdin.readline
4 v
def
solve(N: int, M: int, P: list) -> int:
6
return o
9 v if
name
= °
10
try:
main_*:
11
N = int(input())
12
M = int(input())
13
P = list (map(int, input() -split())
14
result = solve(N, A, ₽)
15
print (result)
16 v
except (EOFError, ValueError):
pass
Complete this code according to above question
pythonfrom itertools import combinations, product from bisect import bisect_left,bisect_right def brute(P,M): n=len(P) best=1 if n else 0 for mask in range(1,1<<n): s=[P[i] for i in range(n) if mask>>i&1] if len(s)<=best: continue dirs=[] ok=True for a,b in zip(s,s[1:]): if abs(b-a)<M or a==b: ok=False; break dirs.append(1 if b>a else -1) if not ok: continue violations=sum(dirs[i]==dirs[i-1] for i in range(1,len(dirs))) if violations<=1: best=len(s) return best class BIT
pythonimport sys from bisect import bisect_left, bisect_right class FenwickMax: """Fenwick tree supporting point updates and prefix maximum queries.""" def __init__(self, size: int): self.size = size self.tree = [0] * (size + 1) def update(self, index: int, value: int) -> None: index += 1 # Convert to 1-based indexing while index <= self.size: if value > self.tree[index]: self.tree[index] = value index += index & -index def query(self, count: int) -> int: """Maximum among indices [0, count).""" result = 0 while count > 0: result = max(result, self.tree[count]) count -= count & -count return result def solve(N: int, M: int, P: list[int]) -> int: if N == 0: return 0 # Coordinate compression of prices. values = sorted(set(P)) size = len(values) # States: # 0: last step was UP, mulligan unused # 1: last step was DOWN, mulligan unused # 2: last step was UP, mulligan used # 3: last step was DOWN, mulligan used prefix = [FenwickMax(size) for _ in range(4)] suffix = [FenwickMax(size) for _ in range(4)] answer = 1 for price in P: index = bisect_left(values, price) # Previous prices eligible for an UP step: # previous_price <= price - M and previous_price < price. lower_count = min( bisect_right(values, price - M), bisect_left(values, price) ) # Previous prices eligible for a DOWN step: # previous_price >= price + M and previous_price > price. higher_start = max( bisect_left(values, price + M), bisect_right(values, price) ) def lower_query(state: int) -> int: return prefix[state].query(lower_count) def higher_query(state: int) -> int: # Prices are reversed in the suffix Fenwick trees. return suffix[state].query(size - higher_start) # Current step is UP and alternates after a DOWN step. previous_down_unused = lower_query(1) up_unused = ( previous_down_unused + 1 if previous_down_unused > 0 else 1 ) # Current step is DOWN and alternates after an UP step. previous_up_unused = higher_query(0) down_unused = ( previous_up_unused + 1 if previous_up_unused > 0 else 1 ) # End with an UP step after using the mulligan: # 1. Alternate after a DOWN step where mulligan was already used. # 2. Follow another UP step and use the mulligan now. previous_down_used = lower_query(3) previous_up_same = lower_query(0) up_used = max( previous_down_used + 1 if previous_down_used > 0 else 0, previous_up_same + 1 if previous_up_same > 0 else 0 ) # End with a DOWN step after using the mulligan: # 1. Alternate after an UP step where mulligan was already used. # 2. Follow another DOWN step and use the mulligan now. previous_up_used = higher_query(2) previous_down_same = higher_query(1) down_used = max( previous_up_used + 1 if previous_up_used > 0 else 0, previous_down_same + 1 if previous_down_same > 0 else 0 ) current = [ up_unused, down_unused, up_used, down_used ] # Insert the current price after calculating all states, so an # element cannot transition to itself. reversed_index = size - 1 - index for state, length in enumerate(current): if length > 0: prefix[state].update(index, length) suffix[state].update(reversed_index, length) answer = max(answer, *current) return answer def main() -> None: data = list(map(int, sys.stdin.buffer.read().split())) if len(data) < 2: return N = data[0] M = data[1] P = data[2:2 + N] print(solve(N, M, P)) if __name__ == "__main__": main()
The four dynamic-programming states track the last direction and whether the mulligan has been used. Fenwick trees retrieve the best earlier subsequence whose final price is at least M below or above the current price.
Complexity: O(N log N) time and O(N) space.