力扣
解法1:暴力
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int i=0;
int j=0;
int Tmp=0;
int Max=nums[0];
for(int i=0;i<nums.size();i++){
Tmp=0;
for(int j=i;j<nums.size();j++){
Tmp+=nums[j];
if(Tmp>Max)
Max=Tmp;
}
}
return Max;
}
};
解法2:贪心
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = INT32_MIN;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
if (count > result) {
result = count;
}
if (count <= 0) count = 0;
}
return result;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0;
int n=prices.size();
for(int i=1;i<n;i++)
{
if(prices[i]>prices[i-1])
{
sum+=(prices[i]-prices[i-1]);
}
}
return sum;
}
};