我試圖實施amazon面試問題。非重疊連續子陣列的最大長度總和
Find the maximum sum of lengths of non-overlapping contiguous subarrays with k as the maximum element. Ex: Array: {2,1,4,9,2,3,8,3,4} and k = 4 Ans: 5 {2,1,4} => Length = 3 {3,4} => Length = 2 So, 3 + 2 = 5 is the answer
我有執行程序:
#include <iostream>
using namespace std;
int main()
{
int a[] = {2,1,4,9,2,3,8,3,4,2};
int cnt = 0, i = 0, j = 0, ele, k = 4;
int tmp = 0, flag = 0;
ele = sizeof(a)/sizeof(a[0]);
for(j = 0; j < ele;)
{
i = j;
//while(i < ele && a[i++] <= k) //It's working fine
while(a[i] <= k && i++ < ele) // It's not work
{
cnt++;
cout<<"while"<<endl;
}
while(j < i)
{
if(a[j++] == k)
{
flag = 1;
}
}
if(flag == 1)
{
tmp += cnt;
flag = 0;
}
cnt = 0;
j = i;
}
cout<<"count : "<<tmp<<endl;
return 0;
}
在我的計劃,我用
while(i < ele && a[i++] <= k)
它的正常工作,並給出正確的輸出。
但是,如果我使用
while(a[i] <= k && i++ < ele)
然後我的程序卡住。爲什麼?
[OT]:你可以簡化你的代碼,就像[that](http://ideone.com/fj8JvB) – Jarod42