标签:style == 解决 不清晰 fit i++ 现在 col 越界
思路不是特别难,双指针就能解决问题,写的时候最大的困扰在于边界条件不清晰导致的数组越界。贴暴力代码
class Solution { public: int maxProfit(vector<int>& prices) { int earn = 0; int n = prices.size(); int i = 0; int j = 1; while(i<n-1 && j<n) { while(i<n-1 &&((i == 0 && prices[i]>prices[i+1]) || (i!=0 &&(prices[i]>prices[i-1] || prices[i]>prices[i+1])))) { i++; cout<<"ok?"<<endl; } while(j<n-1 && (j!=n-1 &&(prices[j]<prices[j-1] || prices[j]<prices[j+1]))) { j++; } earn = earn + prices[j] - prices[i]; i = i + 2; j = j + 2; } return earn; } };
擦,这个贪心算法有点牛的,现在看自己的代码简直像一坨屎,贴代码
class Solution { public: int maxProfit(vector<int>& prices) { int earn = 0; int n = prices.size(); for(int i = 0 ; i < n-1 ; i++) { earn += max(0,prices[i+1]-prices[i]); } return earn; } };
标签:style == 解决 不清晰 fit i++ 现在 col 越界
原文地址:https://www.cnblogs.com/zhaohhhh/p/14477143.html