1. 程式人生 > >LeetCode 53. Maximum Subarray

LeetCode 53. Maximum Subarray

script none div out array emp 我們 pac display

https://leetcode.com/problems/maximum-subarray/description/

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.

  • 第一個算法用動態規劃。設f[i]表示第j處,以a[i]結尾的子序列的最大和。註意:f[i]並不是前i-1個數中最大的連續子序列之和,而只是包含a[i]的最大連續子序列的和。我們求出f[i]中的最大值,即為所求的最大連續子序列的和。
  • 狀態轉移方程:f[i] = max{ a[i], f[i - 1] + a[i] }, target = max { f[i] }。
技術分享
 1 //
 2 //  main.cpp
 3 //  LeetCode
 4 //
 5 //  Created by Hao on 2017/3/16.
 6 //  Copyright © 2017年 Hao. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include <vector>
11 using namespace std;
12 
13
class Solution { 14 public: 15 int maxSubArray(vector<int>& nums) { 16 // empty array 17 if (nums.empty()) return 0; 18 19 int result = nums.at(0), f = 0; 20 21 for (auto i = 0; i < nums.size(); i ++) { 22 // f[i] = max{ a[i], f[i - 1] + a[i] }
23 f = max(f + nums.at(i), nums.at(i)); 24 25 // target = max { f[i] } 26 result = max(result, f); 27 } 28 29 return result; 30 } 31 }; 32 33 int main () 34 { 35 Solution testSolution; 36 37 vector< vector<int> > vecTest{ {-2, 5, 3, -6, 4, -8, 6}, {}, {1, 2, 3, 4, 5} }; 38 39 for (auto v : vecTest) 40 cout << testSolution.maxSubArray(v) << endl; 41 42 return 0; 43 }
View Code

LeetCode 53. Maximum Subarray