We can use sliding window technique to solve this problem in O(n) time. The answer of the question given below: #include<bits/stdc++.h> using namespace std; int main() { optimize(); int arr[6]= {7,6,4,3,1,8}; int n=arr[0],mx=0; for(int i=1; i<6; i++) { if(arr[i]>n) { int x = arr[i]-n; mx = max(mx,x); } else { n = arr[i]; } } cout<<mx<<endl; return 0; } Time Complexity: O(n) Space Complexity: O(1) Question Link: Best Time to Buy and Sell Stock - LeetCode