You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2700-2799/2786.Visit Array Positions to Maximize Score/README_EN.md
+22-9
Original file line number
Diff line number
Diff line change
@@ -67,7 +67,18 @@ The total score is: 2 + 4 + 6 + 8 = 20.
67
67
68
68
<!-- solution:start -->
69
69
70
-
### Solution 1
70
+
### Solution 1: Dynamic Programming
71
+
72
+
Based on the problem description, we can draw the following conclusions:
73
+
74
+
1. Moving from position $i$ to position $j$, if $nums[i]$ and $nums[j]$ have different parities, then $x$ points will be lost;
75
+
2. Moving from position $i$ to position $j$, if $nums[i]$ and $nums[j]$ have the same parity, then no points will be lost.
76
+
77
+
Therefore, we can use an array $f$ of length $2$ to represent the maximum score when the current position's parity is $0$ and $1$. Initially, the values of $f$ are $-\infty$, and then we initialize $f[nums[0]\& 1] = nums[0]$, indicating the score at the initial position.
78
+
79
+
Next, we start traversing the array $nums$ from position $1$. For each position $i$ corresponding to the value $v$, we update the value of $f[v \& 1]$ to be the larger value between $f[v \& 1]$ and $f[v \& 1 \oplus 1] - x$ plus $v$, i.e., $f[v \& 1] = \max(f[v \& 1], f[v \& 1 \oplus 1] - x) + v$.
80
+
81
+
The answer is the larger value between $f[0]$ and $f[1]$.
0 commit comments