美文网首页
寻找数组中的连续子序列的最大值

寻找数组中的连续子序列的最大值

作者: juexin | 来源:发表于2017-03-28 15:49 被阅读0次

**Maximum Subarray **(最基本的)
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int maxSum = nums[0];
        int cur = nums[0];
        for(int i=1;i<nums.size();i++)
        {
            cur = max(cur+nums[i],nums[i]);
            maxSum = max(maxSum,cur);
        }
        return maxSum;
    }
};

**Maximum Product Subarray **(乘积,分正负)
Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int minP = nums[0];
        int maxP = nums[0];
        int a = nums[0];
        int b = nums[0];
        int maxProduct = nums[0];
        for(int i=1;i<nums.size();i++)
        {
            a = nums[i]*minP;
            b = nums[i]*maxP;
            minP = min(min(a,b),nums[i]);
            maxP = max(max(a,b),nums[i]);
            maxProduct = max(maxProduct,maxP);
        }
        return maxProduct;
    }
};

相关文章

  • 寻找数组中的连续子序列的最大值

    **Maximum Subarray **(最基本的)Find the contiguous subarray w...

  • 刷题目录

    数组 滑动窗口的最大值 连续子数组的最大和 最大乘积子序列 树 二叉树的先序、中序、后序遍历-递归和非递归 排序 ...

  • DP问题求解(二)连续子序列

    DP问题求解之连续子序列 continous subarrays类型问题是求数组中连续子序列是否满足某些条件的类型...

  • 485. Max Consecutive Ones

    485[思路]: 寻找0.1序列中连续为1的子序列的长度; 遍历一次,统计;

  • #常见面试算法题

    阅读目录 *求数组最大连续子序列之和 1.求数组最大连续子序列之和 一个有N个元素的整型数组arr,有正有负,数组...

  • 连续子数组的最大和

    题目:输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。...

  • 剑指Offer Java版 面试题42:连续子数组的最大和

    题目:输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。...

  • 46_连续子数组的最大和

    要求:输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。...

  • 连续子数组的最大和

    题目: 输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值...

  • 剑指offer 42 找最大子数列

    输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 动态...

网友评论

      本文标题:寻找数组中的连续子序列的最大值

      本文链接:https://www.haomeiwen.com/subject/fkijottx.html