2018秋招面试记录
作业帮笔试 leetcode 53 Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.empty()) { return -1; } int n = nums.size(); int max_val = nums[0]; int cur_max = 0; for (int i = 0; i < n; i++) { // 这样一来每次还会比较每个值的大小, 如果数组所有值为负数的话 cur_max += nums[i]; max_val = max(max_val, cur_max); cur_max = max(cur_max, 0); // 很优秀 } return max_val; } }