iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
AI & Data

想到甚麼打甚麼系列 第 7

找LeetCode上簡單的題目來撐過30天啦(DAY7)

昨天熬夜看小說,今天早上爬不起來就翹班(開玩笑的,是請假/images/emoticon/emoticon11.gif
今天趕快發一發文我要來去補眠

今天的題目↓

題目:122 標題:Best Time to Buy and Sell Stock II 難度:Medium

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.

Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.


Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.


Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:
• 1 <= prices.length <= 3 * 104
• 0 <= prices[i] <= 104


我的程式碼

int maxProfit(int* prices, int pricesSize){
    int i,mix,max,result=0,flagt=0,flagm=0;
    mix = 10001;
    max = -1;
    for(i=0;i<pricesSize;i++){
        if(flagt== 0){
            if(*prices < mix){
                mix = *prices;
            }else if(*prices > mix){
                max = *prices;
                flagt = 1;
                if(i == pricesSize -1){
                    result = result +  max -mix;
                }
            }
        }else if(flagm == 0){
            if(i == pricesSize -1){
                if(*prices>max){
                    result = result +  *prices -mix;
                }else{
                    result = result + max - mix;
                }
            }else{
                if(max > *prices){
                    result = result + max - mix;
                    mix = *prices;
                    flagt = 0;
                    max = -1; 
                }else{
                    max = *prices;
                } 
            }
        }
        *prices++;
     }
    return result;
}

花比較多時間的地方
看題目,我英文是真滴不好,一開始誤會題目的意思,這題至少改了三次(題意理解了三次才終於懂了)這就是看測資推題目的缺點阿

DAY7心得
寫題目有一部份是想試看看之前沒用過的東西或是邏輯,所以我偏好用跟自己以往習慣不同的方式來解題,這題就不用a[i]的寫法,改成 *a 希望30天內有機會可以多了解一些資料結構跟function


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY6)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY8)
系列文
想到甚麼打甚麼30

尚未有邦友留言

立即登入留言