多语言解编程题之最大子串和

字数 105阅读 30

给予一个整数字符串,找出所有连续子串和的最大值。
样例输入:-23 17 -7 11 -2 1 -34
样例输出:21

JavaScript(Node)实现

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', function(line) {
    let str = line;
    let res = findMaxSum(str);
    console.log(res);
});

function findMaxSum(str) {
    let arr = str.split(' ').map(val => +val);
    let len = arr.length;
    let sum = Number.MIN_SAFE_INTEGER;
    let temp;
    for (let i = 0; i < len; i++) {
        temp = 0;
        for (let j = i; j < len; j++) {
            temp += arr[j];
            if (temp > sum) {
                sum = temp;
            }
        }
    }
    return sum;
}

PHP实现

<?php
    $handle = fopen("php://stdin", "r");
    $str = fgets($handle);
    while ($str !== "") {
        echo findMaxSum($str) . "\n";
        $str = fgets($handle);
    }
    fclose($handle);

    function findMaxSum($str) {
        $arr = array_map("intval", explode(" ", $str));
        $len = count($arr);
        $sum = PHP_INT_MIN;
        for ($i = 0; $i < $len; $i++) {
            $temp = 0;
            for ($j = $i; $j < $len; $j++) {
                $temp += $arr[$j];
                if ($temp > $sum) {
                    $sum = $temp;
                }
            }
        }
        return $sum;
    }

C++实现

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <limits>
using namespace std;

int findMaxSum(string s) {
    stringstream iss(s);
    int number;
    vector<int> v;
    while(iss >> number) {
        v.push_back(number);
    }
    int n = v.size();
    int sum = numeric_limits<int>::min();
    int temp;
    for (int i = 0; i < n; i++) {
        temp = 0;
        for (int j = i; j < n; j++) {
            temp += v[j];
            if (temp > sum) {
                sum = temp;
            }
        }
    }
    return sum;
}

int main() {
    string s;
    while (getline(cin, s)) {
        cout << findMaxSum(s) << endl;
    }
    return 0;
}

题目比较简单,主要是熟悉一下各种语言的写法。

以上。

个人技术博客 biebu.xin,原文链接——多语言解编程题之最大子串和

推荐阅读更多精彩内容