---
# System prepended metadata

title: L9-MaxProfit
tags: [Codility_lessons]

---

# L9-MaxProfit
###### tags: `Codility_lessons`
## Question
https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/
## Key
- 因為只能做一次交易，所以在遍尋過程中找出最小值記錄下來，元素和它相減後，再確認結果是不是目前最大利潤
- 所以總共紀錄1.最小值 2.最大利潤
- 如果在這段期間(陣列大小)內可以進行不只一次交易怎麼辦?
## Reference
## Solution
```cpp=
int solution(vector<int> &A) {
    // write your code in C++14 (g++ 6.2.0)
    int maxSoFar = 0, maxEndingHere = 0, minPrice = 200000;

    for(int i = 0 ; i < A.size(); i++)
    {
        maxEndingHere = max(0, A[i]-minPrice);
        minPrice = min(minPrice, A[i]);
        maxSoFar = max(maxEndingHere, maxSoFar);
    }
    if(maxSoFar > 0)
    {
        return maxSoFar;
    }
    else
    {
        return 0;
    }
}
```
