标签:最大值 for pac imu code iostream def names target
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
.
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 }
标签:最大值 for pac imu code iostream def names target
原文地址:http://www.cnblogs.com/pegasus923/p/7572061.html