標籤:blog java io 2014 art for
原始題目例如以下,意為尋找數組和最大的子串,返回這個最大和就可以。
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.
最普通的方法就是兩層迴圈來尋找,複雜度為O(n^2).
在木易先森的指導下,有一個極其簡單的O(n)複雜度的方法:
- 先找出數組max值,假設max小於0 ,啥也別說了,直接返回max.
- 設定輔助變數currentmax=0;數組從頭至尾掃描一遍
- 假設currentmax + A[i] <= 0,意味著這個子串對於我們尋找最大和是沒有不論什麼協助的,此時,直接再置currentmax = 0
- 假設currentmax + A[i] > 0,意味著這個子串的和是有意義的,將這個和跟max比較,時刻保持max的值是當前最理想的最大值
- 最後返回max就可以
源碼例如以下:
public class Solution { public static int maxSubArray(int[] A) { if(A.length == 0) return 0; int max = A[0]; for(int i = 0; i < A.length; i ++) if(A[i] > max) max = A[i]; if(max <= 0) return max; int currentmax = 0; for(int i = 0;i < A.length; i ++){ currentmax += A[i]; if(currentmax <= 0){ currentmax = 0; continue; } else{ if(currentmax > max) max = currentmax; } } return max; }}