演算法:給你一個整數陣列 nums(至少包含一個元素),請你找出一個具有最大和的連續子陣列(至少包含一個元素),返回其最大和。
本文用 c、c++、python、java、kotlin、swift、js、rust、go 9種主流程式語言實現。基於貪心演算法實現。
演算法原理:遍歷陣列,並計算包含當前元素的子序列和,若當前元素之前的序列和小於0,則丟棄當前元素之前的數列。
C
#include <stdio.h>
int maxSubArray(int* nums, int numsSize) {
int max_sum = nums[0];
int current_sum = nums[0];
for (int i = 1; i < numsSize; i++) {
current_sum = current_sum > 0 ? current_sum + nums[i] : nums[i];
if (current_sum > max_sum) {
max_sum = current_sum;
}
}
return max_sum;
}
int main() {
int nums[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int size = sizeof(nums) / sizeof(nums[0]);
printf("Max Subarray Sum: %d\n", maxSubArray(nums, size));
return 0;
}
C++
#include <iostream>
#include <vector>
using namespace std;
int maxSubArray(vector<int>& nums) {
int max_sum = nums[0];
int current_sum = nums[0];
for (int i = 1; i < nums.size(); i++) {
current_sum = max(current_sum + nums[i], nums[i]);
max_sum = max(max_sum, current_sum);
}
return max_sum;
}
int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << "Max Subarray Sum: " << maxSubArray(nums) << endl;
return 0;
}
## Python
def max_sub_array(nums):
max_sum = current_sum = nums[0]
for num in nums[1:]:
current_sum = max(current_sum + num, num)
max_sum = max(max_sum, current_sum)
return max_sum
Example usage
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Max Subarray Sum:", max_sub_array(nums))
Java
public class MaxSubArray {
public static int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(currentSum + nums[i], nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Max Subarray Sum: " + maxSubArray(nums));
}
}
Kotlin
fun maxSubArray(nums: IntArray): Int {
var maxSum = nums[0]
var currentSum = nums[0]
for (i in 1 until nums.size) {
currentSum = maxOf(currentSum + nums[i], nums[i])
maxSum = maxOf(maxSum, currentSum)
}
return maxSum
}
fun main() {
val nums = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)
println("Max Subarray Sum: ${maxSubArray(nums)}")
}
Swift
func maxSubArray(_ nums: [Int]) -> Int {
var maxSum = nums[0]
var currentSum = nums[0]
for num in nums[1...] {
currentSum = max(currentSum + num, num)
maxSum = max(maxSum, currentSum)
}
return maxSum
}
// Example usage
let nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Max Subarray Sum: \(maxSubArray(nums))")
JavaScript
function maxSubArray(nums) {
let maxSum = nums[0];
let currentSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(currentSum + nums[i], nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
// Example usage
const nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
console.log("Max Subarray Sum:", maxSubArray(nums));
Rust
fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut max_sum = nums[0];
let mut current_sum = nums[0];
for &num in &nums[1..] {
current_sum = current_sum.max(current_sum + num).max(num);
max_sum = max_sum.max(current_sum);
}
max_sum
}
fn main() {
let nums = vec![-2, 1, -3, 4, -1, 2, 1, -5, 4];
println!("Max Subarray Sum: {}", max_sub_array(nums));
}
Go
package main
import "fmt"
func maxSubArray(nums []int) int {
maxSum := nums[0]
currentSum := nums[0]
for _, num := range nums[1:] {
currentSum = max(currentSum+num, num)
maxSum = max(maxSum, currentSum)
}
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
nums := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
fmt.Println("Max Subarray Sum:", maxSubArray(nums))
}