# 面試_子數組類問題

## 劍指 Offer 42. 連續子數組的最大和

``````1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
``````
``````class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = -999, t = 0;
for (const auto& e : nums)
{
// if (t <= 0) {
//     t = e;
// } else {
//     t += e;
// }
t = max(t + e, e);
ans = max(ans, t);
}
return ans;
}
};
``````

## 152. 乘積最大子數組

``````1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums 的任何前綴或後綴的乘積都 保證 是一個 32-位 整數
``````

``````class Solution {
public:
int maxProduct(vector<int>& nums) {
int p_max = 1, p_min = 1;
int ans = -999;
for (const auto& e : nums)
{
int max_tmp = p_max, min_tmp = p_min;
p_max = max(max(max_tmp * e, e), min_tmp * e);
p_min = min(min(max_tmp * e, e), min_tmp * e);
ans = max(ans, p_max);
}

return ans;
}
};
``````

## 300. 最長遞增子序列

``````提示：
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
``````

``````class Solution {
public:
//
int lengthOfLIS(vector<int>& nums) {
int ans = 1;
int nlen = nums.size();
vector<int> dp(nlen, 1);
for(int i = 1; i < nlen; ++i)
{
for (int j = 0; j < i; ++j)
{
if (nums[j] < nums[i]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
if (ans < dp[i]) {
ans = dp[i];
}
}
return ans;
}
};
``````

``````class Solution {
public:
int lengthOfLIS(vector<int>& nums)
{
int nlen = nums.size();
int ans = 0;
vector<int> tails(nlen, 0);
for(const auto& num : nums)
{
int i = 0, j = ans;
while(i < j)
{
int mid = (i + j) / 2;
if (tails[mid] < num) {
i = mid + 1;
} else {
j = mid;
}
}
tails[i] = num;
if(j == ans) {
ans += 1;
}
}
return ans;
}

};
``````