日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetCode 53. maximum subarray

發(fā)布時間:2023/12/9 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetCode 53. maximum subarray 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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.

?

貪婪算法找每個當前位置對應的最大的subarray,?

class Solution { public:int maxSubArray(vector<int>& nums) {int n=nums.size();vector<int> eachnum;int sum=0;for(int i=0;i<n;i++){if(sum<0){sum=0;}sum+=nums[i];eachnum.push_back(sum);cout<<sum<<endl;// eachnum[i]=sum;}vector<int>:: iterator biggest=max_element(eachnum.begin(),eachnum.end());return *biggest;} };

  

更簡單的方法,記錄當前最大的結果,因為每遇到一個數,可能有兩種可能,一是加這個數,二是從這個數開始。 那我們就要找當前的最優(yōu)情況與歷史最優(yōu)情況比較。

和可能的結果:

class Solution { public:int maxSubArray(vector<int>& nums) {int adj_sum = 0;int cont_sum = nums[0];for (vector<int>::iterator it = nums.begin(); it<nums.end(); it++){adj_sum+=*it;adj_sum = max(adj_sum, *it);//記錄加當前數與從當前數開始的最大值cont_sum = max(cont_sum, adj_sum);// 比較當前的最大值與歷史最大值,記錄最大值}return cont_sum;} };

  

?

這是一個最優(yōu)化問題,最優(yōu)化問題一般都可以用DP(動態(tài)規(guī)劃)解決。 對于動態(tài)規(guī)劃,要考慮子問題是什么(形式的子問題或狀態(tài)的子問題)子問題就可以用recursive solution。

  • 對于 maxSubArray( int a[], int i,int j), is searching for the maxSubArray for a[i:j]
  • the goal is to figure out what maxSubArray(A,0,A.length()-1) is.
  • 對于maxSubArray(int a[], int i, int j) is difficult ot connect this sub problem to the original, so we change the format of the sub problem to maxSubArray(int a[], int i), which means the maxSubArray for A[0:i]. which must has A[i] as the end. so we should keep track of each solution of the sub problem to update the global optimal value.
  • maxSubArray(A,i)=maxSubArray(A, i-1)>0?maxSubArray(A, i-1):0+A[i];

    so the solution is same as the previous one:

    int maxSubArray(vector<int> & nums){int n=nums.size();int num=0;int* dp=new int[n];dp[0]=nums[0];int maxsum=nums[0];for (int i=1;i<n;i++){if(dp[i-1]<0)dp[i]=nums[i];elsedp[i]=dp[i-1]+nums[i];cout<<dp[i]<<" "<<dp[i-1]<<endl;maxsum=max(maxsum,dp[i]);cout<<maxsum<<endl;}return maxsum; }

      開始寫 dp[i]=nums[i]+dp[i-1]>0?dp[i-1]:0; ?有錯哈哈, 忘了帶括號

    ? ? ? ? ? ? ? ? ? ?dp[i]=nums[i]+(dp[i-1]>0?dp[i-1]:0);?

    ?

    轉載于:https://www.cnblogs.com/fanhaha/p/7222002.html

    總結

    以上是生活随笔為你收集整理的leetCode 53. maximum subarray的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。