Leetcodes Solutions 53 Maximum Subarray

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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

當sum小於0,則重置為0

相當數組從這裡重新開始計和

class Solution{public: int maxSubArray(vector<int>& nums){ int n = nums.size(); int ans = nums[0], i, j, sum = 0; for(i = 0; i < n; i++){ sum += nums[i]; ans = max(sum, ans); sum = max(sum, 0); } return ans; }};

推薦閱讀:

Leetcodes Solutions 18 4Sum
演算法集錦(7)| 實用代碼 | Google Colab使用及配置技巧
「中國芯」雄起!阿里達摩院自主研發AI晶元
一名業餘選手的2018天梯+藍橋省賽心得體會
一個帶限制條件的均勻洗牌問題

TAG:演算法 | 編程 | 數據結構 |