• LeetCode53 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. (Medium)

    分析:

    遍历一遍,维护一个当前最大值temp,如果temp < 0,则temp = nums[i](前面的元素和更小,不要加进去), 否则 temp += nums[i];

    然后每个temp更新result.

    代码:

     1 class Solution {
     2 public:
     3     int maxSubArray(vector<int>& nums) {
     4         if (nums.size() == 0) {
     5             return -1;
     6         }
     7         int temp = nums[0], result = nums[0];
     8         for (int i = 1; i < nums.size(); ++i) {
     9             if (temp < 0) {
    10                 temp = nums[i];
    11                 result = max(temp, result);
    12             }
    13             else {
    14                 temp = nums[i] + temp;
    15                 result = max(temp, result);
    16             }
    17         }
    18         return result;
    19     }
    20 };

    题目还有分治和动归的算法,明天再说...

     
  • 相关阅读:
    [USACO12FEB]牛券Cow Coupons
    合并果子
    序列合并
    中位数
    道路游戏
    教主的花园
    摆花
    hello world之Makefile
    mysql+tomcat+spring 配置心得(从0开始搭环境)
    C#,.Net自动生成大写字母编码
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5858203.html
Copyright © 2020-2023  润新知