-
Notifications
You must be signed in to change notification settings - Fork 2
/
maximum-sum-circular-subarray.rs
48 lines (39 loc) · 1.33 KB
/
maximum-sum-circular-subarray.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#![allow(dead_code, unused, unused_variables, non_snake_case)]
use std::vec;
fn main() {}
struct Solution;
impl Solution {
/// 取反,求最小和的连续子数组,则其余是最大和
/// 两种情况:1.最大和子数组在数组中间
/// 2.最大和子数组在数组两边,在数组两边就是最小和数组在中间
pub fn max_subarray_sum_circular(mut nums: Vec<i32>) -> i32 {
let mut result = nums[0];
let mut last = nums[0];
let mut all_positive = last < 0; // 是否全是负数, 如果全是负数的话,就不能探究第二种情况
// 第一种情况
for i in 1..nums.len() {
if last > 0 {
last += nums[i];
} else {
last = nums[i];
}
all_positive = all_positive && nums[i] < 0;
result = result.max(last);
}
if all_positive {
return result;
}
// 第二种情况
let mut sum: i32 = nums.iter().map(|x| *x).sum();
let mut last = nums[0];
for i in 1..nums.len() {
if last > 0 {
last = nums[i];
} else {
last += nums[i];
}
result = result.max(sum - last);
}
result
}
}