C++动态规划计算最大子数组

目录
  • 例题
  • 1.求最大的子数组的和
  • 2.求和最大的相应子数组

例题

题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。

1.求最大的子数组的和

代码【C++】

#include <iostream>
using namespace std;
/
// Find the greatest sum of all sub-arrays
// Return value: if the input is valid, return true, otherwise return false
/
bool FindGreatestSumOfSubArray
    (
    int *pData,           // an array
    unsigned int nLength, // the length of array
    int &nGreatestSum     // the greatest sum of all sub-arrays
    )
{
    // if the input is invalid, return false
    if((pData == NULL) || (nLength == 0))
        return false;
    int nCurSum = nGreatestSum = 0;
    for(unsigned int i = 0; i < nLength; ++i)
    {
        nCurSum += pData[i];
        // if the current sum is negative, discard it
        if(nCurSum < 0)
            nCurSum = 0;
        // if a greater sum is found, update the greatest sum
        if(nCurSum > nGreatestSum)
            nGreatestSum = nCurSum;
    }
    // if all data are negative, find the greatest element in the array
    if(nGreatestSum == 0)
    {
        nGreatestSum = pData[0];
        for(unsigned int i = 1; i < nLength; ++i)
        {
            if(pData[i] > nGreatestSum)
                nGreatestSum = pData[i];
        }
    }
    return true;
}
int main()
{
    int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};
    int iGreatestSum;
    FindGreatestSumOfSubArray(arr, sizeof(arr)/sizeof(int), iGreatestSum);
    cout << iGreatestSum << endl;
    return 0;
}

结果

2.求和最大的相应子数组

代码【C++】

#include <iostream>
using namespace std;
/
// Find the greatest sum of all sub-arrays
// Return value: if the input is valid, return true, otherwise return false
/
bool FindGreatestSumOfSubArray
    (
    int *pData,           // an array
    unsigned int nLength, // the length of array
    int &nGreatestSum,    // the greatest sum of all sub-arrays
    int &start,                            // Added
    int &end                            // Added
    )
{
    // if the input is invalid, return false
    if((pData == NULL) || (nLength == 0))
        return false;
    int nCurSum = nGreatestSum = 0;
    int curStart = 0, curEnd = 0;        // Added
    start = end = 0;                    // Added
    for(unsigned int i = 0; i < nLength; ++i)
    {
        nCurSum += pData[i];
        curEnd = i;                        // Added
        // if the current sum is negative, discard it
        if(nCurSum < 0)
        {
            nCurSum = 0;
            curStart = curEnd = i + 1;    // Added
        }
        // if a greater sum is found, update the greatest sum
        if(nCurSum > nGreatestSum)
        {
            nGreatestSum = nCurSum;
            start = curStart;            // Added
            end = curEnd;                // Added
        }
    }
    // if all data are negative, find the greatest element in the array
    if(nGreatestSum == 0)
    {
        nGreatestSum = pData[0];
        start = end = 0;                // Added
        for(unsigned int i = 1; i < nLength; ++i)
        {
            if(pData[i] > nGreatestSum)
            {
                nGreatestSum = pData[i];
                start = end = i;        // Added
            }
        }
    }
    return true;
}
int main()
{
    int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};
    int iGreatestSum, start, end;
    FindGreatestSumOfSubArray(arr, sizeof(arr)/sizeof(int), iGreatestSum,
        start, end);
    cout << iGreatestSum << ": ";
    for(int i = start; i <= end; i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}

结果

到此这篇关于C++动态规划计算最大子数组的文章就介绍到这了,更多相关C++最大子数组内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++动态规划实现查找最长公共子序列

    目录 最长公共子序列 代码实现 结果 最长公共子序列 最长公共子序列(LCS)是一个在一个序列集合中(通常为两个序列)用来查找所有序列中最长子序列的问题.一个数列 ,如果分别是两个或多个已知数列的子序列,且是所有符合此条件序列中最长的,则称为已知序列的最长公共子序列. 动态规划: 采用二维数组flag来记录下标i和j的走向.数字"1"表示,斜向下:数字"2"表示,水平向右:数字"3"表示,竖直向下 问题描述: 设有字符串a[0…n],b[0…m]

  • C++编辑距离(动态规划)

    题目描述: 给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 . 我们可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 编辑距离:是指两个字符串之间,由一个转成另一个所需的最少编辑操作次数.问题:word1到word2的编辑距离子问题:word1前i个字符到word2前j个字符的编辑距离假如有两个字符串"hat"和"wtct"每个格子表示word1前i个字符到word2前j个字符的编

  • C++实现LeetCode(152.求最大子数组乘积)

    [LeetCode] 152. Maximum Product Subarray 求最大子数组乘积 Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has

  • C++动态规划之背包问题解决方法

    本文实例讲述了C++动态规划之背包问题解决方法.分享给大家供大家参考.具体分析如下: 问题描述: 背包的最大容量为W,有N件物品,每件物品重量为w,价值为p,怎样选择物品能使得背包里的物品价值最大? 输入: 10 3   (W,N) 4 5   (w,p) 6 7   (w,p) 8 9   (w,p) 实现代码: #include <stdio.h> #define THING 20 #define WEIGHT 100 int arr[THING][WEIGHT]; /* 背包容量为wei

  • C++实现LeetCode(53.最大子数组)

    [LeetCode] 53. Maximum Subarray 最大子数组 Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1]

  • C++ 动态规划算法使用分析

    目录 Fibonacci 字符串分割(Word Break) 三角矩阵(Triangle) 路径总数(Unique Paths) 最小路径和(Minimum Path Sum) Fibonacci 题目描述: 大家都知道斐波那契数列,现在要求输入一个正整数 n ,请你输出斐波那契数列的第 n 项. 解题思路: 1.递归 2.动态规划 状态:F(n) 状态递推:F(n)=F(n-1)+F(n-2) 初始值:F(1)=F(2)=1 返回结果:F(N) 代码实现: 法一:递归(效率低): class

  • C++动态规划算法实现矩阵链乘法

    问题描述: 给定n个矩阵的链<A1,A2,…,An>,矩阵Ai的规模为p(i-1)×p(i) (1<=i<=n),求完全括号化方案,使得计算乘积A1A2…An所需标量乘法次数最少. 动态规划的第一步是寻找最优子结构,然后就可以利用这种子结构从子问题的最优解构造出原问题的最优解.在矩阵链乘法问题中,我们假设A(i)A(i+1)…A(j)的最优括号方案的分割点在A(k)和A(k+1)之间.那么,继续对“前缀”子链A(i)A(i+1)…A(k)进行括号化时,我们应该直接采用独立求解它时所

  • C++动态规划之最长公子序列实例

    本文实例讲述了C++动态规划之最长公子序列解决方法.分享给大家供大家参考.具体分析如下: 问题描述: 求出两个字符串中的最长公子序列的长度. 输入: csblog belong 输出: max length = 4 实现代码: #include <stdio.h> #include <string.h> int arr[200][200]; /* 表示str1的前i位和str2的前j位的最长公子序列的长度 */ int main() { char str1[100],str2[10

  • c++动态规划经典算法

    目录 基本思想 重要分析问题方法 动态规划算法实例 1.台阶问题 2.从矩阵左上角走到右下角最短路径问题 3.最大子数组问题 4.最长公共子序列 基本思想 动态规划算法通常用于求解具有某种最优性质的问题.在这类问题中,可能会有许多可行解.每一个解都对应于一个值,我们希望找到具有最优值的解.动态规划算法与分治法类似,其基本思想也是将待求解问题分解成若干个子问题,先求解子问题,然后从这些子问题的解得到原问题的解.与分治法不同的是,适合于用动态规划求解的问题,经分解得到子问题往往不是互相独立的.若用分

  • C++动态规划计算最大子数组

    目录 例题 1.求最大的子数组的和 2.求和最大的相应子数组 例题 题目:输入一个整形数组,数组里有正数也有负数.数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和.求所有子数组的和的最大值.要求时间复杂度为O(n). 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18. 1.求最大的子数组的和 代码[C++] #include <iostream> using namespace std

  • 求最大子数组之和的方法解析(2种可选)

    问题描述:一个有n个元素的数组,这n个元素可以是正数也可以是负数,求最大子数组的和. 方法1:蛮力法 思路:最简单也是最容易想到的方法就是找出所有子数组,然后求所有子数组的和,在所有子数组的和中取最大值. /** * 方法1(蛮力法):两次循环求最大子数组之和 */ public static int maxSubArray1(int[] a){ int i,j; int ThisSum=0; int MaxSum=0; for (i = 0; i < a.length; i++) { This

  • Javascript计算二维数组重复值示例代码

    前言 最近工作中遇到了一个问题,需求是利用Javascript计算二维数组重复值,如下面有个二维数组 [[\'error\',3],[\'error\',5],[\'error\',6],[\'true\',3],[\'true\',1]] 需要统计计算重复项 \'error\' 和 \'true\', 统计计算之后的结果: [[\'error\',14],[\'true\',4]] 实现代码: var arr = [[\'error\',3],[\'error\',5],[\'error\',

  • php计算多维数组中所有值总和的方法

    本文实例讲述了php计算多维数组中所有值总和的方法.分享给大家供大家参考.具体实现方法如下: php 内置函数 array_sum() 函数返回数组中所有值的总和,只能返回一维数组的总和: 计算多维数组所有值的和就要自定义函数了: function get_sum($array) { $num = 0; foreach($array as $k => $v) { if(is_array($v)) { $num += get_sum($v); } } return $num + array_sum

  • PHP编程计算文件或数组中单词出现频率的方法

    本文实例讲述了PHP编程计算文件或数组中单词出现频率的方法.分享给大家供大家参考,具体如下: 如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词): <?php $str = file_get_contents("/path/to/file.txt"); //get string from file preg_match_all("/\b(\w+[-]\w+)|(\w+)\b/",$str,$r); //

  • C语言求连续最大子数组和的方法

    本文实例讲述了C语言求连续最大子数组和的方法,是非常实用的技巧.分享给大家供大家参考. 具体实现方法如下: #include <iostream> using namespace std; int array[] = {1, -2, 3, 10, -4, 7, 2, -5}; //int array[] = {-10, -1, -2, -3, -4, -5}; const int size = sizeof array / sizeof *array; int maxSubArray(int

  • JS计算两个数组的交集、差集、并集、补集(多种实现方式)

    方法一:最普遍的做法 使用 ES5 语法来实现虽然会麻烦些,但兼容性最好,不用考虑浏览器 JavaScript 版本.也不用引入其他第三方库. 1,直接使用 filter.concat 来计算 var a = [1,2,3,4,5] var b = [2,4,6,8,10] //交集 var c = a.filter(function(v){ return b.indexOf(v) > -1 }) //差集 var d = a.filter(function(v){ return b.index

  • Python3实现计算两个数组的交集算法示例

    本文实例讲述了Python3实现计算两个数组的交集算法.分享给大家供大家参考,具体如下: 问题: 给定两个数组,写一个方法来计算它们的交集. 方案一:利用collections.Counter的&运算,一步到位,找到 最小次数 的相同元素. # -*- coding:utf-8 -*- #! python3 def intersect(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :r

  • numpy 计算两个数组重复程度的方法

    最近有个需求,是做两个数组重复程度计算,麻烦就麻烦在单个数组的元素有可能重复,处理思路如下: 1. 找到重复元素 2. 元素个数统计,利用np.bincount转换,即元素个数统计到元素转化的索引 3. 统计相同元素匹配个数 具体代码如下: # arr1, arr2都是np.array类型 # 找到重复元素(交集) inters = np.intersect1d(arr1, arr2) # 元素个数索引转换 bc1 = np.bincount(arr1) bc2 = np.bincount(ar

随机推荐