程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> (LeetCode OJ) Maximum Subarray【53】

(LeetCode OJ) Maximum Subarray【53】

編輯:關於C++

53. Maximum Subarray

My SubmissionsTotal Accepted: 89899 Total Submissions: 253014 Difficulty: Medium

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.

click to show more practice.

Subscribe to see which companies asked this question

Hide Tags Divide and Conquer Array Dynamic Programming Show Similar Problems
//典型的動態規劃問題:
//思路首先:
//很顯然在連續累加的過程中,加了nums[i]如果sum是小於0的,那麼說明前一次計算出的sums其副作用,需要重新尋找起始開始累加
//即重新以當前nums[i]為起始值開始累加
class Solution {
public:
    int maxSubArray(vector& nums) {
        int maxSum = nums[0];//記錄累加過程中的最大值
        int subSum = nums[0];
        for(int i = 1; i < nums.size(); i++)
        {
            subSum = subSum <= 0? nums[i] : subSum+nums[i];
            if(subSum > maxSum) 
                maxSum = subSum;
        }
        return maxSum;
    }
};
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved