劍指offer 30 : 連續子陣列的最大和
阿新 • • 發佈:2018-12-30
1 兩次遍歷 尋找最大和
2 貪心思想,sum為負數,sum為當前值, sum大於0,為sum加當前值; 如果全為負數,找到最大的一個負數
//連續子陣列的最大和 int FindGreatSum(vector<int> array) { if (array.size() == 0) { return 0; } int sum = 0 , maxsum = 0; for (int i = 0; i < array.size(); i++) { sum = 0;//每次一開始重置0 for(int j = i; j < array.size(); j++) { sum = sum + array[j]; if (sum > maxsum) { maxsum = sum; cout << maxsum << endl; } } } return maxsum; } //貪心思想 int FindGreatSum2(vector<int> array) { if (array.size() == 0) { return 0; } int sum = 0, maxsum = -100, maxnum = -10000; for (int i = 0; i < array.size(); i++) { if (sum <= 0) { sum = array[i];//和小於0,和就為當前數 } else { sum = sum + array[i];//大於0,加上當前數 } if (sum > maxsum) { maxsum = sum; } if (array[i] > maxnum) { // 全負數情況 maxnum = array[i]; } } return (maxnum < 0 ) ? maxnum : maxsum; }