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
Let us count how many times each element $\textit{nums}[i]$ appears in a continuous subsequence of length greater than 1. Then, multiplying this count by $\textit{nums}[i]$ gives the contribution of $\textit{nums}[i]$ in all continuous subsequences of length greater than 1. We sum these contributions, and adding the sum of all elements, we get the answer.
76
+
77
+
We can first compute the contribution of strictly increasing subsequences, then the contribution of strictly decreasing subsequences, and finally add the sum of all elements.
78
+
79
+
To implement this, we define a function $\textit{calc}(\textit{nums})$, where $\textit{nums}$ is an array. This function returns the sum of all continuous subsequences of length greater than 1 in $\textit{nums}$.
80
+
81
+
In the function, we can use two arrays, $\textit{left}$ and $\textit{right}$, to record the number of strictly increasing subsequences ending with $\textit{nums}[i] - 1$ on the left of each element $\textit{nums}[i]$, and the number of strictly increasing subsequences starting with $\textit{nums}[i] + 1$ on the right of each element $\textit{nums}[i]$. In this way, we can calculate the contribution of $\textit{nums}$ in all continuous subsequences of length greater than 1 in $O(n)$ time complexity.
82
+
83
+
In the main function, we first call $\textit{calc}(\textit{nums})$ to compute the contribution of strictly increasing subsequences, then reverse $\textit{nums}$ and call $\textit{calc}(\textit{nums})$ again to compute the contribution of strictly decreasing subsequences. Finally, adding the sum of all elements gives the answer.
84
+
85
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$.
74
86
75
87
<!-- tabs:start -->
76
88
77
89
#### Python3
78
90
79
91
```python
80
-
92
+
classSolution:
93
+
defgetSum(self, nums: List[int]) -> int:
94
+
defcalc(nums: List[int]) -> int:
95
+
n =len(nums)
96
+
left = [0] * n
97
+
right = [0] * n
98
+
cnt = Counter()
99
+
for i inrange(1, n):
100
+
cnt[nums[i -1]] +=1+ cnt[nums[i -1] -1]
101
+
left[i] = cnt[nums[i] -1]
102
+
cnt = Counter()
103
+
for i inrange(n -2, -1, -1):
104
+
cnt[nums[i +1]] +=1+ cnt[nums[i +1] +1]
105
+
right[i] = cnt[nums[i] +1]
106
+
returnsum((l + r + l * r) * x for l, r, x inzip(left, right, nums)) % mod
107
+
108
+
mod =10**9+7
109
+
x = calc(nums)
110
+
nums.reverse()
111
+
y = calc(nums)
112
+
return (x + y +sum(nums)) % mod
81
113
```
82
114
83
115
#### Java
84
116
85
117
```java
86
-
118
+
classSolution {
119
+
privatefinalint mod = (int) 1e9+7;
120
+
121
+
publicintgetSum(int[] nums) {
122
+
long x = calc(nums);
123
+
for (int i =0, j = nums.length -1; i < j; ++i, --j) {
0 commit comments