Skip to content

Commit 59a0b1a

Browse files
committed
Add: Add 2025/2/4
1 parent 2fcfe4c commit 59a0b1a

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 1800. Maximum Ascending Subarray Sum
2+
3+
Given an array of positive integers `nums`, return the maximum possible sum of an ascending subarray in `nums`.
4+
5+
A subarray is defined as a contiguous sequence of numbers in an array.
6+
7+
A subarray $[\text{nums}_{l}, \text{nums}_{l+1}, ..., \text{nums}_{r-1}, \text{nums}_{r}]$ is ascending if for all `i`
8+
where $l <= i < r, \text{nums}_i < \text{nums}_{i+1}$.
9+
Note that a subarray of size `1` is ascending.
10+
11+
## 基礎思路
12+
我們數組當前位置 `i` 與前一個位置 `i-1` 比較:
13+
- 如果當前位置 `i` 大於前一個位置 `i-1`,則將當前位置 `i` 加入到當前的子數組的和中
14+
- 否則重置當前的子數組和為當前位置 `i` 的值
15+
16+
然後比較當前的子數組和與最大子數組和,取最大值
17+
18+
## 解題步驟
19+
20+
### Step 1: 初始化當前子數組和與最大子數組和
21+
22+
```typescript
23+
let maxSum = nums[0];
24+
let currentSum = nums[0];
25+
```
26+
27+
### Step 2: 從第二個位置開始遍歷數組
28+
29+
```typescript
30+
for (let i = 1; i < nums.length; i++) {
31+
if (nums[i] > nums[i - 1]) {
32+
// 若持續遞增,則將當前位置加入到當前子數組和中
33+
currentSum += nums[i];
34+
} else {
35+
// 否則重置當前子數組和為當前位置的值
36+
currentSum = nums[i];
37+
}
38+
39+
// 比較當前子數組和與最大子數組和,取最大值
40+
if (currentSum > maxSum) {
41+
maxSum = currentSum;
42+
}
43+
}
44+
```
45+
46+
47+
## 時間複雜度
48+
- 需要訪問每個元素一次,故時間複雜度為 $O(n)$
49+
- 總體時間複雜度為 $O(n)$
50+
51+
> $O(n)$
52+
53+
## 空間複雜度
54+
- 僅使用了常數個變量,故空間複雜度為 $O(1)$
55+
- 總體空間複雜度為 $O(1)$
56+
57+
> $O(1)$
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function maxAscendingSum(nums: number[]): number {
2+
let maxSum = nums[0];
3+
let currentSum = nums[0];
4+
for (let i = 1; i < nums.length; i++) {
5+
if (nums[i] > nums[i - 1]) {
6+
currentSum += nums[i];
7+
} else {
8+
currentSum = nums[i];
9+
}
10+
if (currentSum > maxSum) {
11+
maxSum = currentSum;
12+
}
13+
}
14+
return maxSum;
15+
}

0 commit comments

Comments
 (0)