Best Time to Buy and Sell Stock II

来源:互联网 发布:元数据是关于数据的 编辑:程序博客网 时间:2024/05/02 02:35

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


int maxProfitMulti(int *prices, int n) {    int i, j, sum = 0;    if(n == 0) return 0;    for(i = 0 ;i < n - 1; i++ ) {        if(prices[i + 1] > prices[i]) {            for(j = i; j < n - 1 && prices[j] < prices[j + 1]; j++);            if(j != i ) {                sum += prices[j] - prices[i];                //printf("%d\n", sum);            }            i = j;        }    }    return sum;}void main() {    int prices[] = {1,2};    int n = 2;    printf("%d\n", maxProfitMulti(prices, n));}


0 0
原创粉丝点击