1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 if (nums.size() == 0) return 0; 5 else { 6 int result = nums[0]; int sum = nums[0]; 7 for (int i = 1; i < static_cast<int>(nums.size()); ++i) { 8 if (sum < 0) sum = nums[i]; 9 else sum += nums[i]; 10 result = max(result, sum); 11 } 12 return result; 13 } 14 } 15 };
方法二:动态规划
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 if (nums.size() == 0) return 0; 5 else { 6 int result = INT_MIN, f = 0; 7 for (int i = 0; i < static_cast<int>(nums.size()); ++ i) { 8 f = max(f + nums[i], nums[i]); 9 result = max(result, f); 10 } 11 return result; 12 } 13 } 14 };
时间: 2024-11-17 18:00:16